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