Merge branch 'MDL-64201-master' of https://github.com/lucaboesch/moodle
[moodle.git] / course / tests / externallib_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * External course functions unit tests
19  *
20  * @package    core_course
21  * @category   external
22  * @copyright  2012 Jerome Mouneyrac
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
32 /**
33  * External course functions unit tests
34  *
35  * @package    core_course
36  * @category   external
37  * @copyright  2012 Jerome Mouneyrac
38  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  */
40 class core_course_externallib_testcase extends externallib_advanced_testcase {
42     /**
43      * Tests set up
44      */
45     protected function setUp() {
46         global $CFG;
47         require_once($CFG->dirroot . '/course/externallib.php');
48     }
50     /**
51      * Test create_categories
52      */
53     public function test_create_categories() {
55         global $DB;
57         $this->resetAfterTest(true);
59         // Set the required capabilities by the external function
60         $contextid = context_system::instance()->id;
61         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
63         // Create base categories.
64         $category1 = new stdClass();
65         $category1->name = 'Root Test Category 1';
66         $category2 = new stdClass();
67         $category2->name = 'Root Test Category 2';
68         $category2->idnumber = 'rootcattest2';
69         $category2->desc = 'Description for root test category 1';
70         $category2->theme = 'bootstrapbase';
71         $categories = array(
72             array('name' => $category1->name, 'parent' => 0),
73             array('name' => $category2->name, 'parent' => 0, 'idnumber' => $category2->idnumber,
74                 'description' => $category2->desc, 'theme' => $category2->theme)
75         );
77         $createdcats = core_course_external::create_categories($categories);
79         // We need to execute the return values cleaning process to simulate the web service server.
80         $createdcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdcats);
82         // Initially confirm that base data was inserted correctly.
83         $this->assertEquals($category1->name, $createdcats[0]['name']);
84         $this->assertEquals($category2->name, $createdcats[1]['name']);
86         // Save the ids.
87         $category1->id = $createdcats[0]['id'];
88         $category2->id = $createdcats[1]['id'];
90         // Create on sub category.
91         $category3 = new stdClass();
92         $category3->name = 'Sub Root Test Category 3';
93         $subcategories = array(
94             array('name' => $category3->name, 'parent' => $category1->id)
95         );
97         $createdsubcats = core_course_external::create_categories($subcategories);
99         // We need to execute the return values cleaning process to simulate the web service server.
100         $createdsubcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdsubcats);
102         // Confirm that sub categories were inserted correctly.
103         $this->assertEquals($category3->name, $createdsubcats[0]['name']);
105         // Save the ids.
106         $category3->id = $createdsubcats[0]['id'];
108         // Calling the ws function should provide a new sortorder to give category1,
109         // category2, category3. New course categories are ordered by id not name.
110         $category1 = $DB->get_record('course_categories', array('id' => $category1->id));
111         $category2 = $DB->get_record('course_categories', array('id' => $category2->id));
112         $category3 = $DB->get_record('course_categories', array('id' => $category3->id));
114         // sortorder sequence (and sortorder) must be:
115         // category 1
116         //   category 3
117         // category 2
118         $this->assertGreaterThan($category1->sortorder, $category3->sortorder);
119         $this->assertGreaterThan($category3->sortorder, $category2->sortorder);
121         // Call without required capability
122         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
123         $this->expectException('required_capability_exception');
124         $createdsubcats = core_course_external::create_categories($subcategories);
126     }
128     /**
129      * Test delete categories
130      */
131     public function test_delete_categories() {
132         global $DB;
134         $this->resetAfterTest(true);
136         // Set the required capabilities by the external function
137         $contextid = context_system::instance()->id;
138         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
140         $category1  = self::getDataGenerator()->create_category();
141         $category2  = self::getDataGenerator()->create_category(
142                 array('parent' => $category1->id));
143         $category3  = self::getDataGenerator()->create_category();
144         $category4  = self::getDataGenerator()->create_category(
145                 array('parent' => $category3->id));
146         $category5  = self::getDataGenerator()->create_category(
147                 array('parent' => $category4->id));
149         //delete category 1 and 2 + delete category 4, category 5 moved under category 3
150         core_course_external::delete_categories(array(
151             array('id' => $category1->id, 'recursive' => 1),
152             array('id' => $category4->id)
153         ));
155         //check $category 1 and 2 are deleted
156         $notdeletedcount = $DB->count_records_select('course_categories',
157             'id IN ( ' . $category1->id . ',' . $category2->id . ',' . $category4->id . ')');
158         $this->assertEquals(0, $notdeletedcount);
160         //check that $category5 as $category3 for parent
161         $dbcategory5 = $DB->get_record('course_categories', array('id' => $category5->id));
162         $this->assertEquals($dbcategory5->path, $category3->path . '/' . $category5->id);
164          // Call without required capability
165         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
166         $this->expectException('required_capability_exception');
167         $createdsubcats = core_course_external::delete_categories(
168                 array(array('id' => $category3->id)));
169     }
171     /**
172      * Test get categories
173      */
174     public function test_get_categories() {
175         global $DB;
177         $this->resetAfterTest(true);
179         $generatedcats = array();
180         $category1data['idnumber'] = 'idnumbercat1';
181         $category1data['name'] = 'Category 1 for PHPunit test';
182         $category1data['description'] = 'Category 1 description';
183         $category1data['descriptionformat'] = FORMAT_MOODLE;
184         $category1  = self::getDataGenerator()->create_category($category1data);
185         $generatedcats[$category1->id] = $category1;
186         $category2  = self::getDataGenerator()->create_category(
187                 array('parent' => $category1->id));
188         $generatedcats[$category2->id] = $category2;
189         $category6  = self::getDataGenerator()->create_category(
190                 array('parent' => $category1->id, 'visible' => 0));
191         $generatedcats[$category6->id] = $category6;
192         $category3  = self::getDataGenerator()->create_category();
193         $generatedcats[$category3->id] = $category3;
194         $category4  = self::getDataGenerator()->create_category(
195                 array('parent' => $category3->id));
196         $generatedcats[$category4->id] = $category4;
197         $category5  = self::getDataGenerator()->create_category(
198                 array('parent' => $category4->id));
199         $generatedcats[$category5->id] = $category5;
201         // Set the required capabilities by the external function.
202         $context = context_system::instance();
203         $roleid = $this->assignUserCapability('moodle/category:manage', $context->id);
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         // Custom fields.
413         $fieldcategory = self::getDataGenerator()->create_custom_field_category(['name' => 'Other fields']);
415         $customfield = ['shortname' => 'test', 'name' => 'Custom field', 'type' => 'text',
416             'categoryid' => $fieldcategory->get('id'),
417             'configdata' => ['visibility' => \core_course\customfield\course_handler::VISIBLETOALL]];
418         $field = self::getDataGenerator()->create_custom_field($customfield);
420         // Set the required capabilities by the external function
421         $contextid = context_system::instance()->id;
422         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
423         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
424         $this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
426         $category  = self::getDataGenerator()->create_category();
428         // Create base categories.
429         $course1['fullname'] = 'Test course 1';
430         $course1['shortname'] = 'Testcourse1';
431         $course1['categoryid'] = $category->id;
432         $course2['fullname'] = 'Test course 2';
433         $course2['shortname'] = 'Testcourse2';
434         $course2['categoryid'] = $category->id;
435         $course2['idnumber'] = 'testcourse2idnumber';
436         $course2['summary'] = 'Description for course 2';
437         $course2['summaryformat'] = FORMAT_MOODLE;
438         $course2['format'] = 'weeks';
439         $course2['showgrades'] = 1;
440         $course2['newsitems'] = 3;
441         $course2['startdate'] = 1420092000; // 01/01/2015.
442         $course2['enddate'] = 1422669600; // 01/31/2015.
443         $course2['numsections'] = 4;
444         $course2['maxbytes'] = 100000;
445         $course2['showreports'] = 1;
446         $course2['visible'] = 0;
447         $course2['hiddensections'] = 0;
448         $course2['groupmode'] = 0;
449         $course2['groupmodeforce'] = 0;
450         $course2['defaultgroupingid'] = 0;
451         $course2['enablecompletion'] = 1;
452         $course2['completionnotify'] = 1;
453         $course2['lang'] = 'en';
454         $course2['forcetheme'] = 'bootstrapbase';
455         $course2['courseformatoptions'][] = array('name' => 'automaticenddate', 'value' => 0);
456         $course3['fullname'] = 'Test course 3';
457         $course3['shortname'] = 'Testcourse3';
458         $course3['categoryid'] = $category->id;
459         $course3['format'] = 'topics';
460         $course3options = array('numsections' => 8,
461             'hiddensections' => 1,
462             'coursedisplay' => 1);
463         $course3['courseformatoptions'] = array();
464         foreach ($course3options as $key => $value) {
465             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
466         }
467         $course4['fullname'] = 'Test course with custom fields';
468         $course4['shortname'] = 'Testcoursecustomfields';
469         $course4['categoryid'] = $category->id;
470         $course4['customfields'] = [['shortname' => $customfield['shortname'], 'value' => 'Test value']];
471         $courses = array($course4, $course1, $course2, $course3);
473         $createdcourses = core_course_external::create_courses($courses);
475         // We need to execute the return values cleaning process to simulate the web service server.
476         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
478         // Check that right number of courses were created.
479         $this->assertEquals(4, count($createdcourses));
481         // Check that the courses were correctly created.
482         foreach ($createdcourses as $createdcourse) {
483             $courseinfo = course_get_format($createdcourse['id'])->get_course();
485             if ($createdcourse['shortname'] == $course2['shortname']) {
486                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
487                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
488                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
489                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
490                 $this->assertEquals($courseinfo->summary, $course2['summary']);
491                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
492                 $this->assertEquals($courseinfo->format, $course2['format']);
493                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
494                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
495                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
496                 $this->assertEquals($courseinfo->enddate, $course2['enddate']);
497                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(), $course2['numsections']);
498                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
499                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
500                 $this->assertEquals($courseinfo->visible, $course2['visible']);
501                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
502                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
503                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
504                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
505                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
506                 $this->assertEquals($courseinfo->lang, $course2['lang']);
507                 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
509                 // We enabled completion at the beginning of the test.
510                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
512             } else if ($createdcourse['shortname'] == $course1['shortname']) {
513                 $courseconfig = get_config('moodlecourse');
514                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
515                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
516                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
517                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
518                 $this->assertEquals($courseinfo->format, $courseconfig->format);
519                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
520                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
521                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
522                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
523                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
524                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
525                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
526             } else if ($createdcourse['shortname'] == $course3['shortname']) {
527                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
528                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
529                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
530                 $this->assertEquals($courseinfo->format, $course3['format']);
531                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
532                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(),
533                     $course3options['numsections']);
534                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
535             } else if ($createdcourse['shortname'] == $course4['shortname']) {
536                 $this->assertEquals($courseinfo->fullname, $course4['fullname']);
537                 $this->assertEquals($courseinfo->shortname, $course4['shortname']);
538                 $this->assertEquals($courseinfo->category, $course4['categoryid']);
540                 $handler = core_course\customfield\course_handler::create();
541                 $customfields = $handler->export_instance_data_object($createdcourse['id']);
542                 $this->assertEquals((object)['test' => 'Test value'], $customfields);
543             } else {
544                 throw new moodle_exception('Unexpected shortname');
545             }
546         }
548         // Call without required capability
549         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
550         $this->expectException('required_capability_exception');
551         $createdsubcats = core_course_external::create_courses($courses);
552     }
554     /**
555      * Test delete_courses
556      */
557     public function test_delete_courses() {
558         global $DB, $USER;
560         $this->resetAfterTest(true);
562         // Admin can delete a course.
563         $this->setAdminUser();
564         // Validate_context() will fail as the email is not set by $this->setAdminUser().
565         $USER->email = 'emailtopass@example.com';
567         $course1  = self::getDataGenerator()->create_course();
568         $course2  = self::getDataGenerator()->create_course();
569         $course3  = self::getDataGenerator()->create_course();
571         // Delete courses.
572         $result = core_course_external::delete_courses(array($course1->id, $course2->id));
573         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
574         // Check for 0 warnings.
575         $this->assertEquals(0, count($result['warnings']));
577         // Check $course 1 and 2 are deleted.
578         $notdeletedcount = $DB->count_records_select('course',
579             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
580         $this->assertEquals(0, $notdeletedcount);
582         // Try to delete non-existent course.
583         $result = core_course_external::delete_courses(array($course1->id));
584         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
585         // Check for 1 warnings.
586         $this->assertEquals(1, count($result['warnings']));
588         // Try to delete Frontpage course.
589         $result = core_course_external::delete_courses(array(0));
590         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
591         // Check for 1 warnings.
592         $this->assertEquals(1, count($result['warnings']));
594          // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
595         $student1 = self::getDataGenerator()->create_user();
596         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
597         $this->getDataGenerator()->enrol_user($student1->id,
598                                               $course3->id,
599                                               $studentrole->id);
600         $this->setUser($student1);
601         $result = core_course_external::delete_courses(array($course3->id));
602         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
603         // Check for 1 warnings.
604         $this->assertEquals(1, count($result['warnings']));
606          // Fail when the user is not allow to access the course (enrolled) or is not admin.
607         $this->setGuestUser();
608         $this->expectException('require_login_exception');
610         $result = core_course_external::delete_courses(array($course3->id));
611         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
612     }
614     /**
615      * Test get_courses
616      */
617     public function test_get_courses () {
618         global $DB;
620         $this->resetAfterTest(true);
622         $generatedcourses = array();
623         $coursedata['idnumber'] = 'idnumbercourse1';
624         // Adding tags here to check that format_string is applied.
625         $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
626         $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
627         $coursedata['summary'] = 'Course 1 description';
628         $coursedata['summaryformat'] = FORMAT_MOODLE;
629         $course1  = self::getDataGenerator()->create_course($coursedata);
631         $fieldcategory = self::getDataGenerator()->create_custom_field_category(
632             ['name' => 'Other fields']);
634         $customfield = ['shortname' => 'test', 'name' => 'Custom field', 'type' => 'text',
635             'categoryid' => $fieldcategory->get('id')];
636         $field = self::getDataGenerator()->create_custom_field($customfield);
638         $customfieldvalue = ['shortname' => 'test', 'value' => 'Test value'];
640         $generatedcourses[$course1->id] = $course1;
641         $course2  = self::getDataGenerator()->create_course();
642         $generatedcourses[$course2->id] = $course2;
643         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
644         $generatedcourses[$course3->id] = $course3;
645         $course4  = self::getDataGenerator()->create_course(['customfields' => [$customfieldvalue]]);
646         $generatedcourses[$course4->id] = $course4;
648         // Set the required capabilities by the external function.
649         $context = context_system::instance();
650         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
651         $this->assignUserCapability('moodle/course:update',
652                 context_course::instance($course1->id)->id, $roleid);
653         $this->assignUserCapability('moodle/course:update',
654                 context_course::instance($course2->id)->id, $roleid);
655         $this->assignUserCapability('moodle/course:update',
656                 context_course::instance($course3->id)->id, $roleid);
657         $this->assignUserCapability('moodle/course:update',
658                 context_course::instance($course4->id)->id, $roleid);
660         $courses = core_course_external::get_courses(array('ids' =>
661             array($course1->id, $course2->id, $course4->id)));
663         // We need to execute the return values cleaning process to simulate the web service server.
664         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
666         // Check we retrieve the good total number of courses.
667         $this->assertEquals(3, count($courses));
669         foreach ($courses as $course) {
670             $coursecontext = context_course::instance($course['id']);
671             $dbcourse = $generatedcourses[$course['id']];
672             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
673             $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id));
674             $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse),
675                 $coursecontext->id));
676             // Summary was converted to the HTML format.
677             $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
678             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
679             $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id));
680             $this->assertEquals($course['categoryid'], $dbcourse->category);
681             $this->assertEquals($course['format'], $dbcourse->format);
682             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
683             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
684             $this->assertEquals($course['startdate'], $dbcourse->startdate);
685             $this->assertEquals($course['enddate'], $dbcourse->enddate);
686             $this->assertEquals($course['numsections'], course_get_format($dbcourse)->get_last_section_number());
687             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
688             $this->assertEquals($course['showreports'], $dbcourse->showreports);
689             $this->assertEquals($course['visible'], $dbcourse->visible);
690             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
691             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
692             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
693             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
694             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
695             $this->assertEquals($course['lang'], $dbcourse->lang);
696             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
697             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
698             if ($dbcourse->format === 'topics') {
699                 $this->assertEquals($course['courseformatoptions'], array(
700                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
701                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
702                 ));
703             }
704             if ($dbcourse->id == 4) {
705                 $this->assertEquals($course['customfields'], [array_merge($customfield, $customfieldvalue)]);
706             }
707         }
709         // Get all courses in the DB
710         $courses = core_course_external::get_courses(array());
712         // We need to execute the return values cleaning process to simulate the web service server.
713         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
715         $this->assertEquals($DB->count_records('course'), count($courses));
716     }
718     /**
719      * Test get_courses without capability
720      */
721     public function test_get_courses_without_capability() {
722         $this->resetAfterTest(true);
724         $course1 = $this->getDataGenerator()->create_course();
725         $this->setUser($this->getDataGenerator()->create_user());
727         // No permissions are required to get the site course.
728         $courses = core_course_external::get_courses(array('ids' => [SITEID]));
729         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
731         $this->assertEquals(1, count($courses));
732         $this->assertEquals('PHPUnit test site', $courses[0]['fullname']);
733         $this->assertEquals('site', $courses[0]['format']);
735         // Requesting course without being enrolled or capability to view it will throw an exception.
736         try {
737             core_course_external::get_courses(array('ids' => [$course1->id]));
738             $this->fail('Exception expected');
739         } catch (moodle_exception $e) {
740             $this->assertEquals(1, preg_match('/Course or activity not accessible. \(Not enrolled\)/', $e->getMessage()));
741         }
742     }
744     /**
745      * Test search_courses
746      */
747     public function test_search_courses () {
749         global $DB;
751         $this->resetAfterTest(true);
752         $this->setAdminUser();
753         $generatedcourses = array();
754         $coursedata1['fullname'] = 'FIRST COURSE';
755         $course1  = self::getDataGenerator()->create_course($coursedata1);
757         $page = new moodle_page();
758         $page->set_course($course1);
759         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
761         $coursedata2['fullname'] = 'SECOND COURSE';
762         $course2  = self::getDataGenerator()->create_course($coursedata2);
764         $page = new moodle_page();
765         $page->set_course($course2);
766         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
768         // Search by name.
769         $results = core_course_external::search_courses('search', 'FIRST');
770         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
771         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
772         $this->assertCount(1, $results['courses']);
774         // Create the forum.
775         $record = new stdClass();
776         $record->introformat = FORMAT_HTML;
777         $record->course = $course2->id;
778         // Set Aggregate type = Average of ratings.
779         $forum = self::getDataGenerator()->create_module('forum', $record);
781         // Search by module.
782         $results = core_course_external::search_courses('modulelist', 'forum');
783         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
784         $this->assertEquals(1, $results['total']);
786         // Enable coursetag option.
787         set_config('block_tags_showcoursetags', true);
788         // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
789         core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
790                 array('TAG-LABEL ON SECOND COURSE'));
791         $taginstance = $DB->get_record('tag_instance',
792                 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
794         // Search by tagid.
795         $results = core_course_external::search_courses('tagid', $taginstance->tagid);
796         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
797         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
799         // Search by block (use news_items default block).
800         $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
801         $results = core_course_external::search_courses('blocklist', $blockid);
802         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
803         $this->assertEquals(2, $results['total']);
805         // Now as a normal user.
806         $user = self::getDataGenerator()->create_user();
808         // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
809         $coursedata3['fullname'] = 'HIDDEN COURSE';
810         $coursedata3['visible'] = 0;
811         $course3  = self::getDataGenerator()->create_course($coursedata3);
812         $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
814         $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
815         $this->setUser($user);
817         $results = core_course_external::search_courses('search', 'FIRST');
818         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
819         $this->assertCount(1, $results['courses']);
820         $this->assertEquals(1, $results['total']);
821         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
823         // Check that we can see all courses without the limit to enrolled setting.
824         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
825         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
826         $this->assertCount(2, $results['courses']);
827         $this->assertEquals(2, $results['total']);
829         // Check that we only see our enrolled course when limiting.
830         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
831         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
832         $this->assertCount(1, $results['courses']);
833         $this->assertEquals(1, $results['total']);
834         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
836         // Search by block (use news_items default block). Should fail (only admins allowed).
837         $this->expectException('required_capability_exception');
838         $results = core_course_external::search_courses('blocklist', $blockid);
839     }
841     /**
842      * Create a course with contents
843      * @return array A list with the course object and course modules objects
844      */
845     private function prepare_get_course_contents_test() {
846         global $DB, $CFG;
848         $CFG->allowstealth = 1; // Allow stealth activities.
849         $CFG->enablecompletion = true;
850         $course  = self::getDataGenerator()->create_course(['numsections' => 4, 'enablecompletion' => 1]);
852         $forumdescription = 'This is the forum description';
853         $forum = $this->getDataGenerator()->create_module('forum',
854             array('course' => $course->id, 'intro' => $forumdescription, 'trackingtype' => 2),
855             array('showdescription' => true, 'completion' => COMPLETION_TRACKING_MANUAL));
856         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
857         // Add discussions to the tracking forced forum.
858         $record = new stdClass();
859         $record->course = $course->id;
860         $record->userid = 0;
861         $record->forum = $forum->id;
862         $discussionforce = $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
863         $data = $this->getDataGenerator()->create_module('data',
864             array('assessed' => 1, 'scale' => 100, 'course' => $course->id, 'completion' => 2, 'completionentries' => 3));
865         $datacm = get_coursemodule_from_instance('data', $data->id);
866         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
867         $pagecm = get_coursemodule_from_instance('page', $page->id);
868         // This is an stealth page (set by visibleoncoursepage).
869         $pagestealth = $this->getDataGenerator()->create_module('page', array('course' => $course->id, 'visibleoncoursepage' => 0));
870         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
871                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
872         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
873             'intro' => $labeldescription));
874         $labelcm = get_coursemodule_from_instance('label', $label->id);
875         $tomorrow = time() + DAYSECS;
876         // Module with availability restrictions not met.
877         $url = $this->getDataGenerator()->create_module('url',
878             array('course' => $course->id, 'name' => 'URL: % & $ ../', 'section' => 2, 'display' => RESOURCELIB_DISPLAY_POPUP,
879                 'popupwidth' => 100, 'popupheight' => 100),
880             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}'));
881         $urlcm = get_coursemodule_from_instance('url', $url->id);
882         // Module for the last section.
883         $this->getDataGenerator()->create_module('url',
884             array('course' => $course->id, 'name' => 'URL for last section', 'section' => 3));
885         // Module for section 1 with availability restrictions met.
886         $yesterday = time() - DAYSECS;
887         $this->getDataGenerator()->create_module('url',
888             array('course' => $course->id, 'name' => 'URL restrictions met', 'section' => 1),
889             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":'. $yesterday .'}],"showc":[true]}'));
891         // Set the required capabilities by the external function.
892         $context = context_course::instance($course->id);
893         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
894         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
895         $this->assignUserCapability('mod/data:view', $context->id, $roleid);
897         $conditions = array('course' => $course->id, 'section' => 2);
898         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
900         // Add date availability condition not met for section 3.
901         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}';
902         $DB->set_field('course_sections', 'availability', $availability,
903                 array('course' => $course->id, 'section' => 3));
905         // Create resource for last section.
906         $pageinhiddensection = $this->getDataGenerator()->create_module('page',
907             array('course' => $course->id, 'name' => 'Page in hidden section', 'section' => 4));
908         // Set not visible last section.
909         $DB->set_field('course_sections', 'visible', 0,
910                 array('course' => $course->id, 'section' => 4));
912         rebuild_course_cache($course->id, true);
914         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
915     }
917     /**
918      * Test get_course_contents
919      */
920     public function test_get_course_contents() {
921         global $CFG;
922         $this->resetAfterTest(true);
924         $CFG->forum_allowforcedreadtracking = 1;
925         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
927         // We first run the test as admin.
928         $this->setAdminUser();
929         $sections = core_course_external::get_course_contents($course->id, array());
930         // We need to execute the return values cleaning process to simulate the web service server.
931         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
933         $modinfo = get_fast_modinfo($course);
934         $testexecuted = 0;
935         foreach ($sections[0]['modules'] as $module) {
936             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
937                 $cm = $modinfo->cms[$forumcm->id];
938                 $formattedtext = format_text($cm->content, FORMAT_HTML,
939                     array('noclean' => true, 'para' => false, 'filter' => false));
940                 $this->assertEquals($formattedtext, $module['description']);
941                 $this->assertEquals($forumcm->instance, $module['instance']);
942                 $this->assertContains('1 unread post', $module['afterlink']);
943                 $testexecuted = $testexecuted + 2;
944             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
945                 $cm = $modinfo->cms[$labelcm->id];
946                 $formattedtext = format_text($cm->content, FORMAT_HTML,
947                     array('noclean' => true, 'para' => false, 'filter' => false));
948                 $this->assertEquals($formattedtext, $module['description']);
949                 $this->assertEquals($labelcm->instance, $module['instance']);
950                 $testexecuted = $testexecuted + 1;
951             } else if ($module['id'] == $datacm->id and $module['modname'] == 'data') {
952                 $this->assertContains('customcompletionrules', $module['customdata']);
953                 $testexecuted = $testexecuted + 1;
954             }
955         }
956         foreach ($sections[2]['modules'] as $module) {
957             if ($module['id'] == $urlcm->id and $module['modname'] == 'url') {
958                 $this->assertContains('width=100,height=100', $module['onclick']);
959                 $testexecuted = $testexecuted + 1;
960             }
961         }
963         $CFG->forum_allowforcedreadtracking = 0;    // Recover original value.
964         forum_tp_count_forum_unread_posts($forumcm, $course, true);    // Reset static cache for further tests.
966         $this->assertEquals(5, $testexecuted);
967         $this->assertEquals(0, $sections[0]['section']);
969         $this->assertCount(5, $sections[0]['modules']);
970         $this->assertCount(1, $sections[1]['modules']);
971         $this->assertCount(1, $sections[2]['modules']);
972         $this->assertCount(1, $sections[3]['modules']); // One module for the section with availability restrictions.
973         $this->assertCount(1, $sections[4]['modules']); // One module for the hidden section with a visible activity.
974         $this->assertNotEmpty($sections[3]['availabilityinfo']);
975         $this->assertEquals(1, $sections[1]['section']);
976         $this->assertEquals(2, $sections[2]['section']);
977         $this->assertEquals(3, $sections[3]['section']);
978         $this->assertEquals(4, $sections[4]['section']);
979         $this->assertContains('<iframe', $sections[2]['summary']);
980         $this->assertContains('</iframe>', $sections[2]['summary']);
981         $this->assertNotEmpty($sections[2]['modules'][0]['availabilityinfo']);
982         try {
983             $sections = core_course_external::get_course_contents($course->id,
984                                                                     array(array("name" => "invalid", "value" => 1)));
985             $this->fail('Exception expected due to invalid option.');
986         } catch (moodle_exception $e) {
987             $this->assertEquals('errorinvalidparam', $e->errorcode);
988         }
989     }
992     /**
993      * Test get_course_contents as student
994      */
995     public function test_get_course_contents_student() {
996         global $DB;
997         $this->resetAfterTest(true);
999         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1001         $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
1002         $user = self::getDataGenerator()->create_user();
1003         self::getDataGenerator()->enrol_user($user->id, $course->id, $studentroleid);
1004         $this->setUser($user);
1006         $sections = core_course_external::get_course_contents($course->id, array());
1007         // We need to execute the return values cleaning process to simulate the web service server.
1008         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1010         $this->assertCount(4, $sections); // Nothing for the not visible section.
1011         $this->assertCount(5, $sections[0]['modules']);
1012         $this->assertCount(1, $sections[1]['modules']);
1013         $this->assertCount(1, $sections[2]['modules']);
1014         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
1016         $this->assertNotEmpty($sections[3]['availabilityinfo']);
1017         $this->assertEquals(1, $sections[1]['section']);
1018         $this->assertEquals(2, $sections[2]['section']);
1019         $this->assertEquals(3, $sections[3]['section']);
1020         // The module with the availability restriction met is returning contents.
1021         $this->assertNotEmpty($sections[1]['modules'][0]['contents']);
1022         // The module with the availability restriction not met is not returning contents.
1023         $this->assertArrayNotHasKey('contents', $sections[2]['modules'][0]);
1025         // Now include flag for returning stealth information (fake section).
1026         $sections = core_course_external::get_course_contents($course->id,
1027             array(array("name" => "includestealthmodules", "value" => 1)));
1028         // We need to execute the return values cleaning process to simulate the web service server.
1029         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1031         $this->assertCount(5, $sections); // Include fake section with stealth activities.
1032         $this->assertCount(5, $sections[0]['modules']);
1033         $this->assertCount(1, $sections[1]['modules']);
1034         $this->assertCount(1, $sections[2]['modules']);
1035         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
1036         $this->assertCount(1, $sections[4]['modules']); // One stealh module.
1037         $this->assertEquals(-1, $sections[4]['id']);
1038     }
1040     /**
1041      * Test get_course_contents excluding modules
1042      */
1043     public function test_get_course_contents_excluding_modules() {
1044         $this->resetAfterTest(true);
1046         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1048         // Test exclude modules.
1049         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
1051         // We need to execute the return values cleaning process to simulate the web service server.
1052         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1054         $this->assertEmpty($sections[0]['modules']);
1055         $this->assertEmpty($sections[1]['modules']);
1056     }
1058     /**
1059      * Test get_course_contents excluding contents
1060      */
1061     public function test_get_course_contents_excluding_contents() {
1062         $this->resetAfterTest(true);
1064         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1066         // Test exclude modules.
1067         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
1069         // We need to execute the return values cleaning process to simulate the web service server.
1070         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1072         foreach ($sections as $section) {
1073             foreach ($section['modules'] as $module) {
1074                 // Only resources return contents.
1075                 if (isset($module['contents'])) {
1076                     $this->assertEmpty($module['contents']);
1077                 }
1078             }
1079         }
1080     }
1082     /**
1083      * Test get_course_contents filtering by section number
1084      */
1085     public function test_get_course_contents_section_number() {
1086         $this->resetAfterTest(true);
1088         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1090         // Test exclude modules.
1091         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
1093         // We need to execute the return values cleaning process to simulate the web service server.
1094         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1096         $this->assertCount(1, $sections);
1097         $this->assertCount(5, $sections[0]['modules']);
1098     }
1100     /**
1101      * Test get_course_contents filtering by cmid
1102      */
1103     public function test_get_course_contents_cmid() {
1104         $this->resetAfterTest(true);
1106         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1108         // Test exclude modules.
1109         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
1111         // We need to execute the return values cleaning process to simulate the web service server.
1112         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1114         $this->assertCount(4, $sections);
1115         $this->assertCount(1, $sections[0]['modules']);
1116         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1117     }
1120     /**
1121      * Test get_course_contents filtering by cmid and section
1122      */
1123     public function test_get_course_contents_section_cmid() {
1124         $this->resetAfterTest(true);
1126         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1128         // Test exclude modules.
1129         $sections = core_course_external::get_course_contents($course->id, array(
1130                                                                         array("name" => "cmid", "value" => $forumcm->id),
1131                                                                         array("name" => "sectionnumber", "value" => 0)
1132                                                                         ));
1134         // We need to execute the return values cleaning process to simulate the web service server.
1135         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1137         $this->assertCount(1, $sections);
1138         $this->assertCount(1, $sections[0]['modules']);
1139         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1140     }
1142     /**
1143      * Test get_course_contents filtering by modname
1144      */
1145     public function test_get_course_contents_modname() {
1146         $this->resetAfterTest(true);
1148         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1150         // Test exclude modules.
1151         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
1153         // We need to execute the return values cleaning process to simulate the web service server.
1154         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1156         $this->assertCount(4, $sections);
1157         $this->assertCount(1, $sections[0]['modules']);
1158         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1159     }
1161     /**
1162      * Test get_course_contents filtering by modname
1163      */
1164     public function test_get_course_contents_modid() {
1165         $this->resetAfterTest(true);
1167         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1169         // Test exclude modules.
1170         $sections = core_course_external::get_course_contents($course->id, array(
1171                                                                             array("name" => "modname", "value" => "page"),
1172                                                                             array("name" => "modid", "value" => $pagecm->instance),
1173                                                                             ));
1175         // We need to execute the return values cleaning process to simulate the web service server.
1176         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1178         $this->assertCount(4, $sections);
1179         $this->assertCount(1, $sections[0]['modules']);
1180         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
1181         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
1182     }
1184     /**
1185      * Test get course contents completion
1186      */
1187     public function test_get_course_contents_completion() {
1188         global $CFG;
1189         $this->resetAfterTest(true);
1191         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1193         // Test activity not completed yet.
1194         $result = core_course_external::get_course_contents($course->id, array(
1195             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1196         // We need to execute the return values cleaning process to simulate the web service server.
1197         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1199         $this->assertCount(1, $result[0]['modules']);
1200         $this->assertEquals("forum", $result[0]['modules'][0]["modname"]);
1201         $this->assertEquals(COMPLETION_TRACKING_MANUAL, $result[0]['modules'][0]["completion"]);
1202         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['state']);
1203         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['timecompleted']);
1204         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1206         // Set activity completed.
1207         core_completion_external::update_activity_completion_status_manually($forumcm->id, true);
1209         $result = core_course_external::get_course_contents($course->id, array(
1210             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1211         // We need to execute the return values cleaning process to simulate the web service server.
1212         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1214         $this->assertEquals(COMPLETION_COMPLETE, $result[0]['modules'][0]["completiondata"]['state']);
1215         $this->assertNotEmpty($result[0]['modules'][0]["completiondata"]['timecompleted']);
1216         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1218         // Disable completion.
1219         $CFG->enablecompletion = 0;
1220         $result = core_course_external::get_course_contents($course->id, array(
1221             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1222         // We need to execute the return values cleaning process to simulate the web service server.
1223         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1225         $this->assertArrayNotHasKey('completiondata', $result[0]['modules'][0]);
1226     }
1228     /**
1229      * Test duplicate_course
1230      */
1231     public function test_duplicate_course() {
1232         $this->resetAfterTest(true);
1234         // Create one course with three modules.
1235         $course  = self::getDataGenerator()->create_course();
1236         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
1237         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
1238         $forumcontext = context_module::instance($forum->cmid);
1239         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
1240         $datacontext = context_module::instance($data->cmid);
1241         $datacm = get_coursemodule_from_instance('page', $data->id);
1242         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
1243         $pagecontext = context_module::instance($page->cmid);
1244         $pagecm = get_coursemodule_from_instance('page', $page->id);
1246         // Set the required capabilities by the external function.
1247         $coursecontext = context_course::instance($course->id);
1248         $categorycontext = context_coursecat::instance($course->category);
1249         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
1250         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
1251         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
1252         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
1253         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
1254         // Optional capabilities to copy user data.
1255         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
1256         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
1258         $newcourse['fullname'] = 'Course duplicate';
1259         $newcourse['shortname'] = 'courseduplicate';
1260         $newcourse['categoryid'] = $course->category;
1261         $newcourse['visible'] = true;
1262         $newcourse['options'][] = array('name' => 'users', 'value' => true);
1264         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
1265                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
1267         // We need to execute the return values cleaning process to simulate the web service server.
1268         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1270         // Check that the course has been duplicated.
1271         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1272     }
1274     /**
1275      * Test update_courses
1276      */
1277     public function test_update_courses() {
1278         global $DB, $CFG, $USER, $COURSE;
1280         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1281         // trick because we are both updating and getting (for testing) course information
1282         // in the same request and core_course_external::update_courses()
1283         // is overwriting $COURSE all over the time with OLD values, so later
1284         // use of get_course() fetches those OLD values instead of the updated ones.
1285         // See MDL-39723 for more info.
1286         $origcourse = clone($COURSE);
1288         $this->resetAfterTest(true);
1290         // Set the required capabilities by the external function.
1291         $contextid = context_system::instance()->id;
1292         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1293         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1294         $this->assignUserCapability('moodle/course:changelockedcustomfields', $contextid, $roleid);
1295         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1296         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1297         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1298         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1299         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1300         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1301         $this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
1303         // Create category and courses.
1304         $category1  = self::getDataGenerator()->create_category();
1305         $category2  = self::getDataGenerator()->create_category();
1307         $originalcourse1 = self::getDataGenerator()->create_course();
1308         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1310         $originalcourse2 = self::getDataGenerator()->create_course();
1311         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1313         // Course with custom fields.
1314         $fieldcategory = self::getDataGenerator()->create_custom_field_category(['name' => 'Other fields']);
1315         $customfield = ['shortname' => 'test', 'name' => 'Custom field', 'type' => 'text',
1316             'categoryid' => $fieldcategory->get('id'),
1317             'configdata' => ['visibility' => \core_course\customfield\course_handler::VISIBLETOALL, 'locked' => 1]];
1318         $field = self::getDataGenerator()->create_custom_field($customfield);
1320         $originalcourse3 = self::getDataGenerator()->create_course(['customfield_test' => 'Test value']);
1321         self::getDataGenerator()->enrol_user($USER->id, $originalcourse3->id, $roleid);
1323         // Course values to be updated.
1324         $course1['id'] = $originalcourse1->id;
1325         $course1['fullname'] = 'Updated test course 1';
1326         $course1['shortname'] = 'Udestedtestcourse1';
1327         $course1['categoryid'] = $category1->id;
1329         $course2['id'] = $originalcourse2->id;
1330         $course2['fullname'] = 'Updated test course 2';
1331         $course2['shortname'] = 'Updestedtestcourse2';
1332         $course2['categoryid'] = $category2->id;
1333         $course2['idnumber'] = 'Updatedidnumber2';
1334         $course2['summary'] = 'Updaated description for course 2';
1335         $course2['summaryformat'] = FORMAT_HTML;
1336         $course2['format'] = 'topics';
1337         $course2['showgrades'] = 1;
1338         $course2['newsitems'] = 3;
1339         $course2['startdate'] = 1420092000; // 01/01/2015.
1340         $course2['enddate'] = 1422669600; // 01/31/2015.
1341         $course2['maxbytes'] = 100000;
1342         $course2['showreports'] = 1;
1343         $course2['visible'] = 0;
1344         $course2['hiddensections'] = 0;
1345         $course2['groupmode'] = 0;
1346         $course2['groupmodeforce'] = 0;
1347         $course2['defaultgroupingid'] = 0;
1348         $course2['enablecompletion'] = 1;
1349         $course2['lang'] = 'en';
1350         $course2['forcetheme'] = 'bootstrapbase';
1352         $course3['id'] = $originalcourse3->id;
1353         $updatedcustomfieldvalue = ['shortname' => 'test', 'value' => 'Updated test value'];
1354         $course3['customfields'] = [$updatedcustomfieldvalue];
1355         $courses = array($course1, $course2, $course3);
1357         $updatedcoursewarnings = core_course_external::update_courses($courses);
1358         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1359                 $updatedcoursewarnings);
1360         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1362         // Check that right number of courses were created.
1363         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1365         // Check that the courses were correctly created.
1366         foreach ($courses as $course) {
1367             $courseinfo = course_get_format($course['id'])->get_course();
1368             $customfields = \core_course\customfield\course_handler::create()->export_instance_data_object($course['id']);
1369             if ($course['id'] == $course2['id']) {
1370                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1371                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1372                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1373                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1374                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1375                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1376                 $this->assertEquals($course2['format'], $courseinfo->format);
1377                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1378                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1379                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1380                 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
1381                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1382                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1383                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1384                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1385                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1386                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1387                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1388                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1390                 if (!empty($CFG->allowcoursethemes)) {
1391                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1392                 }
1394                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1395                 $this->assertEquals(['test' => null], (array)$customfields);
1396             } else if ($course['id'] == $course1['id']) {
1397                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1398                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1399                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1400                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1401                 $this->assertEquals('topics', $courseinfo->format);
1402                 $this->assertEquals(5, course_get_format($course['id'])->get_last_section_number());
1403                 $this->assertEquals(0, $courseinfo->newsitems);
1404                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1405                 $this->assertEquals(['test' => null], (array)$customfields);
1406             } else if ($course['id'] == $course3['id']) {
1407                 $this->assertEquals(['test' => $updatedcustomfieldvalue['value']], (array)$customfields);
1408             } else {
1409                 throw new moodle_exception('Unexpected shortname');
1410             }
1411         }
1413         $courses = array($course1);
1414         // Try update course without update capability.
1415         $user = self::getDataGenerator()->create_user();
1416         $this->setUser($user);
1417         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1418         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1419         $updatedcoursewarnings = core_course_external::update_courses($courses);
1420         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1421                                                                     $updatedcoursewarnings);
1422         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1424         // Try update course category without capability.
1425         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1426         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1427         $user = self::getDataGenerator()->create_user();
1428         $this->setUser($user);
1429         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1430         $course1['categoryid'] = $category2->id;
1431         $courses = array($course1);
1432         $updatedcoursewarnings = core_course_external::update_courses($courses);
1433         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1434                                                                     $updatedcoursewarnings);
1435         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1437         // Try update course fullname without capability.
1438         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1439         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1440         $user = self::getDataGenerator()->create_user();
1441         $this->setUser($user);
1442         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1443         $updatedcoursewarnings = core_course_external::update_courses($courses);
1444         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1445                                                                     $updatedcoursewarnings);
1446         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1447         $course1['fullname'] = 'Testing fullname without permission';
1448         $courses = array($course1);
1449         $updatedcoursewarnings = core_course_external::update_courses($courses);
1450         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1451                                                                     $updatedcoursewarnings);
1452         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1454         // Try update course shortname without capability.
1455         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1456         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1457         $user = self::getDataGenerator()->create_user();
1458         $this->setUser($user);
1459         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1460         $updatedcoursewarnings = core_course_external::update_courses($courses);
1461         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1462                                                                     $updatedcoursewarnings);
1463         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1464         $course1['shortname'] = 'Testing shortname without permission';
1465         $courses = array($course1);
1466         $updatedcoursewarnings = core_course_external::update_courses($courses);
1467         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1468                                                                     $updatedcoursewarnings);
1469         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1471         // Try update course idnumber without capability.
1472         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1473         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1474         $user = self::getDataGenerator()->create_user();
1475         $this->setUser($user);
1476         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
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(0, count($updatedcoursewarnings['warnings']));
1481         $course1['idnumber'] = 'NEWIDNUMBER';
1482         $courses = array($course1);
1483         $updatedcoursewarnings = core_course_external::update_courses($courses);
1484         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1485                                                                     $updatedcoursewarnings);
1486         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1488         // Try update course summary without capability.
1489         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1490         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1491         $user = self::getDataGenerator()->create_user();
1492         $this->setUser($user);
1493         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1494         $updatedcoursewarnings = core_course_external::update_courses($courses);
1495         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1496                                                                     $updatedcoursewarnings);
1497         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1498         $course1['summary'] = 'New summary';
1499         $courses = array($course1);
1500         $updatedcoursewarnings = core_course_external::update_courses($courses);
1501         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1502                                                                     $updatedcoursewarnings);
1503         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1505         // Try update course with invalid summary format.
1506         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1507         $user = self::getDataGenerator()->create_user();
1508         $this->setUser($user);
1509         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1510         $updatedcoursewarnings = core_course_external::update_courses($courses);
1511         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1512                                                                     $updatedcoursewarnings);
1513         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1514         $course1['summaryformat'] = 10;
1515         $courses = array($course1);
1516         $updatedcoursewarnings = core_course_external::update_courses($courses);
1517         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1518                                                                     $updatedcoursewarnings);
1519         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1521         // Try update course visibility without capability.
1522         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1523         $user = self::getDataGenerator()->create_user();
1524         $this->setUser($user);
1525         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1526         $course1['summaryformat'] = FORMAT_MOODLE;
1527         $courses = array($course1);
1528         $updatedcoursewarnings = core_course_external::update_courses($courses);
1529         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1530                                                                     $updatedcoursewarnings);
1531         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1532         $course1['visible'] = 0;
1533         $courses = array($course1);
1534         $updatedcoursewarnings = core_course_external::update_courses($courses);
1535         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1536                                                                     $updatedcoursewarnings);
1537         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1539         // Try update course custom fields without capability.
1540         $this->unassignUserCapability('moodle/course:changelockedcustomfields', $contextid, $roleid);
1541         $user = self::getDataGenerator()->create_user();
1542         $this->setUser($user);
1543         self::getDataGenerator()->enrol_user($user->id, $course3['id'], $roleid);
1545         $newupdatedcustomfieldvalue = ['shortname' => 'test', 'value' => 'New updated value'];
1546         $course3['customfields'] = [$newupdatedcustomfieldvalue];
1548         core_course_external::update_courses([$course3]);
1550         // Custom field was not updated.
1551         $customfields = \core_course\customfield\course_handler::create()->export_instance_data_object($course3['id']);
1552         $this->assertEquals(['test' => $updatedcustomfieldvalue['value']], (array)$customfields);
1553     }
1555     /**
1556      * Test delete course_module.
1557      */
1558     public function test_delete_modules() {
1559         global $DB;
1561         // Ensure we reset the data after this test.
1562         $this->resetAfterTest(true);
1564         // Create a user.
1565         $user = self::getDataGenerator()->create_user();
1567         // Set the tests to run as the user.
1568         self::setUser($user);
1570         // Create a course to add the modules.
1571         $course = self::getDataGenerator()->create_course();
1573         // Create two test modules.
1574         $record = new stdClass();
1575         $record->course = $course->id;
1576         $module1 = self::getDataGenerator()->create_module('forum', $record);
1577         $module2 = self::getDataGenerator()->create_module('assign', $record);
1579         // Check the forum was correctly created.
1580         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1582         // Check the assignment was correctly created.
1583         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1585         // Check data exists in the course modules table.
1586         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1587                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1589         // Enrol the user in the course.
1590         $enrol = enrol_get_plugin('manual');
1591         $enrolinstances = enrol_get_instances($course->id, true);
1592         foreach ($enrolinstances as $courseenrolinstance) {
1593             if ($courseenrolinstance->enrol == "manual") {
1594                 $instance = $courseenrolinstance;
1595                 break;
1596             }
1597         }
1598         $enrol->enrol_user($instance, $user->id);
1600         // Assign capabilities to delete module 1.
1601         $modcontext = context_module::instance($module1->cmid);
1602         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1604         // Assign capabilities to delete module 2.
1605         $modcontext = context_module::instance($module2->cmid);
1606         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1607         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1609         // Deleting these module instances.
1610         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1612         // Check the forum was deleted.
1613         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1615         // Check the assignment was deleted.
1616         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1618         // Check we retrieve no data in the course modules table.
1619         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1620                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1622         // Call with non-existent course module id and ensure exception thrown.
1623         try {
1624             core_course_external::delete_modules(array('1337'));
1625             $this->fail('Exception expected due to missing course module.');
1626         } catch (dml_missing_record_exception $e) {
1627             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1628         }
1630         // Create two modules.
1631         $module1 = self::getDataGenerator()->create_module('forum', $record);
1632         $module2 = self::getDataGenerator()->create_module('assign', $record);
1634         // Since these modules were recreated the user will not have capabilities
1635         // to delete them, ensure exception is thrown if they try.
1636         try {
1637             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1638             $this->fail('Exception expected due to missing capability.');
1639         } catch (moodle_exception $e) {
1640             $this->assertEquals('nopermissions', $e->errorcode);
1641         }
1643         // Unenrol user from the course.
1644         $enrol->unenrol_user($instance, $user->id);
1646         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1647         try {
1648             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1649             $this->fail('Exception expected due to being unenrolled from the course.');
1650         } catch (moodle_exception $e) {
1651             $this->assertEquals('requireloginerror', $e->errorcode);
1652         }
1653     }
1655     /**
1656      * Test import_course into an empty course
1657      */
1658     public function test_import_course_empty() {
1659         global $USER;
1661         $this->resetAfterTest(true);
1663         $course1  = self::getDataGenerator()->create_course();
1664         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1665         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1667         $course2  = self::getDataGenerator()->create_course();
1669         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1670         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1672         // Verify the state of the courses before we do the import.
1673         $this->assertCount(2, $course1cms);
1674         $this->assertEmpty($course2cms);
1676         // Setup the user to run the operation (ugly hack because validate_context() will
1677         // fail as the email is not set by $this->setAdminUser()).
1678         $this->setAdminUser();
1679         $USER->email = 'emailtopass@example.com';
1681         // Import from course1 to course2.
1682         core_course_external::import_course($course1->id, $course2->id, 0);
1684         // Verify that now we have two modules in both courses.
1685         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1686         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1687         $this->assertCount(2, $course1cms);
1688         $this->assertCount(2, $course2cms);
1690         // Verify that the names transfered across correctly.
1691         foreach ($course2cms as $cm) {
1692             if ($cm->modname === 'page') {
1693                 $this->assertEquals($cm->name, $page->name);
1694             } else if ($cm->modname === 'forum') {
1695                 $this->assertEquals($cm->name, $forum->name);
1696             } else {
1697                 $this->fail('Unknown CM found.');
1698             }
1699         }
1700     }
1702     /**
1703      * Test import_course into an filled course
1704      */
1705     public function test_import_course_filled() {
1706         global $USER;
1708         $this->resetAfterTest(true);
1710         // Add forum and page to course1.
1711         $course1  = self::getDataGenerator()->create_course();
1712         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1713         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1715         // Add quiz to course 2.
1716         $course2  = self::getDataGenerator()->create_course();
1717         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1719         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1720         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1722         // Verify the state of the courses before we do the import.
1723         $this->assertCount(2, $course1cms);
1724         $this->assertCount(1, $course2cms);
1726         // Setup the user to run the operation (ugly hack because validate_context() will
1727         // fail as the email is not set by $this->setAdminUser()).
1728         $this->setAdminUser();
1729         $USER->email = 'emailtopass@example.com';
1731         // Import from course1 to course2 without deleting content.
1732         core_course_external::import_course($course1->id, $course2->id, 0);
1734         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1736         // Verify that now we have three modules in course2.
1737         $this->assertCount(3, $course2cms);
1739         // Verify that the names transfered across correctly.
1740         foreach ($course2cms as $cm) {
1741             if ($cm->modname === 'page') {
1742                 $this->assertEquals($cm->name, $page->name);
1743             } else if ($cm->modname === 'forum') {
1744                 $this->assertEquals($cm->name, $forum->name);
1745             } else if ($cm->modname === 'quiz') {
1746                 $this->assertEquals($cm->name, $quiz->name);
1747             } else {
1748                 $this->fail('Unknown CM found.');
1749             }
1750         }
1751     }
1753     /**
1754      * Test import_course with only blocks set to backup
1755      */
1756     public function test_import_course_blocksonly() {
1757         global $USER, $DB;
1759         $this->resetAfterTest(true);
1761         // Add forum and page to course1.
1762         $course1  = self::getDataGenerator()->create_course();
1763         $course1ctx = context_course::instance($course1->id);
1764         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1765         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1767         $course2  = self::getDataGenerator()->create_course();
1768         $course2ctx = context_course::instance($course2->id);
1769         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1770         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1772         // Setup the user to run the operation (ugly hack because validate_context() will
1773         // fail as the email is not set by $this->setAdminUser()).
1774         $this->setAdminUser();
1775         $USER->email = 'emailtopass@example.com';
1777         // Import from course1 to course2 without deleting content, but excluding
1778         // activities.
1779         $options = array(
1780             array('name' => 'activities', 'value' => 0),
1781             array('name' => 'blocks', 'value' => 1),
1782             array('name' => 'filters', 'value' => 0),
1783         );
1785         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1787         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1788         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1789         // Check that course modules haven't changed, but that blocks have.
1790         $this->assertEquals($initialcmcount, $newcmcount);
1791         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1792     }
1794     /**
1795      * Test import_course into an filled course, deleting content.
1796      */
1797     public function test_import_course_deletecontent() {
1798         global $USER;
1799         $this->resetAfterTest(true);
1801         // Add forum and page to course1.
1802         $course1  = self::getDataGenerator()->create_course();
1803         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1804         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1806         // Add quiz to course 2.
1807         $course2  = self::getDataGenerator()->create_course();
1808         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1810         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1811         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1813         // Verify the state of the courses before we do the import.
1814         $this->assertCount(2, $course1cms);
1815         $this->assertCount(1, $course2cms);
1817         // Setup the user to run the operation (ugly hack because validate_context() will
1818         // fail as the email is not set by $this->setAdminUser()).
1819         $this->setAdminUser();
1820         $USER->email = 'emailtopass@example.com';
1822         // Import from course1 to course2,  deleting content.
1823         core_course_external::import_course($course1->id, $course2->id, 1);
1825         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1827         // Verify that now we have two modules in course2.
1828         $this->assertCount(2, $course2cms);
1830         // Verify that the course only contains the imported modules.
1831         foreach ($course2cms as $cm) {
1832             if ($cm->modname === 'page') {
1833                 $this->assertEquals($cm->name, $page->name);
1834             } else if ($cm->modname === 'forum') {
1835                 $this->assertEquals($cm->name, $forum->name);
1836             } else {
1837                 $this->fail('Unknown CM found: '.$cm->name);
1838             }
1839         }
1840     }
1842     /**
1843      * Ensure import_course handles incorrect deletecontent option correctly.
1844      */
1845     public function test_import_course_invalid_deletecontent_option() {
1846         $this->resetAfterTest(true);
1848         $course1  = self::getDataGenerator()->create_course();
1849         $course2  = self::getDataGenerator()->create_course();
1851         $this->expectException('moodle_exception');
1852         $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
1853         // Import from course1 to course2, with invalid option
1854         core_course_external::import_course($course1->id, $course2->id, -1);;
1855     }
1857     /**
1858      * Test view_course function
1859      */
1860     public function test_view_course() {
1862         $this->resetAfterTest();
1864         // Course without sections.
1865         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1866         $this->setAdminUser();
1868         // Redirect events to the sink, so we can recover them later.
1869         $sink = $this->redirectEvents();
1871         $result = core_course_external::view_course($course->id, 1);
1872         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1873         $events = $sink->get_events();
1874         $event = reset($events);
1876         // Check the event details are correct.
1877         $this->assertInstanceOf('\core\event\course_viewed', $event);
1878         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1879         $this->assertEquals(1, $event->other['coursesectionnumber']);
1881         $result = core_course_external::view_course($course->id);
1882         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1883         $events = $sink->get_events();
1884         $event = array_pop($events);
1885         $sink->close();
1887         // Check the event details are correct.
1888         $this->assertInstanceOf('\core\event\course_viewed', $event);
1889         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1890         $this->assertEmpty($event->other);
1892     }
1894     /**
1895      * Test get_course_module
1896      */
1897     public function test_get_course_module() {
1898         global $DB;
1900         $this->resetAfterTest(true);
1902         $this->setAdminUser();
1903         $course = self::getDataGenerator()->create_course();
1904         $record = array(
1905             'course' => $course->id,
1906             'name' => 'First Assignment'
1907         );
1908         $options = array(
1909             'idnumber' => 'ABC',
1910             'visible' => 0
1911         );
1912         // Hidden activity.
1913         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
1915         $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
1917         // Insert a custom grade scale to be used by an outcome.
1918         $gradescale = new grade_scale();
1919         $gradescale->name        = 'gettcoursemodulescale';
1920         $gradescale->courseid    = $course->id;
1921         $gradescale->userid      = 0;
1922         $gradescale->scale       = $outcomescale;
1923         $gradescale->description = 'This scale is used to mark standard assignments.';
1924         $gradescale->insert();
1926         // Insert an outcome.
1927         $data = new stdClass();
1928         $data->courseid = $course->id;
1929         $data->fullname = 'Team work';
1930         $data->shortname = 'Team work';
1931         $data->scaleid = $gradescale->id;
1932         $outcome = new grade_outcome($data, false);
1933         $outcome->insert();
1935         $outcomegradeitem = new grade_item();
1936         $outcomegradeitem->itemname = $outcome->shortname;
1937         $outcomegradeitem->itemtype = 'mod';
1938         $outcomegradeitem->itemmodule = 'assign';
1939         $outcomegradeitem->iteminstance = $assign->id;
1940         $outcomegradeitem->outcomeid = $outcome->id;
1941         $outcomegradeitem->cmid = 0;
1942         $outcomegradeitem->courseid = $course->id;
1943         $outcomegradeitem->aggregationcoef = 0;
1944         $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
1945         $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
1946         $outcomegradeitem->scaleid = $outcome->scaleid;
1947         $outcomegradeitem->insert();
1949         $assignmentgradeitem = grade_item::fetch(
1950             array(
1951                 'itemtype' => 'mod',
1952                 'itemmodule' => 'assign',
1953                 'iteminstance' => $assign->id,
1954                 'itemnumber' => 0,
1955                 'courseid' => $course->id
1956             )
1957         );
1958         $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
1959         $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
1961         // Test admin user can see the complete hidden activity.
1962         $result = core_course_external::get_course_module($assign->cmid);
1963         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1965         $this->assertCount(0, $result['warnings']);
1966         // Test we retrieve all the fields.
1967         $this->assertCount(28, $result['cm']);
1968         $this->assertEquals($record['name'], $result['cm']['name']);
1969         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1970         $this->assertEquals(100, $result['cm']['grade']);
1971         $this->assertEquals(0.0, $result['cm']['gradepass']);
1972         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
1973         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
1974         $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
1976         $student = $this->getDataGenerator()->create_user();
1977         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1979         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1980         $this->setUser($student);
1982         // The user shouldn't be able to see the activity.
1983         try {
1984             core_course_external::get_course_module($assign->cmid);
1985             $this->fail('Exception expected due to invalid permissions.');
1986         } catch (moodle_exception $e) {
1987             $this->assertEquals('requireloginerror', $e->errorcode);
1988         }
1990         // Make module visible.
1991         set_coursemodule_visible($assign->cmid, 1);
1993         // Test student user.
1994         $result = core_course_external::get_course_module($assign->cmid);
1995         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1997         $this->assertCount(0, $result['warnings']);
1998         // Test we retrieve only the few files we can see.
1999         $this->assertCount(11, $result['cm']);
2000         $this->assertEquals($assign->cmid, $result['cm']['id']);
2001         $this->assertEquals($course->id, $result['cm']['course']);
2002         $this->assertEquals('assign', $result['cm']['modname']);
2003         $this->assertEquals($assign->id, $result['cm']['instance']);
2005     }
2007     /**
2008      * Test get_course_module_by_instance
2009      */
2010     public function test_get_course_module_by_instance() {
2011         global $DB;
2013         $this->resetAfterTest(true);
2015         $this->setAdminUser();
2016         $course = self::getDataGenerator()->create_course();
2017         $record = array(
2018             'course' => $course->id,
2019             'name' => 'First quiz',
2020             'grade' => 90.00
2021         );
2022         $options = array(
2023             'idnumber' => 'ABC',
2024             'visible' => 0
2025         );
2026         // Hidden activity.
2027         $quiz = self::getDataGenerator()->create_module('quiz', $record, $options);
2029         // Test admin user can see the complete hidden activity.
2030         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2031         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
2033         $this->assertCount(0, $result['warnings']);
2034         // Test we retrieve all the fields.
2035         $this->assertCount(26, $result['cm']);
2036         $this->assertEquals($record['name'], $result['cm']['name']);
2037         $this->assertEquals($record['grade'], $result['cm']['grade']);
2038         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
2040         $student = $this->getDataGenerator()->create_user();
2041         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2043         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
2044         $this->setUser($student);
2046         // The user shouldn't be able to see the activity.
2047         try {
2048             core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2049             $this->fail('Exception expected due to invalid permissions.');
2050         } catch (moodle_exception $e) {
2051             $this->assertEquals('requireloginerror', $e->errorcode);
2052         }
2054         // Make module visible.
2055         set_coursemodule_visible($quiz->cmid, 1);
2057         // Test student user.
2058         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2059         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
2061         $this->assertCount(0, $result['warnings']);
2062         // Test we retrieve only the few files we can see.
2063         $this->assertCount(11, $result['cm']);
2064         $this->assertEquals($quiz->cmid, $result['cm']['id']);
2065         $this->assertEquals($course->id, $result['cm']['course']);
2066         $this->assertEquals('quiz', $result['cm']['modname']);
2067         $this->assertEquals($quiz->id, $result['cm']['instance']);
2069         // Try with an invalid module name.
2070         try {
2071             core_course_external::get_course_module_by_instance('abc', $quiz->id);
2072             $this->fail('Exception expected due to invalid module name.');
2073         } catch (dml_read_exception $e) {
2074             $this->assertEquals('dmlreadexception', $e->errorcode);
2075         }
2077     }
2079     /**
2080      * Test get_activities_overview
2081      */
2082     public function test_get_activities_overview() {
2083         global $USER;
2085         $this->resetAfterTest();
2086         $course1 = self::getDataGenerator()->create_course();
2087         $course2 = self::getDataGenerator()->create_course();
2089         // Create a viewer user.
2090         $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
2091         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2092         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2094         // Create two forums - one in each course.
2095         $record = new stdClass();
2096         $record->course = $course1->id;
2097         $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
2098         $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
2100         $this->setAdminUser();
2101         // A standard post in the forum.
2102         $record = new stdClass();
2103         $record->course = $course1->id;
2104         $record->userid = $USER->id;
2105         $record->forum = $forum1->id;
2106         $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
2108         $this->setUser($viewer->id);
2109         $courses = array($course1->id , $course2->id);
2111         $result = core_course_external::get_activities_overview($courses);
2112         $this->assertDebuggingCalledCount(8);
2113         $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
2115         // There should be one entry for course1, and no others.
2116         $this->assertCount(1, $result['courses']);
2117         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2118         // Check expected overview data for the module.
2119         $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
2120         $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
2121     }
2123     /**
2124      * Test get_user_navigation_options
2125      */
2126     public function test_get_user_navigation_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_navigation_options($courses);
2142         $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
2144         $this->assertCount(0, $result['warnings']);
2145         $this->assertCount(3, $result['courses']);
2147         foreach ($result['courses'] as $course) {
2148             $navoptions = new stdClass;
2149             foreach ($course['options'] as $option) {
2150                 $navoptions->{$option['name']} = $option['available'];
2151             }
2152             $this->assertCount(9, $course['options']);
2153             if ($course['id'] == SITEID) {
2154                 $this->assertTrue($navoptions->blogs);
2155                 $this->assertFalse($navoptions->notes);
2156                 $this->assertFalse($navoptions->participants);
2157                 $this->assertTrue($navoptions->badges);
2158                 $this->assertTrue($navoptions->tags);
2159                 $this->assertFalse($navoptions->grades);
2160                 $this->assertFalse($navoptions->search);
2161                 $this->assertTrue($navoptions->calendar);
2162                 $this->assertTrue($navoptions->competencies);
2163             } else {
2164                 $this->assertTrue($navoptions->blogs);
2165                 $this->assertFalse($navoptions->notes);
2166                 $this->assertTrue($navoptions->participants);
2167                 $this->assertTrue($navoptions->badges);
2168                 $this->assertFalse($navoptions->tags);
2169                 $this->assertTrue($navoptions->grades);
2170                 $this->assertFalse($navoptions->search);
2171                 $this->assertFalse($navoptions->calendar);
2172                 $this->assertTrue($navoptions->competencies);
2173             }
2174         }
2175     }
2177     /**
2178      * Test get_user_administration_options
2179      */
2180     public function test_get_user_administration_options() {
2181         global $USER;
2183         $this->resetAfterTest();
2184         $course1 = self::getDataGenerator()->create_course();
2185         $course2 = self::getDataGenerator()->create_course();
2187         // Create a viewer user.
2188         $viewer = self::getDataGenerator()->create_user();
2189         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2190         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2192         $this->setUser($viewer->id);
2193         $courses = array($course1->id , $course2->id, SITEID);
2195         $result = core_course_external::get_user_administration_options($courses);
2196         $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
2198         $this->assertCount(0, $result['warnings']);
2199         $this->assertCount(3, $result['courses']);
2201         foreach ($result['courses'] as $course) {
2202             $adminoptions = new stdClass;
2203             foreach ($course['options'] as $option) {
2204                 $adminoptions->{$option['name']} = $option['available'];
2205             }
2206             if ($course['id'] == SITEID) {
2207                 $this->assertCount(16, $course['options']);
2208                 $this->assertFalse($adminoptions->update);
2209                 $this->assertFalse($adminoptions->filters);
2210                 $this->assertFalse($adminoptions->reports);
2211                 $this->assertFalse($adminoptions->backup);
2212                 $this->assertFalse($adminoptions->restore);
2213                 $this->assertFalse($adminoptions->files);
2214                 $this->assertFalse(!isset($adminoptions->tags));
2215                 $this->assertFalse($adminoptions->gradebook);
2216                 $this->assertFalse($adminoptions->outcomes);
2217                 $this->assertFalse($adminoptions->badges);
2218                 $this->assertFalse($adminoptions->import);
2219                 $this->assertFalse($adminoptions->publish);
2220                 $this->assertFalse($adminoptions->reset);
2221                 $this->assertFalse($adminoptions->roles);
2222                 $this->assertFalse($adminoptions->editcompletion);
2223             } else {
2224                 $this->assertCount(15, $course['options']);
2225                 $this->assertFalse($adminoptions->update);
2226                 $this->assertFalse($adminoptions->filters);
2227                 $this->assertFalse($adminoptions->reports);
2228                 $this->assertFalse($adminoptions->backup);
2229                 $this->assertFalse($adminoptions->restore);
2230                 $this->assertFalse($adminoptions->files);
2231                 $this->assertFalse($adminoptions->tags);
2232                 $this->assertFalse($adminoptions->gradebook);
2233                 $this->assertFalse($adminoptions->outcomes);
2234                 $this->assertTrue($adminoptions->badges);
2235                 $this->assertFalse($adminoptions->import);
2236                 $this->assertFalse($adminoptions->publish);
2237                 $this->assertFalse($adminoptions->reset);
2238                 $this->assertFalse($adminoptions->roles);
2239                 $this->assertFalse($adminoptions->editcompletion);
2240             }
2241         }
2242     }
2244     /**
2245      * Test get_courses_by_fields
2246      */
2247     public function test_get_courses_by_field() {
2248         global $DB;
2249         $this->resetAfterTest(true);
2251         $category1 = self::getDataGenerator()->create_category(array('name' => 'Cat 1'));
2252         $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
2253         $course1 = self::getDataGenerator()->create_course(
2254             array('category' => $category1->id, 'shortname' => 'c1', 'format' => 'topics'));
2255         $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
2257         $student1 = self::getDataGenerator()->create_user();
2258         $user1 = self::getDataGenerator()->create_user();
2259         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2260         self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
2261         self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
2263         self::setAdminUser();
2264         // As admins, we should be able to retrieve everything.
2265         $result = core_course_external::get_courses_by_field();
2266         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2267         $this->assertCount(3, $result['courses']);
2268         // Expect to receive all the fields.
2269         $this->assertCount(37, $result['courses'][0]);
2270         $this->assertCount(38, $result['courses'][1]);  // One more field because is not the site course.
2271         $this->assertCount(38, $result['courses'][2]);  // One more field because is not the site course.
2273         $result = core_course_external::get_courses_by_field('id', $course1->id);
2274         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2275         $this->assertCount(1, $result['courses']);
2276         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2277         // Expect to receive all the fields.
2278         $this->assertCount(38, $result['courses'][0]);
2279         // Check default values for course format topics.
2280         $this->assertCount(2, $result['courses'][0]['courseformatoptions']);
2281         foreach ($result['courses'][0]['courseformatoptions'] as $option) {
2282             if ($option['name'] == 'hiddensections') {
2283                 $this->assertEquals(0, $option['value']);
2284             } else {
2285                 $this->assertEquals('coursedisplay', $option['name']);
2286                 $this->assertEquals(0, $option['value']);
2287             }
2288         }
2290         $result = core_course_external::get_courses_by_field('id', $course2->id);
2291         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2292         $this->assertCount(1, $result['courses']);
2293         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2295         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2296         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2297         $this->assertCount(2, $result['courses']);
2299         // Check default filters.
2300         $this->assertCount(3, $result['courses'][0]['filters']);
2301         $this->assertCount(3, $result['courses'][1]['filters']);
2303         $result = core_course_external::get_courses_by_field('category', $category1->id);
2304         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2305         $this->assertCount(1, $result['courses']);
2306         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2307         $this->assertEquals('Cat 1', $result['courses'][0]['categoryname']);
2309         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2310         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2311         $this->assertCount(1, $result['courses']);
2312         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2314         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2315         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2316         $this->assertCount(1, $result['courses']);
2317         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2319         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2320         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2321         $this->assertCount(0, $result['courses']);
2323         // Change filter value.
2324         filter_set_local_state('mediaplugin', context_course::instance($course1->id)->id, TEXTFILTER_OFF);
2326         self::setUser($student1);
2327         // All visible courses  (including front page) for normal student.
2328         $result = core_course_external::get_courses_by_field();
2329         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2330         $this->assertCount(2, $result['courses']);
2331         $this->assertCount(30, $result['courses'][0]);
2332         $this->assertCount(31, $result['courses'][1]);  // One field more (course format options), not present in site course.
2334         $result = core_course_external::get_courses_by_field('id', $course1->id);
2335         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2336         $this->assertCount(1, $result['courses']);
2337         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2338         // Expect to receive all the files that a student can see.
2339         $this->assertCount(31, $result['courses'][0]);
2341         // Check default filters.
2342         $filters = $result['courses'][0]['filters'];
2343         $this->assertCount(3, $filters);
2344         $found = false;
2345         foreach ($filters as $filter) {
2346             if ($filter['filter'] == 'mediaplugin' and $filter['localstate'] == TEXTFILTER_OFF) {
2347                 $found = true;
2348             }
2349         }
2350         $this->assertTrue($found);
2352         // Course 2 is not visible.
2353         $result = core_course_external::get_courses_by_field('id', $course2->id);
2354         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2355         $this->assertCount(0, $result['courses']);
2357         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2358         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2359         $this->assertCount(1, $result['courses']);
2361         $result = core_course_external::get_courses_by_field('category', $category1->id);
2362         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2363         $this->assertCount(1, $result['courses']);
2364         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2366         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2367         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2368         $this->assertCount(1, $result['courses']);
2369         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2371         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2372         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2373         $this->assertCount(0, $result['courses']);
2375         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2376         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2377         $this->assertCount(0, $result['courses']);
2379         self::setUser($user1);
2380         // All visible courses (including front page) for authenticated user.
2381         $result = core_course_external::get_courses_by_field();
2382         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2383         $this->assertCount(2, $result['courses']);
2384         $this->assertCount(30, $result['courses'][0]);  // Site course.
2385         $this->assertCount(13, $result['courses'][1]);  // Only public information, not enrolled.
2387         $result = core_course_external::get_courses_by_field('id', $course1->id);
2388         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2389         $this->assertCount(1, $result['courses']);
2390         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2391         // Expect to receive all the files that a authenticated can see.
2392         $this->assertCount(13, $result['courses'][0]);
2394         // Course 2 is not visible.
2395         $result = core_course_external::get_courses_by_field('id', $course2->id);
2396         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2397         $this->assertCount(0, $result['courses']);
2399         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2400         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2401         $this->assertCount(1, $result['courses']);
2403         $result = core_course_external::get_courses_by_field('category', $category1->id);
2404         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2405         $this->assertCount(1, $result['courses']);
2406         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2408         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2409         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2410         $this->assertCount(1, $result['courses']);
2411         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2413         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2414         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2415         $this->assertCount(0, $result['courses']);
2417         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2418         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2419         $this->assertCount(0, $result['courses']);
2420     }
2422     public function test_get_courses_by_field_invalid_field() {
2423         $this->expectException('invalid_parameter_exception');
2424         $result = core_course_external::get_courses_by_field('zyx', 'x');
2425     }
2427     public function test_get_courses_by_field_invalid_courses() {
2428         $result = core_course_external::get_courses_by_field('id', '-1');
2429         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2430         $this->assertCount(0, $result['courses']);
2431     }
2433     /**
2434      * Test get_courses_by_field_invalid_theme_and_lang
2435      */
2436     public function test_get_courses_by_field_invalid_theme_and_lang() {
2437         $this->resetAfterTest(true);
2438         $this->setAdminUser();
2440         $course = self::getDataGenerator()->create_course(array('theme' => 'kkt', 'lang' => 'kkl'));
2441         $result = core_course_external::get_courses_by_field('id', $course->id);
2442         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2443         $this->assertEmpty($result['courses']['0']['theme']);
2444         $this->assertEmpty($result['courses']['0']['lang']);
2445     }
2448     public function test_check_updates() {
2449         global $DB;
2450         $this->resetAfterTest(true);
2451         $this->setAdminUser();
2453         // Create different types of activities.
2454         $course  = self::getDataGenerator()->create_course();
2455         $tocreate = array('assign', 'book', 'choice', 'folder', 'forum', 'glossary', 'imscp', 'label', 'lti', 'page', 'quiz',
2456                             'resource', 'scorm', 'survey', 'url', 'wiki');
2458         $modules = array();
2459         foreach ($tocreate as $modname) {
2460             $modules[$modname]['instance'] = $this->getDataGenerator()->create_module($modname, array('course' => $course->id));
2461             $modules[$modname]['cm'] = get_coursemodule_from_id(false, $modules[$modname]['instance']->cmid);
2462             $modules[$modname]['context'] = context_module::instance($modules[$modname]['instance']->cmid);
2463         }
2465         $student = self::getDataGenerator()->create_user();
2466         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2467         self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
2468         $this->setUser($student);
2470         $since = time();
2471         $this->waitForSecond();
2472         $params = array();
2473         foreach ($modules as $modname => $data) {
2474             $params[$data['cm']->id] = array(
2475                 'contextlevel' => 'module',
2476                 'id' => $data['cm']->id,
2477                 'since' => $since
2478             );
2479         }
2481         // Check there is nothing updated because modules are fresh new.
2482         $result = core_course_external::check_updates($course->id, $params);
2483         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2484         $this->assertCount(0, $result['instances']);
2485         $this->assertCount(0, $result['warnings']);
2487         // Test with get_updates_since the same data.
2488         $result = core_course_external::get_updates_since($course->id, $since);
2489         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2490         $this->assertCount(0, $result['instances']);
2491         $this->assertCount(0, $result['warnings']);
2493         // Update a module after a second.
2494         $this->waitForSecond();
2495         set_coursemodule_name($modules['forum']['cm']->id, 'New forum name');
2497         $found = false;
2498         $result = core_course_external::check_updates($course->id, $params);
2499         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2500         $this->assertCount(1, $result['instances']);
2501         $this->assertCount(0, $result['warnings']);
2502         foreach ($result['instances'] as $module) {
2503             foreach ($module['updates'] as $update) {
2504                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2505                     $found = true;
2506                 }
2507             }
2508         }
2509         $this->assertTrue($found);
2511         // Test with get_updates_since the same data.
2512         $result = core_course_external::get_updates_since($course->id, $since);
2513         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2514         $this->assertCount(1, $result['instances']);
2515         $this->assertCount(0, $result['warnings']);
2516         $found = false;
2517         $this->assertCount(1, $result['instances']);
2518         $this->assertCount(0, $result['warnings']);
2519         foreach ($result['instances'] as $module) {
2520             foreach ($module['updates'] as $update) {
2521                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2522                     $found = true;
2523                 }
2524             }
2525         }
2526         $this->assertTrue($found);
2528         // Do not retrieve the configuration field.
2529         $filter = array('files');
2530         $found = false;
2531         $result = core_course_external::check_updates($course->id, $params, $filter);
2532         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2533         $this->assertCount(0, $result['instances']);
2534         $this->assertCount(0, $result['warnings']);
2535         $this->assertFalse($found);
2537         // Add invalid cmid.
2538         $params[] = array(
2539             'contextlevel' => 'module',
2540             'id' => -2,
2541             'since' => $since
2542         );
2543         $result = core_course_external::check_updates($course->id, $params);
2544         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2545         $this->assertCount(1, $result['warnings']);
2546         $this->assertEquals(-2, $result['warnings'][0]['itemid']);
2547     }
2549     /**
2550      * Test cases for the get_enrolled_courses_by_timeline_classification test.
2551      */
2552     public function get_get_enrolled_courses_by_timeline_classification_test_cases() {
2553         $now = time();
2554         $day = 86400;
2556         $coursedata = [
2557             [
2558                 'shortname' => 'apast',
2559                 'startdate' => $now - ($day * 2),
2560                 'enddate' => $now - $day
2561             ],
2562             [
2563                 'shortname' => 'bpast',
2564                 'startdate' => $now - ($day * 2),
2565                 'enddate' => $now - $day
2566             ],
2567             [
2568                 'shortname' => 'cpast',
2569                 'startdate' => $now - ($day * 2),
2570                 'enddate' => $now - $day
2571             ],
2572             [
2573                 'shortname' => 'dpast',
2574                 'startdate' => $now - ($day * 2),
2575                 'enddate' => $now - $day
2576             ],
2577             [
2578                 'shortname' => 'epast',
2579                 'startdate' => $now - ($day * 2),
2580                 'enddate' => $now - $day
2581             ],
2582             [
2583                 'shortname' => 'ainprogress',
2584                 'startdate' => $now - $day,
2585                 'enddate' => $now + $day
2586             ],
2587             [
2588                 'shortname' => 'binprogress',
2589                 'startdate' => $now - $day,
2590                 'enddate' => $now + $day
2591             ],
2592             [
2593                 'shortname' => 'cinprogress',
2594                 'startdate' => $now - $day,
2595                 'enddate' => $now + $day
2596             ],
2597             [
2598                 'shortname' => 'dinprogress',
2599                 'startdate' => $now - $day,
2600                 'enddate' => $now + $day
2601             ],
2602             [
2603                 'shortname' => 'einprogress',
2604                 'startdate' => $now - $day,
2605                 'enddate' => $now + $day
2606             ],
2607             [
2608                 'shortname' => 'afuture',
2609                 'startdate' => $now + $day
2610             ],
2611             [
2612                 'shortname' => 'bfuture',
2613                 'startdate' => $now + $day
2614             ],
2615             [
2616                 'shortname' => 'cfuture',
2617                 'startdate' => $now + $day
2618             ],
2619             [
2620                 'shortname' => 'dfuture',
2621                 'startdate' => $now + $day
2622             ],
2623             [
2624                 'shortname' => 'efuture',
2625                 'startdate' => $now + $day
2626             ]
2627         ];
2629         // Raw enrolled courses result set should be returned in this order:
2630         // afuture, ainprogress, apast, bfuture, binprogress, bpast, cfuture, cinprogress, cpast,
2631         // dfuture, dinprogress, dpast, efuture, einprogress, epast
2632         //
2633         // By classification the offset values for each record should be:
2634         // COURSE_TIMELINE_FUTURE
2635         // 0 (afuture), 3 (bfuture), 6 (cfuture), 9 (dfuture), 12 (efuture)
2636         // COURSE_TIMELINE_INPROGRESS
2637         // 1 (ainprogress), 4 (binprogress), 7 (cinprogress), 10 (dinprogress), 13 (einprogress)
2638         // COURSE_TIMELINE_PAST
2639         // 2 (apast), 5 (bpast), 8 (cpast), 11 (dpast), 14 (epast).
2640         //
2641         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2642         // filtering is done.
2643         // E.g. In our example if an offset of 2 is given then it would mean the first
2644         // two courses (afuture, ainprogress) are ignored.
2645         return [
2646             'empty set' => [
2647                 'coursedata' => [],
2648                 'classification' => 'future',
2649                 'limit' => 2,
2650                 'offset' => 0,
2651                 'expectedcourses' => [],
2652                 'expectednextoffset' => 0
2653             ],
2654             // COURSE_TIMELINE_FUTURE.
2655             'future not limit no offset' => [
2656                 'coursedata' => $coursedata,
2657                 'classification' => 'future',
2658                 'limit' => 0,
2659                 'offset' => 0,
2660                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2661                 'expectednextoffset' => 15
2662             ],
2663             'future no offset' => [
2664                 'coursedata' => $coursedata,
2665                 'classification' => 'future',
2666                 'limit' => 2,
2667                 'offset' => 0,
2668                 'expectedcourses' => ['afuture', 'bfuture'],
2669                 'expectednextoffset' => 4
2670             ],
2671             'future offset' => [
2672                 'coursedata' => $coursedata,
2673                 'classification' => 'future',
2674                 'limit' => 2,
2675                 'offset' => 2,
2676                 'expectedcourses' => ['bfuture', 'cfuture'],
2677                 'expectednextoffset' => 7
2678             ],
2679             'future exact limit' => [
2680                 'coursedata' => $coursedata,
2681                 'classification' => 'future',
2682                 'limit' => 5,
2683                 'offset' => 0,
2684                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2685                 'expectednextoffset' => 13
2686             ],
2687             'future limit less results' => [
2688                 'coursedata' => $coursedata,
2689                 'classification' => 'future',
2690                 'limit' => 10,
2691                 'offset' => 0,
2692                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2693                 'expectednextoffset' => 15
2694             ],
2695             'future limit less results with offset' => [
2696                 'coursedata' => $coursedata,
2697                 'classification' => 'future',
2698                 'limit' => 10,
2699                 'offset' => 5,
2700                 'expectedcourses' => ['cfuture', 'dfuture', 'efuture'],
2701                 'expectednextoffset' => 15
2702             ],
2703             'all no limit or offset' => [
2704                 'coursedata' => $coursedata,
2705                 'classification' => 'all',
2706                 'limit' => 0,
2707                 'offset' => 0,
2708                 'expectedcourses' => [
2709                     'afuture',
2710                     'ainprogress',
2711                     'apast',
2712                     'bfuture',
2713                     'binprogress',
2714                     'bpast',
2715                     'cfuture',
2716                     'cinprogress',
2717                     'cpast',
2718                     'dfuture',
2719                     'dinprogress',
2720                     'dpast',
2721                     'efuture',
2722                     'einprogress',
2723                     'epast'
2724                 ],
2725                 'expectednextoffset' => 15
2726             ],
2727             'all limit no offset' => [
2728                 'coursedata' => $coursedata,
2729                 'classification' => 'all',
2730                 'limit' => 5,
2731                 'offset' => 0,
2732                 'expectedcourses' => [
2733                     'afuture',
2734                     'ainprogress',
2735                     'apast',
2736                     'bfuture',
2737                     'binprogress'
2738                 ],
2739                 'expectednextoffset' => 5
2740             ],
2741             'all limit and offset' => [
2742                 'coursedata' => $coursedata,
2743                 'classification' => 'all',
2744                 'limit' => 5,
2745                 'offset' => 5,
2746                 'expectedcourses' => [
2747                     'bpast',
2748                     'cfuture',
2749                     'cinprogress',
2750                     'cpast',
2751                     'dfuture'
2752                 ],
2753                 'expectednextoffset' => 10
2754             ],
2755             'all offset past result set' => [
2756                 'coursedata' => $coursedata,
2757                 'classification' => 'all',
2758                 'limit' => 5,
2759                 'offset' => 50,
2760                 'expectedcourses' => [],
2761                 'expectednextoffset' => 50
2762             ],
2763         ];
2764     }
2766     /**
2767      * Test the get_enrolled_courses_by_timeline_classification function.
2768      *
2769      * @dataProvider get_get_enrolled_courses_by_timeline_classification_test_cases()
2770      * @param array $coursedata Courses to create
2771      * @param string $classification Timeline classification
2772      * @param int $limit Maximum number of results
2773      * @param int $offset Offset the unfiltered courses result set by this amount
2774      * @param array $expectedcourses Expected courses in result
2775      * @param int $expectednextoffset Expected next offset value in result
2776      */
2777     public function test_get_enrolled_courses_by_timeline_classification(
2778         $coursedata,
2779         $classification,
2780         $limit,
2781         $offset,
2782         $expectedcourses,
2783         $expectednextoffset
2784     ) {
2785         $this->resetAfterTest();
2786         $generator = $this->getDataGenerator();
2788         $courses = array_map(function($coursedata) use ($generator) {
2789             return $generator->create_course($coursedata);
2790         }, $coursedata);
2792         $student = $generator->create_user();
2794         foreach ($courses as $course) {
2795             $generator->enrol_user($student->id, $course->id, 'student');
2796         }
2798         $this->setUser($student);
2800         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2801         // filtering is done.
2802         // E.g. In our example if an offset of 2 is given then it would mean the first
2803         // two courses (afuture, ainprogress) are ignored.
2804         $result = core_course_external::get_enrolled_courses_by_timeline_classification(
2805             $classification,
2806             $limit,
2807             $offset,
2808             'shortname ASC'
2809         );
2810         $result = external_api::clean_returnvalue(
2811             core_course_external::get_enrolled_courses_by_timeline_classification_returns(),
2812             $result
2813         );
2815         $actual = array_map(function($course) {
2816             return $course['shortname'];
2817         }, $result['courses']);
2819         $this->assertEquals($expectedcourses, $actual);
2820         $this->assertEquals($expectednextoffset, $result['nextoffset']);
2821     }
2823     /**
2824      * Test the get_recent_courses function.
2825      */
2826     public function test_get_recent_courses() {
2827         global $USER, $DB;
2829         $this->resetAfterTest();
2830         $generator = $this->getDataGenerator();
2832         set_config('hiddenuserfields', 'lastaccess');
2834         $courses = array();
2835         for ($i = 1; $i < 12; $i++) {
2836             $courses[]  = $generator->create_course();
2837         };
2839         $student = $generator->create_user();
2840         $teacher = $generator->create_user();
2842         foreach ($courses as $course) {
2843             $generator->enrol_user($student->id, $course->id, 'student');
2844         }
2846         $generator->enrol_user($teacher->id, $courses[0]->id, 'teacher');
2848         $this->setUser($student);
2850         $result = core_course_external::get_recent_courses($USER->id);
2852         // No course accessed.
2853         $this->assertCount(0, $result);
2855         foreach ($courses as $course) {
2856             core_course_external::view_course($course->id);
2857         }
2859         // Every course accessed.
2860         $result = core_course_external::get_recent_courses($USER->id);
2861         $this->assertCount( 11, $result);
2863         // Every course accessed, result limited to 10 courses.
2864         $result = core_course_external::get_recent_courses($USER->id, 10);
2865         $this->assertCount(10, $result);
2867         $guestcourse = $generator->create_course(
2868                 (object)array('shortname' => 'guestcourse',
2869                 'enrol_guest_status_0' => ENROL_INSTANCE_ENABLED,
2870                 'enrol_guest_password_0' => ''));
2871         core_course_external::view_course($guestcourse->id);
2873         // Every course accessed, even the not enrolled one.
2874         $result = core_course_external::get_recent_courses($USER->id);
2875         $this->assertCount(12, $result);
2877         // Offset 5, return 7 out of 12.
2878         $result = core_course_external::get_recent_courses($USER->id, 0, 5);
2879         $this->assertCount(7, $result);
2881         // Offset 5 and limit 3, return 3 out of 12.
2882         $result = core_course_external::get_recent_courses($USER->id, 3, 5);
2883         $this->assertCount(3, $result);
2885         // Sorted by course id ASC.
2886         $result = core_course_external::get_recent_courses($USER->id, 0, 0, 'id ASC');
2887         $this->assertEquals($courses[0]->id, array_shift($result)->id);
2889         // Sorted by course id DESC.
2890         $result = core_course_external::get_recent_courses($USER->id, 0, 0, 'id DESC');
2891         $this->assertEquals($guestcourse->id, array_shift($result)->id);
2893         // If last access is hidden, only get the courses where has viewhiddenuserfields capability.
2894         $this->setUser($teacher);
2895         $teacherroleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher'));
2896         $usercontext = context_user::instance($student->id);
2897         $this->assignUserCapability('moodle/user:viewdetails', $usercontext, $teacherroleid);
2899         // Sorted by course id DESC.
2900         $result = core_course_external::get_recent_courses($student->id);
2901         $this->assertCount(1, $result);
2902         $this->assertEquals($courses[0]->id, array_shift($result)->id);
2903     }