674ee827c662386c7ef0950e2e8976d00509daea
[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, 'completion' => COMPLETION_TRACKING_MANUAL));
874         $labelcm = get_coursemodule_from_instance('label', $label->id);
875         $tomorrow = time() + DAYSECS;
876         // Module with availability restrictions not met.
877         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '},'
878                 .'{"type":"completion","cm":' . $label->cmid .',"e":1}],"showc":[true,true]}';
879         $url = $this->getDataGenerator()->create_module('url',
880             array('course' => $course->id, 'name' => 'URL: % & $ ../', 'section' => 2, 'display' => RESOURCELIB_DISPLAY_POPUP,
881                 'popupwidth' => 100, 'popupheight' => 100),
882             array('availability' => $availability));
883         $urlcm = get_coursemodule_from_instance('url', $url->id);
884         // Module for the last section.
885         $this->getDataGenerator()->create_module('url',
886             array('course' => $course->id, 'name' => 'URL for last section', 'section' => 3));
887         // Module for section 1 with availability restrictions met.
888         $yesterday = time() - DAYSECS;
889         $this->getDataGenerator()->create_module('url',
890             array('course' => $course->id, 'name' => 'URL restrictions met', 'section' => 1),
891             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":'. $yesterday .'}],"showc":[true]}'));
893         // Set the required capabilities by the external function.
894         $context = context_course::instance($course->id);
895         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
896         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
897         $this->assignUserCapability('mod/data:view', $context->id, $roleid);
899         $conditions = array('course' => $course->id, 'section' => 2);
900         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
902         // Add date availability condition not met for section 3.
903         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}';
904         $DB->set_field('course_sections', 'availability', $availability,
905                 array('course' => $course->id, 'section' => 3));
907         // Create resource for last section.
908         $pageinhiddensection = $this->getDataGenerator()->create_module('page',
909             array('course' => $course->id, 'name' => 'Page in hidden section', 'section' => 4));
910         // Set not visible last section.
911         $DB->set_field('course_sections', 'visible', 0,
912                 array('course' => $course->id, 'section' => 4));
914         rebuild_course_cache($course->id, true);
916         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
917     }
919     /**
920      * Test get_course_contents
921      */
922     public function test_get_course_contents() {
923         global $CFG;
924         $this->resetAfterTest(true);
926         $CFG->forum_allowforcedreadtracking = 1;
927         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
929         // We first run the test as admin.
930         $this->setAdminUser();
931         $sections = core_course_external::get_course_contents($course->id, array());
932         // We need to execute the return values cleaning process to simulate the web service server.
933         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
935         $modinfo = get_fast_modinfo($course);
936         $testexecuted = 0;
937         foreach ($sections[0]['modules'] as $module) {
938             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
939                 $cm = $modinfo->cms[$forumcm->id];
940                 $formattedtext = format_text($cm->content, FORMAT_HTML,
941                     array('noclean' => true, 'para' => false, 'filter' => false));
942                 $this->assertEquals($formattedtext, $module['description']);
943                 $this->assertEquals($forumcm->instance, $module['instance']);
944                 $this->assertContains('1 unread post', $module['afterlink']);
945                 $testexecuted = $testexecuted + 2;
946             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
947                 $cm = $modinfo->cms[$labelcm->id];
948                 $formattedtext = format_text($cm->content, FORMAT_HTML,
949                     array('noclean' => true, 'para' => false, 'filter' => false));
950                 $this->assertEquals($formattedtext, $module['description']);
951                 $this->assertEquals($labelcm->instance, $module['instance']);
952                 $testexecuted = $testexecuted + 1;
953             } else if ($module['id'] == $datacm->id and $module['modname'] == 'data') {
954                 $this->assertContains('customcompletionrules', $module['customdata']);
955                 $testexecuted = $testexecuted + 1;
956             }
957         }
958         foreach ($sections[2]['modules'] as $module) {
959             if ($module['id'] == $urlcm->id and $module['modname'] == 'url') {
960                 $this->assertContains('width=100,height=100', $module['onclick']);
961                 $this->assertContains('moodle.org', $module['customdata']);
962                 $testexecuted = $testexecuted + 1;
963             }
964         }
966         $CFG->forum_allowforcedreadtracking = 0;    // Recover original value.
967         forum_tp_count_forum_unread_posts($forumcm, $course, true);    // Reset static cache for further tests.
969         $this->assertEquals(5, $testexecuted);
970         $this->assertEquals(0, $sections[0]['section']);
972         $this->assertCount(5, $sections[0]['modules']);
973         $this->assertCount(1, $sections[1]['modules']);
974         $this->assertCount(1, $sections[2]['modules']);
975         $this->assertCount(1, $sections[3]['modules']); // One module for the section with availability restrictions.
976         $this->assertCount(1, $sections[4]['modules']); // One module for the hidden section with a visible activity.
977         $this->assertNotEmpty($sections[3]['availabilityinfo']);
978         $this->assertEquals(1, $sections[1]['section']);
979         $this->assertEquals(2, $sections[2]['section']);
980         $this->assertEquals(3, $sections[3]['section']);
981         $this->assertEquals(4, $sections[4]['section']);
982         $this->assertContains('<iframe', $sections[2]['summary']);
983         $this->assertContains('</iframe>', $sections[2]['summary']);
984         $this->assertNotEmpty($sections[2]['modules'][0]['availabilityinfo']);
985         try {
986             $sections = core_course_external::get_course_contents($course->id,
987                                                                     array(array("name" => "invalid", "value" => 1)));
988             $this->fail('Exception expected due to invalid option.');
989         } catch (moodle_exception $e) {
990             $this->assertEquals('errorinvalidparam', $e->errorcode);
991         }
992     }
995     /**
996      * Test get_course_contents as student
997      */
998     public function test_get_course_contents_student() {
999         global $DB;
1000         $this->resetAfterTest(true);
1002         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1004         $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
1005         $user = self::getDataGenerator()->create_user();
1006         self::getDataGenerator()->enrol_user($user->id, $course->id, $studentroleid);
1007         $this->setUser($user);
1009         $sections = core_course_external::get_course_contents($course->id, array());
1010         // We need to execute the return values cleaning process to simulate the web service server.
1011         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1013         $this->assertCount(4, $sections); // Nothing for the not visible section.
1014         $this->assertCount(5, $sections[0]['modules']);
1015         $this->assertCount(1, $sections[1]['modules']);
1016         $this->assertCount(1, $sections[2]['modules']);
1017         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
1019         $this->assertNotEmpty($sections[3]['availabilityinfo']);
1020         $this->assertEquals(1, $sections[1]['section']);
1021         $this->assertEquals(2, $sections[2]['section']);
1022         $this->assertEquals(3, $sections[3]['section']);
1023         // The module with the availability restriction met is returning contents.
1024         $this->assertNotEmpty($sections[1]['modules'][0]['contents']);
1025         // The module with the availability restriction not met is not returning contents.
1026         $this->assertArrayNotHasKey('contents', $sections[2]['modules'][0]);
1028         // Now include flag for returning stealth information (fake section).
1029         $sections = core_course_external::get_course_contents($course->id,
1030             array(array("name" => "includestealthmodules", "value" => 1)));
1031         // We need to execute the return values cleaning process to simulate the web service server.
1032         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1034         $this->assertCount(5, $sections); // Include fake section with stealth activities.
1035         $this->assertCount(5, $sections[0]['modules']);
1036         $this->assertCount(1, $sections[1]['modules']);
1037         $this->assertCount(1, $sections[2]['modules']);
1038         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
1039         $this->assertCount(1, $sections[4]['modules']); // One stealh module.
1040         $this->assertEquals(-1, $sections[4]['id']);
1041     }
1043     /**
1044      * Test get_course_contents excluding modules
1045      */
1046     public function test_get_course_contents_excluding_modules() {
1047         $this->resetAfterTest(true);
1049         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1051         // Test exclude modules.
1052         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
1054         // We need to execute the return values cleaning process to simulate the web service server.
1055         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1057         $this->assertEmpty($sections[0]['modules']);
1058         $this->assertEmpty($sections[1]['modules']);
1059     }
1061     /**
1062      * Test get_course_contents excluding contents
1063      */
1064     public function test_get_course_contents_excluding_contents() {
1065         $this->resetAfterTest(true);
1067         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1069         // Test exclude modules.
1070         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
1072         // We need to execute the return values cleaning process to simulate the web service server.
1073         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1075         foreach ($sections as $section) {
1076             foreach ($section['modules'] as $module) {
1077                 // Only resources return contents.
1078                 if (isset($module['contents'])) {
1079                     $this->assertEmpty($module['contents']);
1080                 }
1081             }
1082         }
1083     }
1085     /**
1086      * Test get_course_contents filtering by section number
1087      */
1088     public function test_get_course_contents_section_number() {
1089         $this->resetAfterTest(true);
1091         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1093         // Test exclude modules.
1094         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
1096         // We need to execute the return values cleaning process to simulate the web service server.
1097         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1099         $this->assertCount(1, $sections);
1100         $this->assertCount(5, $sections[0]['modules']);
1101     }
1103     /**
1104      * Test get_course_contents filtering by cmid
1105      */
1106     public function test_get_course_contents_cmid() {
1107         $this->resetAfterTest(true);
1109         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1111         // Test exclude modules.
1112         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
1114         // We need to execute the return values cleaning process to simulate the web service server.
1115         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1117         $this->assertCount(4, $sections);
1118         $this->assertCount(1, $sections[0]['modules']);
1119         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1120     }
1123     /**
1124      * Test get_course_contents filtering by cmid and section
1125      */
1126     public function test_get_course_contents_section_cmid() {
1127         $this->resetAfterTest(true);
1129         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1131         // Test exclude modules.
1132         $sections = core_course_external::get_course_contents($course->id, array(
1133                                                                         array("name" => "cmid", "value" => $forumcm->id),
1134                                                                         array("name" => "sectionnumber", "value" => 0)
1135                                                                         ));
1137         // We need to execute the return values cleaning process to simulate the web service server.
1138         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1140         $this->assertCount(1, $sections);
1141         $this->assertCount(1, $sections[0]['modules']);
1142         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1143     }
1145     /**
1146      * Test get_course_contents filtering by modname
1147      */
1148     public function test_get_course_contents_modname() {
1149         $this->resetAfterTest(true);
1151         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1153         // Test exclude modules.
1154         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
1156         // We need to execute the return values cleaning process to simulate the web service server.
1157         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1159         $this->assertCount(4, $sections);
1160         $this->assertCount(1, $sections[0]['modules']);
1161         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1162     }
1164     /**
1165      * Test get_course_contents filtering by modname
1166      */
1167     public function test_get_course_contents_modid() {
1168         $this->resetAfterTest(true);
1170         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1172         // Test exclude modules.
1173         $sections = core_course_external::get_course_contents($course->id, array(
1174                                                                             array("name" => "modname", "value" => "page"),
1175                                                                             array("name" => "modid", "value" => $pagecm->instance),
1176                                                                             ));
1178         // We need to execute the return values cleaning process to simulate the web service server.
1179         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1181         $this->assertCount(4, $sections);
1182         $this->assertCount(1, $sections[0]['modules']);
1183         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
1184         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
1185     }
1187     /**
1188      * Test get course contents completion
1189      */
1190     public function test_get_course_contents_completion() {
1191         global $CFG;
1192         $this->resetAfterTest(true);
1194         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1195         availability_completion\condition::wipe_static_cache();
1197         // Test activity not completed yet.
1198         $result = core_course_external::get_course_contents($course->id, array(
1199             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1200         // We need to execute the return values cleaning process to simulate the web service server.
1201         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1203         $this->assertCount(1, $result[0]['modules']);
1204         $this->assertEquals("forum", $result[0]['modules'][0]["modname"]);
1205         $this->assertEquals(COMPLETION_TRACKING_MANUAL, $result[0]['modules'][0]["completion"]);
1206         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['state']);
1207         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['timecompleted']);
1208         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1209         $this->assertFalse($result[0]['modules'][0]["completiondata"]['valueused']);
1211         // Set activity completed.
1212         core_completion_external::update_activity_completion_status_manually($forumcm->id, true);
1214         $result = core_course_external::get_course_contents($course->id, array(
1215             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1216         // We need to execute the return values cleaning process to simulate the web service server.
1217         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1219         $this->assertEquals(COMPLETION_COMPLETE, $result[0]['modules'][0]["completiondata"]['state']);
1220         $this->assertNotEmpty($result[0]['modules'][0]["completiondata"]['timecompleted']);
1221         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1223         // Test activity with completion value that is used in an availability condition.
1224         $result = core_course_external::get_course_contents($course->id, array(
1225                 array("name" => "modname", "value" => "label"), array("name" => "modid", "value" => $labelcm->instance)));
1226         // We need to execute the return values cleaning process to simulate the web service server.
1227         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1229         $this->assertCount(1, $result[0]['modules']);
1230         $this->assertEquals("label", $result[0]['modules'][0]["modname"]);
1231         $this->assertEquals(COMPLETION_TRACKING_MANUAL, $result[0]['modules'][0]["completion"]);
1232         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['state']);
1233         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['timecompleted']);
1234         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1235         $this->assertTrue($result[0]['modules'][0]["completiondata"]['valueused']);
1237         // Disable completion.
1238         $CFG->enablecompletion = 0;
1239         $result = core_course_external::get_course_contents($course->id, array(
1240             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1241         // We need to execute the return values cleaning process to simulate the web service server.
1242         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1244         $this->assertArrayNotHasKey('completiondata', $result[0]['modules'][0]);
1245     }
1247     /**
1248      * Test mimetype is returned for resources with showtype set.
1249      */
1250     public function test_get_course_contents_including_mimetype() {
1251         $this->resetAfterTest(true);
1253         $this->setAdminUser();
1254         $course = self::getDataGenerator()->create_course();
1256         $record = new stdClass();
1257         $record->course = $course->id;
1258         $record->showtype = 1;
1259         $resource = self::getDataGenerator()->create_module('resource', $record);
1261         $result = core_course_external::get_course_contents($course->id);
1262         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1263         $this->assertCount(1, $result[0]['modules']);   // One module, first section.
1264         $customdata = unserialize(json_decode($result[0]['modules'][0]['customdata']));
1265         $this->assertEquals('text/plain', $customdata['filedetails']['mimetype']);
1266     }
1268     /**
1269      * Test contents info is returned.
1270      */
1271     public function test_get_course_contents_contentsinfo() {
1272         global $USER;
1274         $this->resetAfterTest(true);
1276         $this->setAdminUser();
1277         $course = self::getDataGenerator()->create_course();
1279         $record = new stdClass();
1280         $record->course = $course->id;
1281         // One resource with one file.
1282         $resource1 = self::getDataGenerator()->create_module('resource', $record);
1284         $timenow = time();
1285         // More type of files.
1286         $record->files = file_get_unused_draft_itemid();
1287         $usercontext = context_user::instance($USER->id);
1288         $extensions = array('txt', 'png', 'pdf');
1289         foreach ($extensions as $key => $extension) {
1290             // Add actual file there.
1291             $filerecord = array('component' => 'user', 'filearea' => 'draft',
1292                     'contextid' => $usercontext->id, 'itemid' => $record->files,
1293                     'filename' => 'resource' . $key . '.' . $extension, 'filepath' => '/');
1294             $fs = get_file_storage();
1295             $fs->create_file_from_string($filerecord, 'Test resource ' . $key . ' file');
1296         }
1298         $resource2 = self::getDataGenerator()->create_module('resource', $record);
1300         $result = core_course_external::get_course_contents($course->id);
1301         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1302         $this->assertCount(2, $result[0]['modules']);
1303         foreach ($result[0]['modules'] as $module) {
1304             if ($module['instance'] == $resource1->id) {
1305                 $this->assertEquals(1, $module['contentsinfo']['filescount']);
1306                 $this->assertGreaterThanOrEqual($timenow, $module['contentsinfo']['lastmodified']);
1307                 $this->assertEquals($module['contents'][0]['filesize'], $module['contentsinfo']['filessize']);
1308                 $this->assertEquals(array('text/plain'), $module['contentsinfo']['mimetypes']);
1309             } else {
1310                 $this->assertEquals(count($extensions), $module['contentsinfo']['filescount']);
1311                 $filessize = $module['contents'][0]['filesize'] + $module['contents'][1]['filesize'] +
1312                     $module['contents'][2]['filesize'];
1313                 $this->assertEquals($filessize, $module['contentsinfo']['filessize']);
1314                 $this->assertGreaterThanOrEqual($timenow, $module['contentsinfo']['lastmodified']);
1315                 $this->assertEquals(array('text/plain', 'image/png', 'application/pdf'), $module['contentsinfo']['mimetypes']);
1316             }
1317         }
1318     }
1320     /**
1321      * Test duplicate_course
1322      */
1323     public function test_duplicate_course() {
1324         $this->resetAfterTest(true);
1326         // Create one course with three modules.
1327         $course  = self::getDataGenerator()->create_course();
1328         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
1329         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
1330         $forumcontext = context_module::instance($forum->cmid);
1331         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
1332         $datacontext = context_module::instance($data->cmid);
1333         $datacm = get_coursemodule_from_instance('page', $data->id);
1334         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
1335         $pagecontext = context_module::instance($page->cmid);
1336         $pagecm = get_coursemodule_from_instance('page', $page->id);
1338         // Set the required capabilities by the external function.
1339         $coursecontext = context_course::instance($course->id);
1340         $categorycontext = context_coursecat::instance($course->category);
1341         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
1342         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
1343         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
1344         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
1345         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
1346         // Optional capabilities to copy user data.
1347         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
1348         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
1350         $newcourse['fullname'] = 'Course duplicate';
1351         $newcourse['shortname'] = 'courseduplicate';
1352         $newcourse['categoryid'] = $course->category;
1353         $newcourse['visible'] = true;
1354         $newcourse['options'][] = array('name' => 'users', 'value' => true);
1356         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
1357                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
1359         // We need to execute the return values cleaning process to simulate the web service server.
1360         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1362         // Check that the course has been duplicated.
1363         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1364     }
1366     /**
1367      * Test update_courses
1368      */
1369     public function test_update_courses() {
1370         global $DB, $CFG, $USER, $COURSE;
1372         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1373         // trick because we are both updating and getting (for testing) course information
1374         // in the same request and core_course_external::update_courses()
1375         // is overwriting $COURSE all over the time with OLD values, so later
1376         // use of get_course() fetches those OLD values instead of the updated ones.
1377         // See MDL-39723 for more info.
1378         $origcourse = clone($COURSE);
1380         $this->resetAfterTest(true);
1382         // Set the required capabilities by the external function.
1383         $contextid = context_system::instance()->id;
1384         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1385         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1386         $this->assignUserCapability('moodle/course:changelockedcustomfields', $contextid, $roleid);
1387         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1388         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1389         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1390         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1391         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1392         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1393         $this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
1395         // Create category and courses.
1396         $category1  = self::getDataGenerator()->create_category();
1397         $category2  = self::getDataGenerator()->create_category();
1399         $originalcourse1 = self::getDataGenerator()->create_course();
1400         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1402         $originalcourse2 = self::getDataGenerator()->create_course();
1403         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1405         // Course with custom fields.
1406         $fieldcategory = self::getDataGenerator()->create_custom_field_category(['name' => 'Other fields']);
1407         $customfield = ['shortname' => 'test', 'name' => 'Custom field', 'type' => 'text',
1408             'categoryid' => $fieldcategory->get('id'),
1409             'configdata' => ['visibility' => \core_course\customfield\course_handler::VISIBLETOALL, 'locked' => 1]];
1410         $field = self::getDataGenerator()->create_custom_field($customfield);
1412         $originalcourse3 = self::getDataGenerator()->create_course(['customfield_test' => 'Test value']);
1413         self::getDataGenerator()->enrol_user($USER->id, $originalcourse3->id, $roleid);
1415         // Course values to be updated.
1416         $course1['id'] = $originalcourse1->id;
1417         $course1['fullname'] = 'Updated test course 1';
1418         $course1['shortname'] = 'Udestedtestcourse1';
1419         $course1['categoryid'] = $category1->id;
1421         $course2['id'] = $originalcourse2->id;
1422         $course2['fullname'] = 'Updated test course 2';
1423         $course2['shortname'] = 'Updestedtestcourse2';
1424         $course2['categoryid'] = $category2->id;
1425         $course2['idnumber'] = 'Updatedidnumber2';
1426         $course2['summary'] = 'Updaated description for course 2';
1427         $course2['summaryformat'] = FORMAT_HTML;
1428         $course2['format'] = 'topics';
1429         $course2['showgrades'] = 1;
1430         $course2['newsitems'] = 3;
1431         $course2['startdate'] = 1420092000; // 01/01/2015.
1432         $course2['enddate'] = 1422669600; // 01/31/2015.
1433         $course2['maxbytes'] = 100000;
1434         $course2['showreports'] = 1;
1435         $course2['visible'] = 0;
1436         $course2['hiddensections'] = 0;
1437         $course2['groupmode'] = 0;
1438         $course2['groupmodeforce'] = 0;
1439         $course2['defaultgroupingid'] = 0;
1440         $course2['enablecompletion'] = 1;
1441         $course2['lang'] = 'en';
1442         $course2['forcetheme'] = 'bootstrapbase';
1444         $course3['id'] = $originalcourse3->id;
1445         $updatedcustomfieldvalue = ['shortname' => 'test', 'value' => 'Updated test value'];
1446         $course3['customfields'] = [$updatedcustomfieldvalue];
1447         $courses = array($course1, $course2, $course3);
1449         $updatedcoursewarnings = core_course_external::update_courses($courses);
1450         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1451                 $updatedcoursewarnings);
1452         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1454         // Check that right number of courses were created.
1455         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1457         // Check that the courses were correctly created.
1458         foreach ($courses as $course) {
1459             $courseinfo = course_get_format($course['id'])->get_course();
1460             $customfields = \core_course\customfield\course_handler::create()->export_instance_data_object($course['id']);
1461             if ($course['id'] == $course2['id']) {
1462                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1463                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1464                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1465                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1466                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1467                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1468                 $this->assertEquals($course2['format'], $courseinfo->format);
1469                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1470                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1471                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1472                 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
1473                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1474                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1475                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1476                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1477                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1478                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1479                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1480                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1482                 if (!empty($CFG->allowcoursethemes)) {
1483                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1484                 }
1486                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1487                 $this->assertEquals(['test' => null], (array)$customfields);
1488             } else if ($course['id'] == $course1['id']) {
1489                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1490                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1491                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1492                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1493                 $this->assertEquals('topics', $courseinfo->format);
1494                 $this->assertEquals(5, course_get_format($course['id'])->get_last_section_number());
1495                 $this->assertEquals(0, $courseinfo->newsitems);
1496                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1497                 $this->assertEquals(['test' => null], (array)$customfields);
1498             } else if ($course['id'] == $course3['id']) {
1499                 $this->assertEquals(['test' => $updatedcustomfieldvalue['value']], (array)$customfields);
1500             } else {
1501                 throw new moodle_exception('Unexpected shortname');
1502             }
1503         }
1505         $courses = array($course1);
1506         // Try update course without update capability.
1507         $user = self::getDataGenerator()->create_user();
1508         $this->setUser($user);
1509         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1510         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1511         $updatedcoursewarnings = core_course_external::update_courses($courses);
1512         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1513                                                                     $updatedcoursewarnings);
1514         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1516         // Try update course category without capability.
1517         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1518         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1519         $user = self::getDataGenerator()->create_user();
1520         $this->setUser($user);
1521         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1522         $course1['categoryid'] = $category2->id;
1523         $courses = array($course1);
1524         $updatedcoursewarnings = core_course_external::update_courses($courses);
1525         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1526                                                                     $updatedcoursewarnings);
1527         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1529         // Try update course fullname without capability.
1530         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1531         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1532         $user = self::getDataGenerator()->create_user();
1533         $this->setUser($user);
1534         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1535         $updatedcoursewarnings = core_course_external::update_courses($courses);
1536         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1537                                                                     $updatedcoursewarnings);
1538         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1539         $course1['fullname'] = 'Testing fullname without permission';
1540         $courses = array($course1);
1541         $updatedcoursewarnings = core_course_external::update_courses($courses);
1542         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1543                                                                     $updatedcoursewarnings);
1544         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1546         // Try update course shortname without capability.
1547         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1548         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1549         $user = self::getDataGenerator()->create_user();
1550         $this->setUser($user);
1551         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1552         $updatedcoursewarnings = core_course_external::update_courses($courses);
1553         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1554                                                                     $updatedcoursewarnings);
1555         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1556         $course1['shortname'] = 'Testing shortname without permission';
1557         $courses = array($course1);
1558         $updatedcoursewarnings = core_course_external::update_courses($courses);
1559         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1560                                                                     $updatedcoursewarnings);
1561         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1563         // Try update course idnumber without capability.
1564         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1565         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1566         $user = self::getDataGenerator()->create_user();
1567         $this->setUser($user);
1568         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1569         $updatedcoursewarnings = core_course_external::update_courses($courses);
1570         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1571                                                                     $updatedcoursewarnings);
1572         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1573         $course1['idnumber'] = 'NEWIDNUMBER';
1574         $courses = array($course1);
1575         $updatedcoursewarnings = core_course_external::update_courses($courses);
1576         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1577                                                                     $updatedcoursewarnings);
1578         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1580         // Try update course summary without capability.
1581         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1582         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1583         $user = self::getDataGenerator()->create_user();
1584         $this->setUser($user);
1585         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1586         $updatedcoursewarnings = core_course_external::update_courses($courses);
1587         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1588                                                                     $updatedcoursewarnings);
1589         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1590         $course1['summary'] = 'New summary';
1591         $courses = array($course1);
1592         $updatedcoursewarnings = core_course_external::update_courses($courses);
1593         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1594                                                                     $updatedcoursewarnings);
1595         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1597         // Try update course with invalid summary format.
1598         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1599         $user = self::getDataGenerator()->create_user();
1600         $this->setUser($user);
1601         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1602         $updatedcoursewarnings = core_course_external::update_courses($courses);
1603         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1604                                                                     $updatedcoursewarnings);
1605         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1606         $course1['summaryformat'] = 10;
1607         $courses = array($course1);
1608         $updatedcoursewarnings = core_course_external::update_courses($courses);
1609         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1610                                                                     $updatedcoursewarnings);
1611         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1613         // Try update course visibility without capability.
1614         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1615         $user = self::getDataGenerator()->create_user();
1616         $this->setUser($user);
1617         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1618         $course1['summaryformat'] = FORMAT_MOODLE;
1619         $courses = array($course1);
1620         $updatedcoursewarnings = core_course_external::update_courses($courses);
1621         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1622                                                                     $updatedcoursewarnings);
1623         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1624         $course1['visible'] = 0;
1625         $courses = array($course1);
1626         $updatedcoursewarnings = core_course_external::update_courses($courses);
1627         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1628                                                                     $updatedcoursewarnings);
1629         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1631         // Try update course custom fields without capability.
1632         $this->unassignUserCapability('moodle/course:changelockedcustomfields', $contextid, $roleid);
1633         $user = self::getDataGenerator()->create_user();
1634         $this->setUser($user);
1635         self::getDataGenerator()->enrol_user($user->id, $course3['id'], $roleid);
1637         $newupdatedcustomfieldvalue = ['shortname' => 'test', 'value' => 'New updated value'];
1638         $course3['customfields'] = [$newupdatedcustomfieldvalue];
1640         core_course_external::update_courses([$course3]);
1642         // Custom field was not updated.
1643         $customfields = \core_course\customfield\course_handler::create()->export_instance_data_object($course3['id']);
1644         $this->assertEquals(['test' => $updatedcustomfieldvalue['value']], (array)$customfields);
1645     }
1647     /**
1648      * Test delete course_module.
1649      */
1650     public function test_delete_modules() {
1651         global $DB;
1653         // Ensure we reset the data after this test.
1654         $this->resetAfterTest(true);
1656         // Create a user.
1657         $user = self::getDataGenerator()->create_user();
1659         // Set the tests to run as the user.
1660         self::setUser($user);
1662         // Create a course to add the modules.
1663         $course = self::getDataGenerator()->create_course();
1665         // Create two test modules.
1666         $record = new stdClass();
1667         $record->course = $course->id;
1668         $module1 = self::getDataGenerator()->create_module('forum', $record);
1669         $module2 = self::getDataGenerator()->create_module('assign', $record);
1671         // Check the forum was correctly created.
1672         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1674         // Check the assignment was correctly created.
1675         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1677         // Check data exists in the course modules table.
1678         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1679                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1681         // Enrol the user in the course.
1682         $enrol = enrol_get_plugin('manual');
1683         $enrolinstances = enrol_get_instances($course->id, true);
1684         foreach ($enrolinstances as $courseenrolinstance) {
1685             if ($courseenrolinstance->enrol == "manual") {
1686                 $instance = $courseenrolinstance;
1687                 break;
1688             }
1689         }
1690         $enrol->enrol_user($instance, $user->id);
1692         // Assign capabilities to delete module 1.
1693         $modcontext = context_module::instance($module1->cmid);
1694         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1696         // Assign capabilities to delete module 2.
1697         $modcontext = context_module::instance($module2->cmid);
1698         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1699         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1701         // Deleting these module instances.
1702         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1704         // Check the forum was deleted.
1705         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1707         // Check the assignment was deleted.
1708         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1710         // Check we retrieve no data in the course modules table.
1711         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1712                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1714         // Call with non-existent course module id and ensure exception thrown.
1715         try {
1716             core_course_external::delete_modules(array('1337'));
1717             $this->fail('Exception expected due to missing course module.');
1718         } catch (dml_missing_record_exception $e) {
1719             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1720         }
1722         // Create two modules.
1723         $module1 = self::getDataGenerator()->create_module('forum', $record);
1724         $module2 = self::getDataGenerator()->create_module('assign', $record);
1726         // Since these modules were recreated the user will not have capabilities
1727         // to delete them, ensure exception is thrown if they try.
1728         try {
1729             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1730             $this->fail('Exception expected due to missing capability.');
1731         } catch (moodle_exception $e) {
1732             $this->assertEquals('nopermissions', $e->errorcode);
1733         }
1735         // Unenrol user from the course.
1736         $enrol->unenrol_user($instance, $user->id);
1738         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1739         try {
1740             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1741             $this->fail('Exception expected due to being unenrolled from the course.');
1742         } catch (moodle_exception $e) {
1743             $this->assertEquals('requireloginerror', $e->errorcode);
1744         }
1745     }
1747     /**
1748      * Test import_course into an empty course
1749      */
1750     public function test_import_course_empty() {
1751         global $USER;
1753         $this->resetAfterTest(true);
1755         $course1  = self::getDataGenerator()->create_course();
1756         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1757         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1759         $course2  = self::getDataGenerator()->create_course();
1761         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1762         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1764         // Verify the state of the courses before we do the import.
1765         $this->assertCount(2, $course1cms);
1766         $this->assertEmpty($course2cms);
1768         // Setup the user to run the operation (ugly hack because validate_context() will
1769         // fail as the email is not set by $this->setAdminUser()).
1770         $this->setAdminUser();
1771         $USER->email = 'emailtopass@example.com';
1773         // Import from course1 to course2.
1774         core_course_external::import_course($course1->id, $course2->id, 0);
1776         // Verify that now we have two modules in both courses.
1777         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1778         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1779         $this->assertCount(2, $course1cms);
1780         $this->assertCount(2, $course2cms);
1782         // Verify that the names transfered across correctly.
1783         foreach ($course2cms as $cm) {
1784             if ($cm->modname === 'page') {
1785                 $this->assertEquals($cm->name, $page->name);
1786             } else if ($cm->modname === 'forum') {
1787                 $this->assertEquals($cm->name, $forum->name);
1788             } else {
1789                 $this->fail('Unknown CM found.');
1790             }
1791         }
1792     }
1794     /**
1795      * Test import_course into an filled course
1796      */
1797     public function test_import_course_filled() {
1798         global $USER;
1800         $this->resetAfterTest(true);
1802         // Add forum and page to course1.
1803         $course1  = self::getDataGenerator()->create_course();
1804         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1805         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1807         // Add quiz to course 2.
1808         $course2  = self::getDataGenerator()->create_course();
1809         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1811         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1812         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1814         // Verify the state of the courses before we do the import.
1815         $this->assertCount(2, $course1cms);
1816         $this->assertCount(1, $course2cms);
1818         // Setup the user to run the operation (ugly hack because validate_context() will
1819         // fail as the email is not set by $this->setAdminUser()).
1820         $this->setAdminUser();
1821         $USER->email = 'emailtopass@example.com';
1823         // Import from course1 to course2 without deleting content.
1824         core_course_external::import_course($course1->id, $course2->id, 0);
1826         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1828         // Verify that now we have three modules in course2.
1829         $this->assertCount(3, $course2cms);
1831         // Verify that the names transfered across correctly.
1832         foreach ($course2cms as $cm) {
1833             if ($cm->modname === 'page') {
1834                 $this->assertEquals($cm->name, $page->name);
1835             } else if ($cm->modname === 'forum') {
1836                 $this->assertEquals($cm->name, $forum->name);
1837             } else if ($cm->modname === 'quiz') {
1838                 $this->assertEquals($cm->name, $quiz->name);
1839             } else {
1840                 $this->fail('Unknown CM found.');
1841             }
1842         }
1843     }
1845     /**
1846      * Test import_course with only blocks set to backup
1847      */
1848     public function test_import_course_blocksonly() {
1849         global $USER, $DB;
1851         $this->resetAfterTest(true);
1853         // Add forum and page to course1.
1854         $course1  = self::getDataGenerator()->create_course();
1855         $course1ctx = context_course::instance($course1->id);
1856         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1857         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1859         $course2  = self::getDataGenerator()->create_course();
1860         $course2ctx = context_course::instance($course2->id);
1861         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1862         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1864         // Setup the user to run the operation (ugly hack because validate_context() will
1865         // fail as the email is not set by $this->setAdminUser()).
1866         $this->setAdminUser();
1867         $USER->email = 'emailtopass@example.com';
1869         // Import from course1 to course2 without deleting content, but excluding
1870         // activities.
1871         $options = array(
1872             array('name' => 'activities', 'value' => 0),
1873             array('name' => 'blocks', 'value' => 1),
1874             array('name' => 'filters', 'value' => 0),
1875         );
1877         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1879         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1880         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1881         // Check that course modules haven't changed, but that blocks have.
1882         $this->assertEquals($initialcmcount, $newcmcount);
1883         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1884     }
1886     /**
1887      * Test import_course into an filled course, deleting content.
1888      */
1889     public function test_import_course_deletecontent() {
1890         global $USER;
1891         $this->resetAfterTest(true);
1893         // Add forum and page to course1.
1894         $course1  = self::getDataGenerator()->create_course();
1895         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1896         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1898         // Add quiz to course 2.
1899         $course2  = self::getDataGenerator()->create_course();
1900         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1902         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1903         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1905         // Verify the state of the courses before we do the import.
1906         $this->assertCount(2, $course1cms);
1907         $this->assertCount(1, $course2cms);
1909         // Setup the user to run the operation (ugly hack because validate_context() will
1910         // fail as the email is not set by $this->setAdminUser()).
1911         $this->setAdminUser();
1912         $USER->email = 'emailtopass@example.com';
1914         // Import from course1 to course2,  deleting content.
1915         core_course_external::import_course($course1->id, $course2->id, 1);
1917         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1919         // Verify that now we have two modules in course2.
1920         $this->assertCount(2, $course2cms);
1922         // Verify that the course only contains the imported modules.
1923         foreach ($course2cms as $cm) {
1924             if ($cm->modname === 'page') {
1925                 $this->assertEquals($cm->name, $page->name);
1926             } else if ($cm->modname === 'forum') {
1927                 $this->assertEquals($cm->name, $forum->name);
1928             } else {
1929                 $this->fail('Unknown CM found: '.$cm->name);
1930             }
1931         }
1932     }
1934     /**
1935      * Ensure import_course handles incorrect deletecontent option correctly.
1936      */
1937     public function test_import_course_invalid_deletecontent_option() {
1938         $this->resetAfterTest(true);
1940         $course1  = self::getDataGenerator()->create_course();
1941         $course2  = self::getDataGenerator()->create_course();
1943         $this->expectException('moodle_exception');
1944         $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
1945         // Import from course1 to course2, with invalid option
1946         core_course_external::import_course($course1->id, $course2->id, -1);;
1947     }
1949     /**
1950      * Test view_course function
1951      */
1952     public function test_view_course() {
1954         $this->resetAfterTest();
1956         // Course without sections.
1957         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1958         $this->setAdminUser();
1960         // Redirect events to the sink, so we can recover them later.
1961         $sink = $this->redirectEvents();
1963         $result = core_course_external::view_course($course->id, 1);
1964         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1965         $events = $sink->get_events();
1966         $event = reset($events);
1968         // Check the event details are correct.
1969         $this->assertInstanceOf('\core\event\course_viewed', $event);
1970         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1971         $this->assertEquals(1, $event->other['coursesectionnumber']);
1973         $result = core_course_external::view_course($course->id);
1974         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1975         $events = $sink->get_events();
1976         $event = array_pop($events);
1977         $sink->close();
1979         // Check the event details are correct.
1980         $this->assertInstanceOf('\core\event\course_viewed', $event);
1981         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1982         $this->assertEmpty($event->other);
1984     }
1986     /**
1987      * Test get_course_module
1988      */
1989     public function test_get_course_module() {
1990         global $DB;
1992         $this->resetAfterTest(true);
1994         $this->setAdminUser();
1995         $course = self::getDataGenerator()->create_course();
1996         $record = array(
1997             'course' => $course->id,
1998             'name' => 'First Assignment'
1999         );
2000         $options = array(
2001             'idnumber' => 'ABC',
2002             'visible' => 0
2003         );
2004         // Hidden activity.
2005         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
2007         $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
2009         // Insert a custom grade scale to be used by an outcome.
2010         $gradescale = new grade_scale();
2011         $gradescale->name        = 'gettcoursemodulescale';
2012         $gradescale->courseid    = $course->id;
2013         $gradescale->userid      = 0;
2014         $gradescale->scale       = $outcomescale;
2015         $gradescale->description = 'This scale is used to mark standard assignments.';
2016         $gradescale->insert();
2018         // Insert an outcome.
2019         $data = new stdClass();
2020         $data->courseid = $course->id;
2021         $data->fullname = 'Team work';
2022         $data->shortname = 'Team work';
2023         $data->scaleid = $gradescale->id;
2024         $outcome = new grade_outcome($data, false);
2025         $outcome->insert();
2027         $outcomegradeitem = new grade_item();
2028         $outcomegradeitem->itemname = $outcome->shortname;
2029         $outcomegradeitem->itemtype = 'mod';
2030         $outcomegradeitem->itemmodule = 'assign';
2031         $outcomegradeitem->iteminstance = $assign->id;
2032         $outcomegradeitem->outcomeid = $outcome->id;
2033         $outcomegradeitem->cmid = 0;
2034         $outcomegradeitem->courseid = $course->id;
2035         $outcomegradeitem->aggregationcoef = 0;
2036         $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
2037         $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
2038         $outcomegradeitem->scaleid = $outcome->scaleid;
2039         $outcomegradeitem->insert();
2041         $assignmentgradeitem = grade_item::fetch(
2042             array(
2043                 'itemtype' => 'mod',
2044                 'itemmodule' => 'assign',
2045                 'iteminstance' => $assign->id,
2046                 'itemnumber' => 0,
2047                 'courseid' => $course->id
2048             )
2049         );
2050         $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
2051         $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
2053         // Test admin user can see the complete hidden activity.
2054         $result = core_course_external::get_course_module($assign->cmid);
2055         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
2057         $this->assertCount(0, $result['warnings']);
2058         // Test we retrieve all the fields.
2059         $this->assertCount(28, $result['cm']);
2060         $this->assertEquals($record['name'], $result['cm']['name']);
2061         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
2062         $this->assertEquals(100, $result['cm']['grade']);
2063         $this->assertEquals(0.0, $result['cm']['gradepass']);
2064         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
2065         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
2066         $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
2068         $student = $this->getDataGenerator()->create_user();
2069         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2071         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
2072         $this->setUser($student);
2074         // The user shouldn't be able to see the activity.
2075         try {
2076             core_course_external::get_course_module($assign->cmid);
2077             $this->fail('Exception expected due to invalid permissions.');
2078         } catch (moodle_exception $e) {
2079             $this->assertEquals('requireloginerror', $e->errorcode);
2080         }
2082         // Make module visible.
2083         set_coursemodule_visible($assign->cmid, 1);
2085         // Test student user.
2086         $result = core_course_external::get_course_module($assign->cmid);
2087         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
2089         $this->assertCount(0, $result['warnings']);
2090         // Test we retrieve only the few files we can see.
2091         $this->assertCount(11, $result['cm']);
2092         $this->assertEquals($assign->cmid, $result['cm']['id']);
2093         $this->assertEquals($course->id, $result['cm']['course']);
2094         $this->assertEquals('assign', $result['cm']['modname']);
2095         $this->assertEquals($assign->id, $result['cm']['instance']);
2097     }
2099     /**
2100      * Test get_course_module_by_instance
2101      */
2102     public function test_get_course_module_by_instance() {
2103         global $DB;
2105         $this->resetAfterTest(true);
2107         $this->setAdminUser();
2108         $course = self::getDataGenerator()->create_course();
2109         $record = array(
2110             'course' => $course->id,
2111             'name' => 'First quiz',
2112             'grade' => 90.00
2113         );
2114         $options = array(
2115             'idnumber' => 'ABC',
2116             'visible' => 0
2117         );
2118         // Hidden activity.
2119         $quiz = self::getDataGenerator()->create_module('quiz', $record, $options);
2121         // Test admin user can see the complete hidden activity.
2122         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2123         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
2125         $this->assertCount(0, $result['warnings']);
2126         // Test we retrieve all the fields.
2127         $this->assertCount(26, $result['cm']);
2128         $this->assertEquals($record['name'], $result['cm']['name']);
2129         $this->assertEquals($record['grade'], $result['cm']['grade']);
2130         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
2132         $student = $this->getDataGenerator()->create_user();
2133         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2135         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
2136         $this->setUser($student);
2138         // The user shouldn't be able to see the activity.
2139         try {
2140             core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2141             $this->fail('Exception expected due to invalid permissions.');
2142         } catch (moodle_exception $e) {
2143             $this->assertEquals('requireloginerror', $e->errorcode);
2144         }
2146         // Make module visible.
2147         set_coursemodule_visible($quiz->cmid, 1);
2149         // Test student user.
2150         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2151         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
2153         $this->assertCount(0, $result['warnings']);
2154         // Test we retrieve only the few files we can see.
2155         $this->assertCount(11, $result['cm']);
2156         $this->assertEquals($quiz->cmid, $result['cm']['id']);
2157         $this->assertEquals($course->id, $result['cm']['course']);
2158         $this->assertEquals('quiz', $result['cm']['modname']);
2159         $this->assertEquals($quiz->id, $result['cm']['instance']);
2161         // Try with an invalid module name.
2162         try {
2163             core_course_external::get_course_module_by_instance('abc', $quiz->id);
2164             $this->fail('Exception expected due to invalid module name.');
2165         } catch (dml_read_exception $e) {
2166             $this->assertEquals('dmlreadexception', $e->errorcode);
2167         }
2169     }
2171     /**
2172      * Test get_activities_overview
2173      */
2174     public function test_get_activities_overview() {
2175         global $USER;
2177         $this->resetAfterTest();
2178         $course1 = self::getDataGenerator()->create_course();
2179         $course2 = self::getDataGenerator()->create_course();
2181         // Create a viewer user.
2182         $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
2183         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2184         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2186         // Create two forums - one in each course.
2187         $record = new stdClass();
2188         $record->course = $course1->id;
2189         $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
2190         $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
2192         $this->setAdminUser();
2193         // A standard post in the forum.
2194         $record = new stdClass();
2195         $record->course = $course1->id;
2196         $record->userid = $USER->id;
2197         $record->forum = $forum1->id;
2198         $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
2200         $this->setUser($viewer->id);
2201         $courses = array($course1->id , $course2->id);
2203         $result = core_course_external::get_activities_overview($courses);
2204         $this->assertDebuggingCalledCount(8);
2205         $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
2207         // There should be one entry for course1, and no others.
2208         $this->assertCount(1, $result['courses']);
2209         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2210         // Check expected overview data for the module.
2211         $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
2212         $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
2213     }
2215     /**
2216      * Test get_user_navigation_options
2217      */
2218     public function test_get_user_navigation_options() {
2219         global $USER;
2221         $this->resetAfterTest();
2222         $course1 = self::getDataGenerator()->create_course();
2223         $course2 = self::getDataGenerator()->create_course();
2225         // Create a viewer user.
2226         $viewer = self::getDataGenerator()->create_user();
2227         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2228         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2230         $this->setUser($viewer->id);
2231         $courses = array($course1->id , $course2->id, SITEID);
2233         $result = core_course_external::get_user_navigation_options($courses);
2234         $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
2236         $this->assertCount(0, $result['warnings']);
2237         $this->assertCount(3, $result['courses']);
2239         foreach ($result['courses'] as $course) {
2240             $navoptions = new stdClass;
2241             foreach ($course['options'] as $option) {
2242                 $navoptions->{$option['name']} = $option['available'];
2243             }
2244             $this->assertCount(9, $course['options']);
2245             if ($course['id'] == SITEID) {
2246                 $this->assertTrue($navoptions->blogs);
2247                 $this->assertFalse($navoptions->notes);
2248                 $this->assertFalse($navoptions->participants);
2249                 $this->assertTrue($navoptions->badges);
2250                 $this->assertTrue($navoptions->tags);
2251                 $this->assertFalse($navoptions->grades);
2252                 $this->assertFalse($navoptions->search);
2253                 $this->assertTrue($navoptions->calendar);
2254                 $this->assertTrue($navoptions->competencies);
2255             } else {
2256                 $this->assertTrue($navoptions->blogs);
2257                 $this->assertFalse($navoptions->notes);
2258                 $this->assertTrue($navoptions->participants);
2259                 $this->assertTrue($navoptions->badges);
2260                 $this->assertFalse($navoptions->tags);
2261                 $this->assertTrue($navoptions->grades);
2262                 $this->assertFalse($navoptions->search);
2263                 $this->assertFalse($navoptions->calendar);
2264                 $this->assertTrue($navoptions->competencies);
2265             }
2266         }
2267     }
2269     /**
2270      * Test get_user_administration_options
2271      */
2272     public function test_get_user_administration_options() {
2273         global $USER;
2275         $this->resetAfterTest();
2276         $course1 = self::getDataGenerator()->create_course();
2277         $course2 = self::getDataGenerator()->create_course();
2279         // Create a viewer user.
2280         $viewer = self::getDataGenerator()->create_user();
2281         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2282         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2284         $this->setUser($viewer->id);
2285         $courses = array($course1->id , $course2->id, SITEID);
2287         $result = core_course_external::get_user_administration_options($courses);
2288         $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
2290         $this->assertCount(0, $result['warnings']);
2291         $this->assertCount(3, $result['courses']);
2293         foreach ($result['courses'] as $course) {
2294             $adminoptions = new stdClass;
2295             foreach ($course['options'] as $option) {
2296                 $adminoptions->{$option['name']} = $option['available'];
2297             }
2298             if ($course['id'] == SITEID) {
2299                 $this->assertCount(16, $course['options']);
2300                 $this->assertFalse($adminoptions->update);
2301                 $this->assertFalse($adminoptions->filters);
2302                 $this->assertFalse($adminoptions->reports);
2303                 $this->assertFalse($adminoptions->backup);
2304                 $this->assertFalse($adminoptions->restore);
2305                 $this->assertFalse($adminoptions->files);
2306                 $this->assertFalse(!isset($adminoptions->tags));
2307                 $this->assertFalse($adminoptions->gradebook);
2308                 $this->assertFalse($adminoptions->outcomes);
2309                 $this->assertFalse($adminoptions->badges);
2310                 $this->assertFalse($adminoptions->import);
2311                 $this->assertFalse($adminoptions->publish);
2312                 $this->assertFalse($adminoptions->reset);
2313                 $this->assertFalse($adminoptions->roles);
2314                 $this->assertFalse($adminoptions->editcompletion);
2315             } else {
2316                 $this->assertCount(15, $course['options']);
2317                 $this->assertFalse($adminoptions->update);
2318                 $this->assertFalse($adminoptions->filters);
2319                 $this->assertFalse($adminoptions->reports);
2320                 $this->assertFalse($adminoptions->backup);
2321                 $this->assertFalse($adminoptions->restore);
2322                 $this->assertFalse($adminoptions->files);
2323                 $this->assertFalse($adminoptions->tags);
2324                 $this->assertFalse($adminoptions->gradebook);
2325                 $this->assertFalse($adminoptions->outcomes);
2326                 $this->assertTrue($adminoptions->badges);
2327                 $this->assertFalse($adminoptions->import);
2328                 $this->assertFalse($adminoptions->publish);
2329                 $this->assertFalse($adminoptions->reset);
2330                 $this->assertFalse($adminoptions->roles);
2331                 $this->assertFalse($adminoptions->editcompletion);
2332             }
2333         }
2334     }
2336     /**
2337      * Test get_courses_by_fields
2338      */
2339     public function test_get_courses_by_field() {
2340         global $DB;
2341         $this->resetAfterTest(true);
2343         $category1 = self::getDataGenerator()->create_category(array('name' => 'Cat 1'));
2344         $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
2345         $course1 = self::getDataGenerator()->create_course(
2346             array('category' => $category1->id, 'shortname' => 'c1', 'format' => 'topics'));
2347         $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
2349         $student1 = self::getDataGenerator()->create_user();
2350         $user1 = self::getDataGenerator()->create_user();
2351         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2352         self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
2353         self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
2355         self::setAdminUser();
2356         // As admins, we should be able to retrieve everything.
2357         $result = core_course_external::get_courses_by_field();
2358         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2359         $this->assertCount(3, $result['courses']);
2360         // Expect to receive all the fields.
2361         $this->assertCount(37, $result['courses'][0]);
2362         $this->assertCount(38, $result['courses'][1]);  // One more field because is not the site course.
2363         $this->assertCount(38, $result['courses'][2]);  // One more field because is not the site course.
2365         $result = core_course_external::get_courses_by_field('id', $course1->id);
2366         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2367         $this->assertCount(1, $result['courses']);
2368         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2369         // Expect to receive all the fields.
2370         $this->assertCount(38, $result['courses'][0]);
2371         // Check default values for course format topics.
2372         $this->assertCount(2, $result['courses'][0]['courseformatoptions']);
2373         foreach ($result['courses'][0]['courseformatoptions'] as $option) {
2374             if ($option['name'] == 'hiddensections') {
2375                 $this->assertEquals(0, $option['value']);
2376             } else {
2377                 $this->assertEquals('coursedisplay', $option['name']);
2378                 $this->assertEquals(0, $option['value']);
2379             }
2380         }
2382         $result = core_course_external::get_courses_by_field('id', $course2->id);
2383         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2384         $this->assertCount(1, $result['courses']);
2385         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2387         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2388         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2389         $this->assertCount(2, $result['courses']);
2391         // Check default filters.
2392         $this->assertCount(3, $result['courses'][0]['filters']);
2393         $this->assertCount(3, $result['courses'][1]['filters']);
2395         $result = core_course_external::get_courses_by_field('category', $category1->id);
2396         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2397         $this->assertCount(1, $result['courses']);
2398         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2399         $this->assertEquals('Cat 1', $result['courses'][0]['categoryname']);
2401         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2402         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2403         $this->assertCount(1, $result['courses']);
2404         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2406         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2407         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2408         $this->assertCount(1, $result['courses']);
2409         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2411         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2412         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2413         $this->assertCount(0, $result['courses']);
2415         // Change filter value.
2416         filter_set_local_state('mediaplugin', context_course::instance($course1->id)->id, TEXTFILTER_OFF);
2418         self::setUser($student1);
2419         // All visible courses  (including front page) for normal student.
2420         $result = core_course_external::get_courses_by_field();
2421         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2422         $this->assertCount(2, $result['courses']);
2423         $this->assertCount(30, $result['courses'][0]);
2424         $this->assertCount(31, $result['courses'][1]);  // One field more (course format options), not present in site course.
2426         $result = core_course_external::get_courses_by_field('id', $course1->id);
2427         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2428         $this->assertCount(1, $result['courses']);
2429         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2430         // Expect to receive all the files that a student can see.
2431         $this->assertCount(31, $result['courses'][0]);
2433         // Check default filters.
2434         $filters = $result['courses'][0]['filters'];
2435         $this->assertCount(3, $filters);
2436         $found = false;
2437         foreach ($filters as $filter) {
2438             if ($filter['filter'] == 'mediaplugin' and $filter['localstate'] == TEXTFILTER_OFF) {
2439                 $found = true;
2440             }
2441         }
2442         $this->assertTrue($found);
2444         // Course 2 is not visible.
2445         $result = core_course_external::get_courses_by_field('id', $course2->id);
2446         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2447         $this->assertCount(0, $result['courses']);
2449         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2450         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2451         $this->assertCount(1, $result['courses']);
2453         $result = core_course_external::get_courses_by_field('category', $category1->id);
2454         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2455         $this->assertCount(1, $result['courses']);
2456         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2458         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2459         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2460         $this->assertCount(1, $result['courses']);
2461         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2463         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2464         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2465         $this->assertCount(0, $result['courses']);
2467         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2468         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2469         $this->assertCount(0, $result['courses']);
2471         self::setUser($user1);
2472         // All visible courses (including front page) for authenticated user.
2473         $result = core_course_external::get_courses_by_field();
2474         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2475         $this->assertCount(2, $result['courses']);
2476         $this->assertCount(30, $result['courses'][0]);  // Site course.
2477         $this->assertCount(13, $result['courses'][1]);  // Only public information, not enrolled.
2479         $result = core_course_external::get_courses_by_field('id', $course1->id);
2480         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2481         $this->assertCount(1, $result['courses']);
2482         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2483         // Expect to receive all the files that a authenticated can see.
2484         $this->assertCount(13, $result['courses'][0]);
2486         // Course 2 is not visible.
2487         $result = core_course_external::get_courses_by_field('id', $course2->id);
2488         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2489         $this->assertCount(0, $result['courses']);
2491         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2492         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2493         $this->assertCount(1, $result['courses']);
2495         $result = core_course_external::get_courses_by_field('category', $category1->id);
2496         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2497         $this->assertCount(1, $result['courses']);
2498         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2500         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2501         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2502         $this->assertCount(1, $result['courses']);
2503         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2505         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2506         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2507         $this->assertCount(0, $result['courses']);
2509         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2510         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2511         $this->assertCount(0, $result['courses']);
2512     }
2514     public function test_get_courses_by_field_invalid_field() {
2515         $this->expectException('invalid_parameter_exception');
2516         $result = core_course_external::get_courses_by_field('zyx', 'x');
2517     }
2519     public function test_get_courses_by_field_invalid_courses() {
2520         $result = core_course_external::get_courses_by_field('id', '-1');
2521         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2522         $this->assertCount(0, $result['courses']);
2523     }
2525     /**
2526      * Test get_courses_by_field_invalid_theme_and_lang
2527      */
2528     public function test_get_courses_by_field_invalid_theme_and_lang() {
2529         $this->resetAfterTest(true);
2530         $this->setAdminUser();
2532         $course = self::getDataGenerator()->create_course(array('theme' => 'kkt', 'lang' => 'kkl'));
2533         $result = core_course_external::get_courses_by_field('id', $course->id);
2534         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2535         $this->assertEmpty($result['courses']['0']['theme']);
2536         $this->assertEmpty($result['courses']['0']['lang']);
2537     }
2540     public function test_check_updates() {
2541         global $DB;
2542         $this->resetAfterTest(true);
2543         $this->setAdminUser();
2545         // Create different types of activities.
2546         $course  = self::getDataGenerator()->create_course();
2547         $tocreate = array('assign', 'book', 'choice', 'folder', 'forum', 'glossary', 'imscp', 'label', 'lti', 'page', 'quiz',
2548                             'resource', 'scorm', 'survey', 'url', 'wiki');
2550         $modules = array();
2551         foreach ($tocreate as $modname) {
2552             $modules[$modname]['instance'] = $this->getDataGenerator()->create_module($modname, array('course' => $course->id));
2553             $modules[$modname]['cm'] = get_coursemodule_from_id(false, $modules[$modname]['instance']->cmid);
2554             $modules[$modname]['context'] = context_module::instance($modules[$modname]['instance']->cmid);
2555         }
2557         $student = self::getDataGenerator()->create_user();
2558         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2559         self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
2560         $this->setUser($student);
2562         $since = time();
2563         $this->waitForSecond();
2564         $params = array();
2565         foreach ($modules as $modname => $data) {
2566             $params[$data['cm']->id] = array(
2567                 'contextlevel' => 'module',
2568                 'id' => $data['cm']->id,
2569                 'since' => $since
2570             );
2571         }
2573         // Check there is nothing updated because modules are fresh new.
2574         $result = core_course_external::check_updates($course->id, $params);
2575         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2576         $this->assertCount(0, $result['instances']);
2577         $this->assertCount(0, $result['warnings']);
2579         // Test with get_updates_since the same data.
2580         $result = core_course_external::get_updates_since($course->id, $since);
2581         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2582         $this->assertCount(0, $result['instances']);
2583         $this->assertCount(0, $result['warnings']);
2585         // Update a module after a second.
2586         $this->waitForSecond();
2587         set_coursemodule_name($modules['forum']['cm']->id, 'New forum name');
2589         $found = false;
2590         $result = core_course_external::check_updates($course->id, $params);
2591         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2592         $this->assertCount(1, $result['instances']);
2593         $this->assertCount(0, $result['warnings']);
2594         foreach ($result['instances'] as $module) {
2595             foreach ($module['updates'] as $update) {
2596                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2597                     $found = true;
2598                 }
2599             }
2600         }
2601         $this->assertTrue($found);
2603         // Test with get_updates_since the same data.
2604         $result = core_course_external::get_updates_since($course->id, $since);
2605         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2606         $this->assertCount(1, $result['instances']);
2607         $this->assertCount(0, $result['warnings']);
2608         $found = false;
2609         $this->assertCount(1, $result['instances']);
2610         $this->assertCount(0, $result['warnings']);
2611         foreach ($result['instances'] as $module) {
2612             foreach ($module['updates'] as $update) {
2613                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2614                     $found = true;
2615                 }
2616             }
2617         }
2618         $this->assertTrue($found);
2620         // Do not retrieve the configuration field.
2621         $filter = array('files');
2622         $found = false;
2623         $result = core_course_external::check_updates($course->id, $params, $filter);
2624         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2625         $this->assertCount(0, $result['instances']);
2626         $this->assertCount(0, $result['warnings']);
2627         $this->assertFalse($found);
2629         // Add invalid cmid.
2630         $params[] = array(
2631             'contextlevel' => 'module',
2632             'id' => -2,
2633             'since' => $since
2634         );
2635         $result = core_course_external::check_updates($course->id, $params);
2636         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2637         $this->assertCount(1, $result['warnings']);
2638         $this->assertEquals(-2, $result['warnings'][0]['itemid']);
2639     }
2641     /**
2642      * Test cases for the get_enrolled_courses_by_timeline_classification test.
2643      */
2644     public function get_get_enrolled_courses_by_timeline_classification_test_cases() {
2645         $now = time();
2646         $day = 86400;
2648         $coursedata = [
2649             [
2650                 'shortname' => 'apast',
2651                 'startdate' => $now - ($day * 2),
2652                 'enddate' => $now - $day
2653             ],
2654             [
2655                 'shortname' => 'bpast',
2656                 'startdate' => $now - ($day * 2),
2657                 'enddate' => $now - $day
2658             ],
2659             [
2660                 'shortname' => 'cpast',
2661                 'startdate' => $now - ($day * 2),
2662                 'enddate' => $now - $day
2663             ],
2664             [
2665                 'shortname' => 'dpast',
2666                 'startdate' => $now - ($day * 2),
2667                 'enddate' => $now - $day
2668             ],
2669             [
2670                 'shortname' => 'epast',
2671                 'startdate' => $now - ($day * 2),
2672                 'enddate' => $now - $day
2673             ],
2674             [
2675                 'shortname' => 'ainprogress',
2676                 'startdate' => $now - $day,
2677                 'enddate' => $now + $day
2678             ],
2679             [
2680                 'shortname' => 'binprogress',
2681                 'startdate' => $now - $day,
2682                 'enddate' => $now + $day
2683             ],
2684             [
2685                 'shortname' => 'cinprogress',
2686                 'startdate' => $now - $day,
2687                 'enddate' => $now + $day
2688             ],
2689             [
2690                 'shortname' => 'dinprogress',
2691                 'startdate' => $now - $day,
2692                 'enddate' => $now + $day
2693             ],
2694             [
2695                 'shortname' => 'einprogress',
2696                 'startdate' => $now - $day,
2697                 'enddate' => $now + $day
2698             ],
2699             [
2700                 'shortname' => 'afuture',
2701                 'startdate' => $now + $day
2702             ],
2703             [
2704                 'shortname' => 'bfuture',
2705                 'startdate' => $now + $day
2706             ],
2707             [
2708                 'shortname' => 'cfuture',
2709                 'startdate' => $now + $day
2710             ],
2711             [
2712                 'shortname' => 'dfuture',
2713                 'startdate' => $now + $day
2714             ],
2715             [
2716                 'shortname' => 'efuture',
2717                 'startdate' => $now + $day
2718             ]
2719         ];
2721         // Raw enrolled courses result set should be returned in this order:
2722         // afuture, ainprogress, apast, bfuture, binprogress, bpast, cfuture, cinprogress, cpast,
2723         // dfuture, dinprogress, dpast, efuture, einprogress, epast
2724         //
2725         // By classification the offset values for each record should be:
2726         // COURSE_TIMELINE_FUTURE
2727         // 0 (afuture), 3 (bfuture), 6 (cfuture), 9 (dfuture), 12 (efuture)
2728         // COURSE_TIMELINE_INPROGRESS
2729         // 1 (ainprogress), 4 (binprogress), 7 (cinprogress), 10 (dinprogress), 13 (einprogress)
2730         // COURSE_TIMELINE_PAST
2731         // 2 (apast), 5 (bpast), 8 (cpast), 11 (dpast), 14 (epast).
2732         //
2733         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2734         // filtering is done.
2735         // E.g. In our example if an offset of 2 is given then it would mean the first
2736         // two courses (afuture, ainprogress) are ignored.
2737         return [
2738             'empty set' => [
2739                 'coursedata' => [],
2740                 'classification' => 'future',
2741                 'limit' => 2,
2742                 'offset' => 0,
2743                 'expectedcourses' => [],
2744                 'expectednextoffset' => 0
2745             ],
2746             // COURSE_TIMELINE_FUTURE.
2747             'future not limit no offset' => [
2748                 'coursedata' => $coursedata,
2749                 'classification' => 'future',
2750                 'limit' => 0,
2751                 'offset' => 0,
2752                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2753                 'expectednextoffset' => 15
2754             ],
2755             'future no offset' => [
2756                 'coursedata' => $coursedata,
2757                 'classification' => 'future',
2758                 'limit' => 2,
2759                 'offset' => 0,
2760                 'expectedcourses' => ['afuture', 'bfuture'],
2761                 'expectednextoffset' => 4
2762             ],
2763             'future offset' => [
2764                 'coursedata' => $coursedata,
2765                 'classification' => 'future',
2766                 'limit' => 2,
2767                 'offset' => 2,
2768                 'expectedcourses' => ['bfuture', 'cfuture'],
2769                 'expectednextoffset' => 7
2770             ],
2771             'future exact limit' => [
2772                 'coursedata' => $coursedata,
2773                 'classification' => 'future',
2774                 'limit' => 5,
2775                 'offset' => 0,
2776                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2777                 'expectednextoffset' => 13
2778             ],
2779             'future limit less results' => [
2780                 'coursedata' => $coursedata,
2781                 'classification' => 'future',
2782                 'limit' => 10,
2783                 'offset' => 0,
2784                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2785                 'expectednextoffset' => 15
2786             ],
2787             'future limit less results with offset' => [
2788                 'coursedata' => $coursedata,
2789                 'classification' => 'future',
2790                 'limit' => 10,
2791                 'offset' => 5,
2792                 'expectedcourses' => ['cfuture', 'dfuture', 'efuture'],
2793                 'expectednextoffset' => 15
2794             ],
2795             'all no limit or offset' => [
2796                 'coursedata' => $coursedata,
2797                 'classification' => 'all',
2798                 'limit' => 0,
2799                 'offset' => 0,
2800                 'expectedcourses' => [
2801                     'afuture',
2802                     'ainprogress',
2803                     'apast',
2804                     'bfuture',
2805                     'binprogress',
2806                     'bpast',
2807                     'cfuture',
2808                     'cinprogress',
2809                     'cpast',
2810                     'dfuture',
2811                     'dinprogress',
2812                     'dpast',
2813                     'efuture',
2814                     'einprogress',
2815                     'epast'
2816                 ],
2817                 'expectednextoffset' => 15
2818             ],
2819             'all limit no offset' => [
2820                 'coursedata' => $coursedata,
2821                 'classification' => 'all',
2822                 'limit' => 5,
2823                 'offset' => 0,
2824                 'expectedcourses' => [
2825                     'afuture',
2826                     'ainprogress',
2827                     'apast',
2828                     'bfuture',
2829                     'binprogress'
2830                 ],
2831                 'expectednextoffset' => 5
2832             ],
2833             'all limit and offset' => [
2834                 'coursedata' => $coursedata,
2835                 'classification' => 'all',
2836                 'limit' => 5,
2837                 'offset' => 5,
2838                 'expectedcourses' => [
2839                     'bpast',
2840                     'cfuture',
2841                     'cinprogress',
2842                     'cpast',
2843                     'dfuture'
2844                 ],
2845                 'expectednextoffset' => 10
2846             ],
2847             'all offset past result set' => [
2848                 'coursedata' => $coursedata,
2849                 'classification' => 'all',
2850                 'limit' => 5,
2851                 'offset' => 50,
2852                 'expectedcourses' => [],
2853                 'expectednextoffset' => 50
2854             ],
2855         ];
2856     }
2858     /**
2859      * Test the get_enrolled_courses_by_timeline_classification function.
2860      *
2861      * @dataProvider get_get_enrolled_courses_by_timeline_classification_test_cases()
2862      * @param array $coursedata Courses to create
2863      * @param string $classification Timeline classification
2864      * @param int $limit Maximum number of results
2865      * @param int $offset Offset the unfiltered courses result set by this amount
2866      * @param array $expectedcourses Expected courses in result
2867      * @param int $expectednextoffset Expected next offset value in result
2868      */
2869     public function test_get_enrolled_courses_by_timeline_classification(
2870         $coursedata,
2871         $classification,
2872         $limit,
2873         $offset,
2874         $expectedcourses,
2875         $expectednextoffset
2876     ) {
2877         $this->resetAfterTest();
2878         $generator = $this->getDataGenerator();
2880         $courses = array_map(function($coursedata) use ($generator) {
2881             return $generator->create_course($coursedata);
2882         }, $coursedata);
2884         $student = $generator->create_user();
2886         foreach ($courses as $course) {
2887             $generator->enrol_user($student->id, $course->id, 'student');
2888         }
2890         $this->setUser($student);
2892         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2893         // filtering is done.
2894         // E.g. In our example if an offset of 2 is given then it would mean the first
2895         // two courses (afuture, ainprogress) are ignored.
2896         $result = core_course_external::get_enrolled_courses_by_timeline_classification(
2897             $classification,
2898             $limit,
2899             $offset,
2900             'shortname ASC'
2901         );
2902         $result = external_api::clean_returnvalue(
2903             core_course_external::get_enrolled_courses_by_timeline_classification_returns(),
2904             $result
2905         );
2907         $actual = array_map(function($course) {
2908             return $course['shortname'];
2909         }, $result['courses']);
2911         $this->assertEquals($expectedcourses, $actual);
2912         $this->assertEquals($expectednextoffset, $result['nextoffset']);
2913     }
2915     /**
2916      * Test the get_recent_courses function.
2917      */
2918     public function test_get_recent_courses() {
2919         global $USER, $DB;
2921         $this->resetAfterTest();
2922         $generator = $this->getDataGenerator();
2924         set_config('hiddenuserfields', 'lastaccess');
2926         $courses = array();
2927         for ($i = 1; $i < 12; $i++) {
2928             $courses[]  = $generator->create_course();
2929         };
2931         $student = $generator->create_user();
2932         $teacher = $generator->create_user();
2934         foreach ($courses as $course) {
2935             $generator->enrol_user($student->id, $course->id, 'student');
2936         }
2938         $generator->enrol_user($teacher->id, $courses[0]->id, 'teacher');
2940         $this->setUser($student);
2942         $result = core_course_external::get_recent_courses($USER->id);
2944         // No course accessed.
2945         $this->assertCount(0, $result);
2947         foreach ($courses as $course) {
2948             core_course_external::view_course($course->id);
2949         }
2951         // Every course accessed.
2952         $result = core_course_external::get_recent_courses($USER->id);
2953         $this->assertCount( 11, $result);
2955         // Every course accessed, result limited to 10 courses.
2956         $result = core_course_external::get_recent_courses($USER->id, 10);
2957         $this->assertCount(10, $result);
2959         $guestcourse = $generator->create_course(
2960                 (object)array('shortname' => 'guestcourse',
2961                 'enrol_guest_status_0' => ENROL_INSTANCE_ENABLED,
2962                 'enrol_guest_password_0' => ''));
2963         core_course_external::view_course($guestcourse->id);
2965         // Every course accessed, even the not enrolled one.
2966         $result = core_course_external::get_recent_courses($USER->id);
2967         $this->assertCount(12, $result);
2969         // Offset 5, return 7 out of 12.
2970         $result = core_course_external::get_recent_courses($USER->id, 0, 5);
2971         $this->assertCount(7, $result);
2973         // Offset 5 and limit 3, return 3 out of 12.
2974         $result = core_course_external::get_recent_courses($USER->id, 3, 5);
2975         $this->assertCount(3, $result);
2977         // Sorted by course id ASC.
2978         $result = core_course_external::get_recent_courses($USER->id, 0, 0, 'id ASC');
2979         $this->assertEquals($courses[0]->id, array_shift($result)->id);
2981         // Sorted by course id DESC.
2982         $result = core_course_external::get_recent_courses($USER->id, 0, 0, 'id DESC');
2983         $this->assertEquals($guestcourse->id, array_shift($result)->id);
2985         // If last access is hidden, only get the courses where has viewhiddenuserfields capability.
2986         $this->setUser($teacher);
2987         $teacherroleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher'));
2988         $usercontext = context_user::instance($student->id);
2989         $this->assignUserCapability('moodle/user:viewdetails', $usercontext, $teacherroleid);
2991         // Sorted by course id DESC.
2992         $result = core_course_external::get_recent_courses($student->id);
2993         $this->assertCount(1, $result);
2994         $this->assertEquals($courses[0]->id, array_shift($result)->id);
2995     }