Merge branch 'MDL-65019-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 = 'classic';
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'] = 'classic';
455         $course2['courseformatoptions'][] = array('name' => 'automaticenddate', 'value' => 0);
456         $course3['fullname'] = 'Test course 3';
457         $course3['shortname'] = 'Testcourse3';
458         $course3['categoryid'] = $category->id;
459         $course3['format'] = 'topics';
460         $course3options = array('numsections' => 8,
461             'hiddensections' => 1,
462             'coursedisplay' => 1);
463         $course3['courseformatoptions'] = array();
464         foreach ($course3options as $key => $value) {
465             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
466         }
467         $course4['fullname'] = 'Test course with custom fields';
468         $course4['shortname'] = 'Testcoursecustomfields';
469         $course4['categoryid'] = $category->id;
470         $course4['customfields'] = [['shortname' => $customfield['shortname'], 'value' => 'Test value']];
471         $courses = array($course4, $course1, $course2, $course3);
473         $createdcourses = core_course_external::create_courses($courses);
475         // We need to execute the return values cleaning process to simulate the web service server.
476         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
478         // Check that right number of courses were created.
479         $this->assertEquals(4, count($createdcourses));
481         // Check that the courses were correctly created.
482         foreach ($createdcourses as $createdcourse) {
483             $courseinfo = course_get_format($createdcourse['id'])->get_course();
485             if ($createdcourse['shortname'] == $course2['shortname']) {
486                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
487                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
488                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
489                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
490                 $this->assertEquals($courseinfo->summary, $course2['summary']);
491                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
492                 $this->assertEquals($courseinfo->format, $course2['format']);
493                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
494                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
495                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
496                 $this->assertEquals($courseinfo->enddate, $course2['enddate']);
497                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(), $course2['numsections']);
498                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
499                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
500                 $this->assertEquals($courseinfo->visible, $course2['visible']);
501                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
502                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
503                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
504                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
505                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
506                 $this->assertEquals($courseinfo->lang, $course2['lang']);
507                 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
509                 // We enabled completion at the beginning of the test.
510                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
512             } else if ($createdcourse['shortname'] == $course1['shortname']) {
513                 $courseconfig = get_config('moodlecourse');
514                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
515                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
516                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
517                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
518                 $this->assertEquals($courseinfo->format, $courseconfig->format);
519                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
520                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
521                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
522                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
523                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
524                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
525                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
526             } else if ($createdcourse['shortname'] == $course3['shortname']) {
527                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
528                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
529                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
530                 $this->assertEquals($courseinfo->format, $course3['format']);
531                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
532                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(),
533                     $course3options['numsections']);
534                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
535             } else if ($createdcourse['shortname'] == $course4['shortname']) {
536                 $this->assertEquals($courseinfo->fullname, $course4['fullname']);
537                 $this->assertEquals($courseinfo->shortname, $course4['shortname']);
538                 $this->assertEquals($courseinfo->category, $course4['categoryid']);
540                 $handler = core_course\customfield\course_handler::create();
541                 $customfields = $handler->export_instance_data_object($createdcourse['id']);
542                 $this->assertEquals((object)['test' => 'Test value'], $customfields);
543             } else {
544                 throw new moodle_exception('Unexpected shortname');
545             }
546         }
548         // Call without required capability
549         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
550         $this->expectException('required_capability_exception');
551         $createdsubcats = core_course_external::create_courses($courses);
552     }
554     /**
555      * Test delete_courses
556      */
557     public function test_delete_courses() {
558         global $DB, $USER;
560         $this->resetAfterTest(true);
562         // Admin can delete a course.
563         $this->setAdminUser();
564         // Validate_context() will fail as the email is not set by $this->setAdminUser().
565         $USER->email = 'emailtopass@example.com';
567         $course1  = self::getDataGenerator()->create_course();
568         $course2  = self::getDataGenerator()->create_course();
569         $course3  = self::getDataGenerator()->create_course();
571         // Delete courses.
572         $result = core_course_external::delete_courses(array($course1->id, $course2->id));
573         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
574         // Check for 0 warnings.
575         $this->assertEquals(0, count($result['warnings']));
577         // Check $course 1 and 2 are deleted.
578         $notdeletedcount = $DB->count_records_select('course',
579             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
580         $this->assertEquals(0, $notdeletedcount);
582         // Try to delete non-existent course.
583         $result = core_course_external::delete_courses(array($course1->id));
584         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
585         // Check for 1 warnings.
586         $this->assertEquals(1, count($result['warnings']));
588         // Try to delete Frontpage course.
589         $result = core_course_external::delete_courses(array(0));
590         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
591         // Check for 1 warnings.
592         $this->assertEquals(1, count($result['warnings']));
594          // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
595         $student1 = self::getDataGenerator()->create_user();
596         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
597         $this->getDataGenerator()->enrol_user($student1->id,
598                                               $course3->id,
599                                               $studentrole->id);
600         $this->setUser($student1);
601         $result = core_course_external::delete_courses(array($course3->id));
602         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
603         // Check for 1 warnings.
604         $this->assertEquals(1, count($result['warnings']));
606          // Fail when the user is not allow to access the course (enrolled) or is not admin.
607         $this->setGuestUser();
608         $this->expectException('require_login_exception');
610         $result = core_course_external::delete_courses(array($course3->id));
611         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
612     }
614     /**
615      * Test get_courses
616      */
617     public function test_get_courses () {
618         global $DB;
620         $this->resetAfterTest(true);
622         $generatedcourses = array();
623         $coursedata['idnumber'] = 'idnumbercourse1';
624         // Adding tags here to check that format_string is applied.
625         $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
626         $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
627         $coursedata['summary'] = 'Course 1 description';
628         $coursedata['summaryformat'] = FORMAT_MOODLE;
629         $course1  = self::getDataGenerator()->create_course($coursedata);
631         $fieldcategory = self::getDataGenerator()->create_custom_field_category(
632             ['name' => 'Other fields']);
634         $customfield = ['shortname' => 'test', 'name' => 'Custom field', 'type' => 'text',
635             'categoryid' => $fieldcategory->get('id')];
636         $field = self::getDataGenerator()->create_custom_field($customfield);
638         $customfieldvalue = ['shortname' => 'test', 'value' => 'Test value'];
640         $generatedcourses[$course1->id] = $course1;
641         $course2  = self::getDataGenerator()->create_course();
642         $generatedcourses[$course2->id] = $course2;
643         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
644         $generatedcourses[$course3->id] = $course3;
645         $course4  = self::getDataGenerator()->create_course(['customfields' => [$customfieldvalue]]);
646         $generatedcourses[$course4->id] = $course4;
648         // Set the required capabilities by the external function.
649         $context = context_system::instance();
650         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
651         $this->assignUserCapability('moodle/course:update',
652                 context_course::instance($course1->id)->id, $roleid);
653         $this->assignUserCapability('moodle/course:update',
654                 context_course::instance($course2->id)->id, $roleid);
655         $this->assignUserCapability('moodle/course:update',
656                 context_course::instance($course3->id)->id, $roleid);
657         $this->assignUserCapability('moodle/course:update',
658                 context_course::instance($course4->id)->id, $roleid);
660         $courses = core_course_external::get_courses(array('ids' =>
661             array($course1->id, $course2->id, $course4->id)));
663         // We need to execute the return values cleaning process to simulate the web service server.
664         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
666         // Check we retrieve the good total number of courses.
667         $this->assertEquals(3, count($courses));
669         foreach ($courses as $course) {
670             $coursecontext = context_course::instance($course['id']);
671             $dbcourse = $generatedcourses[$course['id']];
672             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
673             $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id));
674             $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse),
675                 $coursecontext->id));
676             // Summary was converted to the HTML format.
677             $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
678             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
679             $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id));
680             $this->assertEquals($course['categoryid'], $dbcourse->category);
681             $this->assertEquals($course['format'], $dbcourse->format);
682             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
683             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
684             $this->assertEquals($course['startdate'], $dbcourse->startdate);
685             $this->assertEquals($course['enddate'], $dbcourse->enddate);
686             $this->assertEquals($course['numsections'], course_get_format($dbcourse)->get_last_section_number());
687             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
688             $this->assertEquals($course['showreports'], $dbcourse->showreports);
689             $this->assertEquals($course['visible'], $dbcourse->visible);
690             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
691             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
692             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
693             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
694             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
695             $this->assertEquals($course['lang'], $dbcourse->lang);
696             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
697             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
698             if ($dbcourse->format === 'topics') {
699                 $this->assertEquals($course['courseformatoptions'], array(
700                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
701                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
702                 ));
703             }
704             if ($dbcourse->id == 4) {
705                 $this->assertEquals($course['customfields'], [array_merge($customfield, $customfieldvalue)]);
706             }
707         }
709         // Get all courses in the DB
710         $courses = core_course_external::get_courses(array());
712         // We need to execute the return values cleaning process to simulate the web service server.
713         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
715         $this->assertEquals($DB->count_records('course'), count($courses));
716     }
718     /**
719      * Test get_courses without capability
720      */
721     public function test_get_courses_without_capability() {
722         $this->resetAfterTest(true);
724         $course1 = $this->getDataGenerator()->create_course();
725         $this->setUser($this->getDataGenerator()->create_user());
727         // No permissions are required to get the site course.
728         $courses = core_course_external::get_courses(array('ids' => [SITEID]));
729         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
731         $this->assertEquals(1, count($courses));
732         $this->assertEquals('PHPUnit test site', $courses[0]['fullname']);
733         $this->assertEquals('site', $courses[0]['format']);
735         // Requesting course without being enrolled or capability to view it will throw an exception.
736         try {
737             core_course_external::get_courses(array('ids' => [$course1->id]));
738             $this->fail('Exception expected');
739         } catch (moodle_exception $e) {
740             $this->assertEquals(1, preg_match('/Course or activity not accessible. \(Not enrolled\)/', $e->getMessage()));
741         }
742     }
744     /**
745      * Test search_courses
746      */
747     public function test_search_courses () {
749         global $DB;
751         $this->resetAfterTest(true);
752         $this->setAdminUser();
753         $generatedcourses = array();
754         $coursedata1['fullname'] = 'FIRST COURSE';
755         $course1  = self::getDataGenerator()->create_course($coursedata1);
757         $page = new moodle_page();
758         $page->set_course($course1);
759         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
761         $coursedata2['fullname'] = 'SECOND COURSE';
762         $course2  = self::getDataGenerator()->create_course($coursedata2);
764         $page = new moodle_page();
765         $page->set_course($course2);
766         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
768         // Search by name.
769         $results = core_course_external::search_courses('search', 'FIRST');
770         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
771         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
772         $this->assertCount(1, $results['courses']);
774         // Create the forum.
775         $record = new stdClass();
776         $record->introformat = FORMAT_HTML;
777         $record->course = $course2->id;
778         // Set Aggregate type = Average of ratings.
779         $forum = self::getDataGenerator()->create_module('forum', $record);
781         // Search by module.
782         $results = core_course_external::search_courses('modulelist', 'forum');
783         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
784         $this->assertEquals(1, $results['total']);
786         // Enable coursetag option.
787         set_config('block_tags_showcoursetags', true);
788         // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
789         core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
790                 array('TAG-LABEL ON SECOND COURSE'));
791         $taginstance = $DB->get_record('tag_instance',
792                 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
794         // Search by tagid.
795         $results = core_course_external::search_courses('tagid', $taginstance->tagid);
796         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
797         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
799         // Search by block (use news_items default block).
800         $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
801         $results = core_course_external::search_courses('blocklist', $blockid);
802         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
803         $this->assertEquals(2, $results['total']);
805         // Now as a normal user.
806         $user = self::getDataGenerator()->create_user();
808         // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
809         $coursedata3['fullname'] = 'HIDDEN COURSE';
810         $coursedata3['visible'] = 0;
811         $course3  = self::getDataGenerator()->create_course($coursedata3);
812         $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
814         $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
815         $this->setUser($user);
817         $results = core_course_external::search_courses('search', 'FIRST');
818         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
819         $this->assertCount(1, $results['courses']);
820         $this->assertEquals(1, $results['total']);
821         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
823         // Check that we can see all courses without the limit to enrolled setting.
824         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
825         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
826         $this->assertCount(2, $results['courses']);
827         $this->assertEquals(2, $results['total']);
829         // Check that we only see our enrolled course when limiting.
830         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
831         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
832         $this->assertCount(1, $results['courses']);
833         $this->assertEquals(1, $results['total']);
834         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
836         // Search by block (use news_items default block). Should fail (only admins allowed).
837         $this->expectException('required_capability_exception');
838         $results = core_course_external::search_courses('blocklist', $blockid);
839     }
841     /**
842      * Create a course with contents
843      * @return array A list with the course object and course modules objects
844      */
845     private function prepare_get_course_contents_test() {
846         global $DB, $CFG;
848         $CFG->allowstealth = 1; // Allow stealth activities.
849         $CFG->enablecompletion = true;
850         $course  = self::getDataGenerator()->create_course(['numsections' => 4, 'enablecompletion' => 1]);
852         $forumdescription = 'This is the forum description';
853         $forum = $this->getDataGenerator()->create_module('forum',
854             array('course' => $course->id, 'intro' => $forumdescription, 'trackingtype' => 2),
855             array('showdescription' => true, 'completion' => COMPLETION_TRACKING_MANUAL));
856         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
857         // Add discussions to the tracking forced forum.
858         $record = new stdClass();
859         $record->course = $course->id;
860         $record->userid = 0;
861         $record->forum = $forum->id;
862         $discussionforce = $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
863         $data = $this->getDataGenerator()->create_module('data',
864             array('assessed' => 1, 'scale' => 100, 'course' => $course->id, 'completion' => 2, 'completionentries' => 3));
865         $datacm = get_coursemodule_from_instance('data', $data->id);
866         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
867         $pagecm = get_coursemodule_from_instance('page', $page->id);
868         // This is an stealth page (set by visibleoncoursepage).
869         $pagestealth = $this->getDataGenerator()->create_module('page', array('course' => $course->id, 'visibleoncoursepage' => 0));
870         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
871                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
872         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
873             'intro' => $labeldescription, 'completion' => COMPLETION_TRACKING_MANUAL));
874         $labelcm = get_coursemodule_from_instance('label', $label->id);
875         $tomorrow = time() + DAYSECS;
876         // Module with availability restrictions not met.
877         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '},'
878                 .'{"type":"completion","cm":' . $label->cmid .',"e":1}],"showc":[true,true]}';
879         $url = $this->getDataGenerator()->create_module('url',
880             array('course' => $course->id, 'name' => 'URL: % & $ ../', 'section' => 2, 'display' => RESOURCELIB_DISPLAY_POPUP,
881                 'popupwidth' => 100, 'popupheight' => 100),
882             array('availability' => $availability));
883         $urlcm = get_coursemodule_from_instance('url', $url->id);
884         // Module for the last section.
885         $this->getDataGenerator()->create_module('url',
886             array('course' => $course->id, 'name' => 'URL for last section', 'section' => 3));
887         // Module for section 1 with availability restrictions met.
888         $yesterday = time() - DAYSECS;
889         $this->getDataGenerator()->create_module('url',
890             array('course' => $course->id, 'name' => 'URL restrictions met', 'section' => 1),
891             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":'. $yesterday .'}],"showc":[true]}'));
893         // Set the required capabilities by the external function.
894         $context = context_course::instance($course->id);
895         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
896         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
897         $this->assignUserCapability('mod/data:view', $context->id, $roleid);
899         $conditions = array('course' => $course->id, 'section' => 2);
900         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
902         // Add date availability condition not met for section 3.
903         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}';
904         $DB->set_field('course_sections', 'availability', $availability,
905                 array('course' => $course->id, 'section' => 3));
907         // Create resource for last section.
908         $pageinhiddensection = $this->getDataGenerator()->create_module('page',
909             array('course' => $course->id, 'name' => 'Page in hidden section', 'section' => 4));
910         // Set not visible last section.
911         $DB->set_field('course_sections', 'visible', 0,
912                 array('course' => $course->id, 'section' => 4));
914         rebuild_course_cache($course->id, true);
916         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
917     }
919     /**
920      * Test get_course_contents
921      */
922     public function test_get_course_contents() {
923         global $CFG;
924         $this->resetAfterTest(true);
926         $CFG->forum_allowforcedreadtracking = 1;
927         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
929         // We first run the test as admin.
930         $this->setAdminUser();
931         $sections = core_course_external::get_course_contents($course->id, array());
932         // We need to execute the return values cleaning process to simulate the web service server.
933         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
935         $modinfo = get_fast_modinfo($course);
936         $testexecuted = 0;
937         foreach ($sections[0]['modules'] as $module) {
938             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
939                 $cm = $modinfo->cms[$forumcm->id];
940                 $formattedtext = format_text($cm->content, FORMAT_HTML,
941                     array('noclean' => true, 'para' => false, 'filter' => false));
942                 $this->assertEquals($formattedtext, $module['description']);
943                 $this->assertEquals($forumcm->instance, $module['instance']);
944                 $this->assertContains('1 unread post', $module['afterlink']);
945                 $testexecuted = $testexecuted + 2;
946             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
947                 $cm = $modinfo->cms[$labelcm->id];
948                 $formattedtext = format_text($cm->content, FORMAT_HTML,
949                     array('noclean' => true, 'para' => false, 'filter' => false));
950                 $this->assertEquals($formattedtext, $module['description']);
951                 $this->assertEquals($labelcm->instance, $module['instance']);
952                 $testexecuted = $testexecuted + 1;
953             } else if ($module['id'] == $datacm->id and $module['modname'] == 'data') {
954                 $this->assertContains('customcompletionrules', $module['customdata']);
955                 $testexecuted = $testexecuted + 1;
956             }
957         }
958         foreach ($sections[2]['modules'] as $module) {
959             if ($module['id'] == $urlcm->id and $module['modname'] == 'url') {
960                 $this->assertContains('width=100,height=100', $module['onclick']);
961                 $this->assertContains('moodle.org', $module['customdata']);
962                 $testexecuted = $testexecuted + 1;
963             }
964         }
966         $CFG->forum_allowforcedreadtracking = 0;    // Recover original value.
967         forum_tp_count_forum_unread_posts($forumcm, $course, true);    // Reset static cache for further tests.
969         $this->assertEquals(5, $testexecuted);
970         $this->assertEquals(0, $sections[0]['section']);
972         $this->assertCount(5, $sections[0]['modules']);
973         $this->assertCount(1, $sections[1]['modules']);
974         $this->assertCount(1, $sections[2]['modules']);
975         $this->assertCount(1, $sections[3]['modules']); // One module for the section with availability restrictions.
976         $this->assertCount(1, $sections[4]['modules']); // One module for the hidden section with a visible activity.
977         $this->assertNotEmpty($sections[3]['availabilityinfo']);
978         $this->assertEquals(1, $sections[1]['section']);
979         $this->assertEquals(2, $sections[2]['section']);
980         $this->assertEquals(3, $sections[3]['section']);
981         $this->assertEquals(4, $sections[4]['section']);
982         $this->assertContains('<iframe', $sections[2]['summary']);
983         $this->assertContains('</iframe>', $sections[2]['summary']);
984         $this->assertNotEmpty($sections[2]['modules'][0]['availabilityinfo']);
985         try {
986             $sections = core_course_external::get_course_contents($course->id,
987                                                                     array(array("name" => "invalid", "value" => 1)));
988             $this->fail('Exception expected due to invalid option.');
989         } catch (moodle_exception $e) {
990             $this->assertEquals('errorinvalidparam', $e->errorcode);
991         }
992     }
995     /**
996      * Test get_course_contents as student
997      */
998     public function test_get_course_contents_student() {
999         global $DB;
1000         $this->resetAfterTest(true);
1002         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1004         $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
1005         $user = self::getDataGenerator()->create_user();
1006         self::getDataGenerator()->enrol_user($user->id, $course->id, $studentroleid);
1007         $this->setUser($user);
1009         $sections = core_course_external::get_course_contents($course->id, array());
1010         // We need to execute the return values cleaning process to simulate the web service server.
1011         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1013         $this->assertCount(4, $sections); // Nothing for the not visible section.
1014         $this->assertCount(5, $sections[0]['modules']);
1015         $this->assertCount(1, $sections[1]['modules']);
1016         $this->assertCount(1, $sections[2]['modules']);
1017         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
1019         $this->assertNotEmpty($sections[3]['availabilityinfo']);
1020         $this->assertEquals(1, $sections[1]['section']);
1021         $this->assertEquals(2, $sections[2]['section']);
1022         $this->assertEquals(3, $sections[3]['section']);
1023         // The module with the availability restriction met is returning contents.
1024         $this->assertNotEmpty($sections[1]['modules'][0]['contents']);
1025         // The module with the availability restriction not met is not returning contents.
1026         $this->assertArrayNotHasKey('contents', $sections[2]['modules'][0]);
1028         // Now include flag for returning stealth information (fake section).
1029         $sections = core_course_external::get_course_contents($course->id,
1030             array(array("name" => "includestealthmodules", "value" => 1)));
1031         // We need to execute the return values cleaning process to simulate the web service server.
1032         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1034         $this->assertCount(5, $sections); // Include fake section with stealth activities.
1035         $this->assertCount(5, $sections[0]['modules']);
1036         $this->assertCount(1, $sections[1]['modules']);
1037         $this->assertCount(1, $sections[2]['modules']);
1038         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
1039         $this->assertCount(1, $sections[4]['modules']); // One stealh module.
1040         $this->assertEquals(-1, $sections[4]['id']);
1041     }
1043     /**
1044      * Test get_course_contents excluding modules
1045      */
1046     public function test_get_course_contents_excluding_modules() {
1047         $this->resetAfterTest(true);
1049         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1051         // Test exclude modules.
1052         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
1054         // We need to execute the return values cleaning process to simulate the web service server.
1055         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1057         $this->assertEmpty($sections[0]['modules']);
1058         $this->assertEmpty($sections[1]['modules']);
1059     }
1061     /**
1062      * Test get_course_contents excluding contents
1063      */
1064     public function test_get_course_contents_excluding_contents() {
1065         $this->resetAfterTest(true);
1067         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1069         // Test exclude modules.
1070         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
1072         // We need to execute the return values cleaning process to simulate the web service server.
1073         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1075         foreach ($sections as $section) {
1076             foreach ($section['modules'] as $module) {
1077                 // Only resources return contents.
1078                 if (isset($module['contents'])) {
1079                     $this->assertEmpty($module['contents']);
1080                 }
1081             }
1082         }
1083     }
1085     /**
1086      * Test get_course_contents filtering by section number
1087      */
1088     public function test_get_course_contents_section_number() {
1089         $this->resetAfterTest(true);
1091         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1093         // Test exclude modules.
1094         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
1096         // We need to execute the return values cleaning process to simulate the web service server.
1097         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1099         $this->assertCount(1, $sections);
1100         $this->assertCount(5, $sections[0]['modules']);
1101     }
1103     /**
1104      * Test get_course_contents filtering by cmid
1105      */
1106     public function test_get_course_contents_cmid() {
1107         $this->resetAfterTest(true);
1109         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1111         // Test exclude modules.
1112         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
1114         // We need to execute the return values cleaning process to simulate the web service server.
1115         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1117         $this->assertCount(4, $sections);
1118         $this->assertCount(1, $sections[0]['modules']);
1119         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1120     }
1123     /**
1124      * Test get_course_contents filtering by cmid and section
1125      */
1126     public function test_get_course_contents_section_cmid() {
1127         $this->resetAfterTest(true);
1129         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1131         // Test exclude modules.
1132         $sections = core_course_external::get_course_contents($course->id, array(
1133                                                                         array("name" => "cmid", "value" => $forumcm->id),
1134                                                                         array("name" => "sectionnumber", "value" => 0)
1135                                                                         ));
1137         // We need to execute the return values cleaning process to simulate the web service server.
1138         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1140         $this->assertCount(1, $sections);
1141         $this->assertCount(1, $sections[0]['modules']);
1142         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1143     }
1145     /**
1146      * Test get_course_contents filtering by modname
1147      */
1148     public function test_get_course_contents_modname() {
1149         $this->resetAfterTest(true);
1151         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1153         // Test exclude modules.
1154         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
1156         // We need to execute the return values cleaning process to simulate the web service server.
1157         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1159         $this->assertCount(4, $sections);
1160         $this->assertCount(1, $sections[0]['modules']);
1161         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1162     }
1164     /**
1165      * Test get_course_contents filtering by modname
1166      */
1167     public function test_get_course_contents_modid() {
1168         $this->resetAfterTest(true);
1170         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1172         // Test exclude modules.
1173         $sections = core_course_external::get_course_contents($course->id, array(
1174                                                                             array("name" => "modname", "value" => "page"),
1175                                                                             array("name" => "modid", "value" => $pagecm->instance),
1176                                                                             ));
1178         // We need to execute the return values cleaning process to simulate the web service server.
1179         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1181         $this->assertCount(4, $sections);
1182         $this->assertCount(1, $sections[0]['modules']);
1183         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
1184         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
1185     }
1187     /**
1188      * Test get course contents completion
1189      */
1190     public function test_get_course_contents_completion() {
1191         global $CFG;
1192         $this->resetAfterTest(true);
1194         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1195         availability_completion\condition::wipe_static_cache();
1197         // Test activity not completed yet.
1198         $result = core_course_external::get_course_contents($course->id, array(
1199             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1200         // We need to execute the return values cleaning process to simulate the web service server.
1201         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1203         $this->assertCount(1, $result[0]['modules']);
1204         $this->assertEquals("forum", $result[0]['modules'][0]["modname"]);
1205         $this->assertEquals(COMPLETION_TRACKING_MANUAL, $result[0]['modules'][0]["completion"]);
1206         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['state']);
1207         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['timecompleted']);
1208         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1209         $this->assertFalse($result[0]['modules'][0]["completiondata"]['valueused']);
1211         // Set activity completed.
1212         core_completion_external::update_activity_completion_status_manually($forumcm->id, true);
1214         $result = core_course_external::get_course_contents($course->id, array(
1215             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1216         // We need to execute the return values cleaning process to simulate the web service server.
1217         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1219         $this->assertEquals(COMPLETION_COMPLETE, $result[0]['modules'][0]["completiondata"]['state']);
1220         $this->assertNotEmpty($result[0]['modules'][0]["completiondata"]['timecompleted']);
1221         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1223         // Test activity with completion value that is used in an availability condition.
1224         $result = core_course_external::get_course_contents($course->id, array(
1225                 array("name" => "modname", "value" => "label"), array("name" => "modid", "value" => $labelcm->instance)));
1226         // We need to execute the return values cleaning process to simulate the web service server.
1227         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1229         $this->assertCount(1, $result[0]['modules']);
1230         $this->assertEquals("label", $result[0]['modules'][0]["modname"]);
1231         $this->assertEquals(COMPLETION_TRACKING_MANUAL, $result[0]['modules'][0]["completion"]);
1232         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['state']);
1233         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['timecompleted']);
1234         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1235         $this->assertTrue($result[0]['modules'][0]["completiondata"]['valueused']);
1237         // Disable completion.
1238         $CFG->enablecompletion = 0;
1239         $result = core_course_external::get_course_contents($course->id, array(
1240             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1241         // We need to execute the return values cleaning process to simulate the web service server.
1242         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1244         $this->assertArrayNotHasKey('completiondata', $result[0]['modules'][0]);
1245     }
1247     /**
1248      * Test mimetype is returned for resources with showtype set.
1249      */
1250     public function test_get_course_contents_including_mimetype() {
1251         $this->resetAfterTest(true);
1253         $this->setAdminUser();
1254         $course = self::getDataGenerator()->create_course();
1256         $record = new stdClass();
1257         $record->course = $course->id;
1258         $record->showtype = 1;
1259         $resource = self::getDataGenerator()->create_module('resource', $record);
1261         $result = core_course_external::get_course_contents($course->id);
1262         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1263         $this->assertCount(1, $result[0]['modules']);   // One module, first section.
1264         $customdata = unserialize(json_decode($result[0]['modules'][0]['customdata']));
1265         $this->assertEquals('text/plain', $customdata['filedetails']['mimetype']);
1266     }
1268     /**
1269      * Test contents info is returned.
1270      */
1271     public function test_get_course_contents_contentsinfo() {
1272         global $USER;
1274         $this->resetAfterTest(true);
1276         $this->setAdminUser();
1277         $course = self::getDataGenerator()->create_course();
1279         $record = new stdClass();
1280         $record->course = $course->id;
1281         // One resource with one file.
1282         $resource1 = self::getDataGenerator()->create_module('resource', $record);
1284         $timenow = time();
1285         // More type of files.
1286         $record->files = file_get_unused_draft_itemid();
1287         $usercontext = context_user::instance($USER->id);
1288         $extensions = array('txt', 'png', 'pdf');
1289         $fs = get_file_storage();
1290         foreach ($extensions as $key => $extension) {
1291             // Add actual file there.
1292             $filerecord = array('component' => 'user', 'filearea' => 'draft',
1293                     'contextid' => $usercontext->id, 'itemid' => $record->files,
1294                     'filename' => 'resource' . $key . '.' . $extension, 'filepath' => '/');
1295             $fs->create_file_from_string($filerecord, 'Test resource ' . $key . ' file');
1296         }
1298         // Create file reference.
1299         $repos = repository::get_instances(array('type' => 'user'));
1300         $userrepository = reset($repos);
1302         // Create a user private file.
1303         $userfilerecord = new stdClass;
1304         $userfilerecord->contextid = $usercontext->id;
1305         $userfilerecord->component = 'user';
1306         $userfilerecord->filearea  = 'private';
1307         $userfilerecord->itemid    = 0;
1308         $userfilerecord->filepath  = '/';
1309         $userfilerecord->filename  = 'userfile.txt';
1310         $userfilerecord->source    = 'test';
1311         $userfile = $fs->create_file_from_string($userfilerecord, 'User file content');
1312         $userfileref = $fs->pack_reference($userfilerecord);
1314         // Clone latest "normal" file.
1315         $filerefrecord = clone (object) $filerecord;
1316         $filerefrecord->filename = 'testref.txt';
1317         $fileref = $fs->create_file_from_reference($filerefrecord, $userrepository->id, $userfileref);
1318         // Set main file pointing to the file reference.
1319         file_set_sortorder($usercontext->id, 'user', 'draft', $record->files, $filerefrecord->filepath,
1320             $filerefrecord->filename, 1);
1322         // Once the reference has been created, create the file resource.
1323         $resource2 = self::getDataGenerator()->create_module('resource', $record);
1325         $result = core_course_external::get_course_contents($course->id);
1326         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1327         $this->assertCount(2, $result[0]['modules']);
1328         foreach ($result[0]['modules'] as $module) {
1329             if ($module['instance'] == $resource1->id) {
1330                 $this->assertEquals(1, $module['contentsinfo']['filescount']);
1331                 $this->assertGreaterThanOrEqual($timenow, $module['contentsinfo']['lastmodified']);
1332                 $this->assertEquals($module['contents'][0]['filesize'], $module['contentsinfo']['filessize']);
1333                 $this->assertEquals(array('text/plain'), $module['contentsinfo']['mimetypes']);
1334             } else {
1335                 $this->assertEquals(count($extensions) + 1, $module['contentsinfo']['filescount']);
1336                 $filessize = $module['contents'][0]['filesize'] + $module['contents'][1]['filesize'] +
1337                     $module['contents'][2]['filesize'] + $module['contents'][3]['filesize'];
1338                 $this->assertEquals($filessize, $module['contentsinfo']['filessize']);
1339                 $this->assertEquals('user', $module['contentsinfo']['repositorytype']);
1340                 $this->assertGreaterThanOrEqual($timenow, $module['contentsinfo']['lastmodified']);
1341                 $this->assertEquals(array('text/plain', 'image/png', 'application/pdf'), $module['contentsinfo']['mimetypes']);
1342             }
1343         }
1344     }
1346     /**
1347      * Test duplicate_course
1348      */
1349     public function test_duplicate_course() {
1350         $this->resetAfterTest(true);
1352         // Create one course with three modules.
1353         $course  = self::getDataGenerator()->create_course();
1354         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
1355         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
1356         $forumcontext = context_module::instance($forum->cmid);
1357         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
1358         $datacontext = context_module::instance($data->cmid);
1359         $datacm = get_coursemodule_from_instance('page', $data->id);
1360         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
1361         $pagecontext = context_module::instance($page->cmid);
1362         $pagecm = get_coursemodule_from_instance('page', $page->id);
1364         // Set the required capabilities by the external function.
1365         $coursecontext = context_course::instance($course->id);
1366         $categorycontext = context_coursecat::instance($course->category);
1367         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
1368         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
1369         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
1370         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
1371         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
1372         // Optional capabilities to copy user data.
1373         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
1374         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
1376         $newcourse['fullname'] = 'Course duplicate';
1377         $newcourse['shortname'] = 'courseduplicate';
1378         $newcourse['categoryid'] = $course->category;
1379         $newcourse['visible'] = true;
1380         $newcourse['options'][] = array('name' => 'users', 'value' => true);
1382         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
1383                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
1385         // We need to execute the return values cleaning process to simulate the web service server.
1386         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1388         // Check that the course has been duplicated.
1389         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1390     }
1392     /**
1393      * Test update_courses
1394      */
1395     public function test_update_courses() {
1396         global $DB, $CFG, $USER, $COURSE;
1398         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1399         // trick because we are both updating and getting (for testing) course information
1400         // in the same request and core_course_external::update_courses()
1401         // is overwriting $COURSE all over the time with OLD values, so later
1402         // use of get_course() fetches those OLD values instead of the updated ones.
1403         // See MDL-39723 for more info.
1404         $origcourse = clone($COURSE);
1406         $this->resetAfterTest(true);
1408         // Set the required capabilities by the external function.
1409         $contextid = context_system::instance()->id;
1410         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1411         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1412         $this->assignUserCapability('moodle/course:changelockedcustomfields', $contextid, $roleid);
1413         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1414         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1415         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1416         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1417         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1418         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1419         $this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
1421         // Create category and courses.
1422         $category1  = self::getDataGenerator()->create_category();
1423         $category2  = self::getDataGenerator()->create_category();
1425         $originalcourse1 = self::getDataGenerator()->create_course();
1426         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1428         $originalcourse2 = self::getDataGenerator()->create_course();
1429         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1431         // Course with custom fields.
1432         $fieldcategory = self::getDataGenerator()->create_custom_field_category(['name' => 'Other fields']);
1433         $customfield = ['shortname' => 'test', 'name' => 'Custom field', 'type' => 'text',
1434             'categoryid' => $fieldcategory->get('id'),
1435             'configdata' => ['visibility' => \core_course\customfield\course_handler::VISIBLETOALL, 'locked' => 1]];
1436         $field = self::getDataGenerator()->create_custom_field($customfield);
1438         $originalcourse3 = self::getDataGenerator()->create_course(['customfield_test' => 'Test value']);
1439         self::getDataGenerator()->enrol_user($USER->id, $originalcourse3->id, $roleid);
1441         // Course values to be updated.
1442         $course1['id'] = $originalcourse1->id;
1443         $course1['fullname'] = 'Updated test course 1';
1444         $course1['shortname'] = 'Udestedtestcourse1';
1445         $course1['categoryid'] = $category1->id;
1447         $course2['id'] = $originalcourse2->id;
1448         $course2['fullname'] = 'Updated test course 2';
1449         $course2['shortname'] = 'Updestedtestcourse2';
1450         $course2['categoryid'] = $category2->id;
1451         $course2['idnumber'] = 'Updatedidnumber2';
1452         $course2['summary'] = 'Updaated description for course 2';
1453         $course2['summaryformat'] = FORMAT_HTML;
1454         $course2['format'] = 'topics';
1455         $course2['showgrades'] = 1;
1456         $course2['newsitems'] = 3;
1457         $course2['startdate'] = 1420092000; // 01/01/2015.
1458         $course2['enddate'] = 1422669600; // 01/31/2015.
1459         $course2['maxbytes'] = 100000;
1460         $course2['showreports'] = 1;
1461         $course2['visible'] = 0;
1462         $course2['hiddensections'] = 0;
1463         $course2['groupmode'] = 0;
1464         $course2['groupmodeforce'] = 0;
1465         $course2['defaultgroupingid'] = 0;
1466         $course2['enablecompletion'] = 1;
1467         $course2['lang'] = 'en';
1468         $course2['forcetheme'] = 'classic';
1470         $course3['id'] = $originalcourse3->id;
1471         $updatedcustomfieldvalue = ['shortname' => 'test', 'value' => 'Updated test value'];
1472         $course3['customfields'] = [$updatedcustomfieldvalue];
1473         $courses = array($course1, $course2, $course3);
1475         $updatedcoursewarnings = core_course_external::update_courses($courses);
1476         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1477                 $updatedcoursewarnings);
1478         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1480         // Check that right number of courses were created.
1481         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1483         // Check that the courses were correctly created.
1484         foreach ($courses as $course) {
1485             $courseinfo = course_get_format($course['id'])->get_course();
1486             $customfields = \core_course\customfield\course_handler::create()->export_instance_data_object($course['id']);
1487             if ($course['id'] == $course2['id']) {
1488                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1489                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1490                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1491                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1492                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1493                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1494                 $this->assertEquals($course2['format'], $courseinfo->format);
1495                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1496                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1497                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1498                 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
1499                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1500                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1501                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1502                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1503                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1504                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1505                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1506                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1508                 if (!empty($CFG->allowcoursethemes)) {
1509                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1510                 }
1512                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1513                 $this->assertEquals(['test' => null], (array)$customfields);
1514             } else if ($course['id'] == $course1['id']) {
1515                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1516                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1517                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1518                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1519                 $this->assertEquals('topics', $courseinfo->format);
1520                 $this->assertEquals(5, course_get_format($course['id'])->get_last_section_number());
1521                 $this->assertEquals(0, $courseinfo->newsitems);
1522                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1523                 $this->assertEquals(['test' => null], (array)$customfields);
1524             } else if ($course['id'] == $course3['id']) {
1525                 $this->assertEquals(['test' => $updatedcustomfieldvalue['value']], (array)$customfields);
1526             } else {
1527                 throw new moodle_exception('Unexpected shortname');
1528             }
1529         }
1531         $courses = array($course1);
1532         // Try update course without update capability.
1533         $user = self::getDataGenerator()->create_user();
1534         $this->setUser($user);
1535         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1536         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
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 category without capability.
1543         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1544         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1545         $user = self::getDataGenerator()->create_user();
1546         $this->setUser($user);
1547         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1548         $course1['categoryid'] = $category2->id;
1549         $courses = array($course1);
1550         $updatedcoursewarnings = core_course_external::update_courses($courses);
1551         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1552                                                                     $updatedcoursewarnings);
1553         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1555         // Try update course fullname without capability.
1556         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1557         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1558         $user = self::getDataGenerator()->create_user();
1559         $this->setUser($user);
1560         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1561         $updatedcoursewarnings = core_course_external::update_courses($courses);
1562         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1563                                                                     $updatedcoursewarnings);
1564         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1565         $course1['fullname'] = 'Testing fullname without permission';
1566         $courses = array($course1);
1567         $updatedcoursewarnings = core_course_external::update_courses($courses);
1568         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1569                                                                     $updatedcoursewarnings);
1570         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1572         // Try update course shortname without capability.
1573         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1574         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1575         $user = self::getDataGenerator()->create_user();
1576         $this->setUser($user);
1577         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1578         $updatedcoursewarnings = core_course_external::update_courses($courses);
1579         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1580                                                                     $updatedcoursewarnings);
1581         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1582         $course1['shortname'] = 'Testing shortname without permission';
1583         $courses = array($course1);
1584         $updatedcoursewarnings = core_course_external::update_courses($courses);
1585         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1586                                                                     $updatedcoursewarnings);
1587         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1589         // Try update course idnumber without capability.
1590         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1591         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1592         $user = self::getDataGenerator()->create_user();
1593         $this->setUser($user);
1594         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1595         $updatedcoursewarnings = core_course_external::update_courses($courses);
1596         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1597                                                                     $updatedcoursewarnings);
1598         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1599         $course1['idnumber'] = 'NEWIDNUMBER';
1600         $courses = array($course1);
1601         $updatedcoursewarnings = core_course_external::update_courses($courses);
1602         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1603                                                                     $updatedcoursewarnings);
1604         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1606         // Try update course summary without capability.
1607         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1608         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1609         $user = self::getDataGenerator()->create_user();
1610         $this->setUser($user);
1611         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1612         $updatedcoursewarnings = core_course_external::update_courses($courses);
1613         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1614                                                                     $updatedcoursewarnings);
1615         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1616         $course1['summary'] = 'New summary';
1617         $courses = array($course1);
1618         $updatedcoursewarnings = core_course_external::update_courses($courses);
1619         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1620                                                                     $updatedcoursewarnings);
1621         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1623         // Try update course with invalid summary format.
1624         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1625         $user = self::getDataGenerator()->create_user();
1626         $this->setUser($user);
1627         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1628         $updatedcoursewarnings = core_course_external::update_courses($courses);
1629         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1630                                                                     $updatedcoursewarnings);
1631         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1632         $course1['summaryformat'] = 10;
1633         $courses = array($course1);
1634         $updatedcoursewarnings = core_course_external::update_courses($courses);
1635         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1636                                                                     $updatedcoursewarnings);
1637         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1639         // Try update course visibility without capability.
1640         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1641         $user = self::getDataGenerator()->create_user();
1642         $this->setUser($user);
1643         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1644         $course1['summaryformat'] = FORMAT_MOODLE;
1645         $courses = array($course1);
1646         $updatedcoursewarnings = core_course_external::update_courses($courses);
1647         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1648                                                                     $updatedcoursewarnings);
1649         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1650         $course1['visible'] = 0;
1651         $courses = array($course1);
1652         $updatedcoursewarnings = core_course_external::update_courses($courses);
1653         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1654                                                                     $updatedcoursewarnings);
1655         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1657         // Try update course custom fields without capability.
1658         $this->unassignUserCapability('moodle/course:changelockedcustomfields', $contextid, $roleid);
1659         $user = self::getDataGenerator()->create_user();
1660         $this->setUser($user);
1661         self::getDataGenerator()->enrol_user($user->id, $course3['id'], $roleid);
1663         $newupdatedcustomfieldvalue = ['shortname' => 'test', 'value' => 'New updated value'];
1664         $course3['customfields'] = [$newupdatedcustomfieldvalue];
1666         core_course_external::update_courses([$course3]);
1668         // Custom field was not updated.
1669         $customfields = \core_course\customfield\course_handler::create()->export_instance_data_object($course3['id']);
1670         $this->assertEquals(['test' => $updatedcustomfieldvalue['value']], (array)$customfields);
1671     }
1673     /**
1674      * Test delete course_module.
1675      */
1676     public function test_delete_modules() {
1677         global $DB;
1679         // Ensure we reset the data after this test.
1680         $this->resetAfterTest(true);
1682         // Create a user.
1683         $user = self::getDataGenerator()->create_user();
1685         // Set the tests to run as the user.
1686         self::setUser($user);
1688         // Create a course to add the modules.
1689         $course = self::getDataGenerator()->create_course();
1691         // Create two test modules.
1692         $record = new stdClass();
1693         $record->course = $course->id;
1694         $module1 = self::getDataGenerator()->create_module('forum', $record);
1695         $module2 = self::getDataGenerator()->create_module('assign', $record);
1697         // Check the forum was correctly created.
1698         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1700         // Check the assignment was correctly created.
1701         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1703         // Check data exists in the course modules table.
1704         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1705                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1707         // Enrol the user in the course.
1708         $enrol = enrol_get_plugin('manual');
1709         $enrolinstances = enrol_get_instances($course->id, true);
1710         foreach ($enrolinstances as $courseenrolinstance) {
1711             if ($courseenrolinstance->enrol == "manual") {
1712                 $instance = $courseenrolinstance;
1713                 break;
1714             }
1715         }
1716         $enrol->enrol_user($instance, $user->id);
1718         // Assign capabilities to delete module 1.
1719         $modcontext = context_module::instance($module1->cmid);
1720         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1722         // Assign capabilities to delete module 2.
1723         $modcontext = context_module::instance($module2->cmid);
1724         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1725         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1727         // Deleting these module instances.
1728         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1730         // Check the forum was deleted.
1731         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1733         // Check the assignment was deleted.
1734         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1736         // Check we retrieve no data in the course modules table.
1737         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1738                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1740         // Call with non-existent course module id and ensure exception thrown.
1741         try {
1742             core_course_external::delete_modules(array('1337'));
1743             $this->fail('Exception expected due to missing course module.');
1744         } catch (dml_missing_record_exception $e) {
1745             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1746         }
1748         // Create two modules.
1749         $module1 = self::getDataGenerator()->create_module('forum', $record);
1750         $module2 = self::getDataGenerator()->create_module('assign', $record);
1752         // Since these modules were recreated the user will not have capabilities
1753         // to delete them, ensure exception is thrown if they try.
1754         try {
1755             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1756             $this->fail('Exception expected due to missing capability.');
1757         } catch (moodle_exception $e) {
1758             $this->assertEquals('nopermissions', $e->errorcode);
1759         }
1761         // Unenrol user from the course.
1762         $enrol->unenrol_user($instance, $user->id);
1764         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1765         try {
1766             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1767             $this->fail('Exception expected due to being unenrolled from the course.');
1768         } catch (moodle_exception $e) {
1769             $this->assertEquals('requireloginerror', $e->errorcode);
1770         }
1771     }
1773     /**
1774      * Test import_course into an empty course
1775      */
1776     public function test_import_course_empty() {
1777         global $USER;
1779         $this->resetAfterTest(true);
1781         $course1  = self::getDataGenerator()->create_course();
1782         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1783         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1785         $course2  = self::getDataGenerator()->create_course();
1787         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1788         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1790         // Verify the state of the courses before we do the import.
1791         $this->assertCount(2, $course1cms);
1792         $this->assertEmpty($course2cms);
1794         // Setup the user to run the operation (ugly hack because validate_context() will
1795         // fail as the email is not set by $this->setAdminUser()).
1796         $this->setAdminUser();
1797         $USER->email = 'emailtopass@example.com';
1799         // Import from course1 to course2.
1800         core_course_external::import_course($course1->id, $course2->id, 0);
1802         // Verify that now we have two modules in both courses.
1803         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1804         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1805         $this->assertCount(2, $course1cms);
1806         $this->assertCount(2, $course2cms);
1808         // Verify that the names transfered across correctly.
1809         foreach ($course2cms as $cm) {
1810             if ($cm->modname === 'page') {
1811                 $this->assertEquals($cm->name, $page->name);
1812             } else if ($cm->modname === 'forum') {
1813                 $this->assertEquals($cm->name, $forum->name);
1814             } else {
1815                 $this->fail('Unknown CM found.');
1816             }
1817         }
1818     }
1820     /**
1821      * Test import_course into an filled course
1822      */
1823     public function test_import_course_filled() {
1824         global $USER;
1826         $this->resetAfterTest(true);
1828         // Add forum and page to course1.
1829         $course1  = self::getDataGenerator()->create_course();
1830         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1831         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1833         // Add quiz to course 2.
1834         $course2  = self::getDataGenerator()->create_course();
1835         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1837         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1838         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1840         // Verify the state of the courses before we do the import.
1841         $this->assertCount(2, $course1cms);
1842         $this->assertCount(1, $course2cms);
1844         // Setup the user to run the operation (ugly hack because validate_context() will
1845         // fail as the email is not set by $this->setAdminUser()).
1846         $this->setAdminUser();
1847         $USER->email = 'emailtopass@example.com';
1849         // Import from course1 to course2 without deleting content.
1850         core_course_external::import_course($course1->id, $course2->id, 0);
1852         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1854         // Verify that now we have three modules in course2.
1855         $this->assertCount(3, $course2cms);
1857         // Verify that the names transfered across correctly.
1858         foreach ($course2cms as $cm) {
1859             if ($cm->modname === 'page') {
1860                 $this->assertEquals($cm->name, $page->name);
1861             } else if ($cm->modname === 'forum') {
1862                 $this->assertEquals($cm->name, $forum->name);
1863             } else if ($cm->modname === 'quiz') {
1864                 $this->assertEquals($cm->name, $quiz->name);
1865             } else {
1866                 $this->fail('Unknown CM found.');
1867             }
1868         }
1869     }
1871     /**
1872      * Test import_course with only blocks set to backup
1873      */
1874     public function test_import_course_blocksonly() {
1875         global $USER, $DB;
1877         $this->resetAfterTest(true);
1879         // Add forum and page to course1.
1880         $course1  = self::getDataGenerator()->create_course();
1881         $course1ctx = context_course::instance($course1->id);
1882         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1883         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1885         $course2  = self::getDataGenerator()->create_course();
1886         $course2ctx = context_course::instance($course2->id);
1887         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1888         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1890         // Setup the user to run the operation (ugly hack because validate_context() will
1891         // fail as the email is not set by $this->setAdminUser()).
1892         $this->setAdminUser();
1893         $USER->email = 'emailtopass@example.com';
1895         // Import from course1 to course2 without deleting content, but excluding
1896         // activities.
1897         $options = array(
1898             array('name' => 'activities', 'value' => 0),
1899             array('name' => 'blocks', 'value' => 1),
1900             array('name' => 'filters', 'value' => 0),
1901         );
1903         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1905         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1906         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1907         // Check that course modules haven't changed, but that blocks have.
1908         $this->assertEquals($initialcmcount, $newcmcount);
1909         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1910     }
1912     /**
1913      * Test import_course into an filled course, deleting content.
1914      */
1915     public function test_import_course_deletecontent() {
1916         global $USER;
1917         $this->resetAfterTest(true);
1919         // Add forum and page to course1.
1920         $course1  = self::getDataGenerator()->create_course();
1921         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1922         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1924         // Add quiz to course 2.
1925         $course2  = self::getDataGenerator()->create_course();
1926         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1928         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1929         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1931         // Verify the state of the courses before we do the import.
1932         $this->assertCount(2, $course1cms);
1933         $this->assertCount(1, $course2cms);
1935         // Setup the user to run the operation (ugly hack because validate_context() will
1936         // fail as the email is not set by $this->setAdminUser()).
1937         $this->setAdminUser();
1938         $USER->email = 'emailtopass@example.com';
1940         // Import from course1 to course2,  deleting content.
1941         core_course_external::import_course($course1->id, $course2->id, 1);
1943         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1945         // Verify that now we have two modules in course2.
1946         $this->assertCount(2, $course2cms);
1948         // Verify that the course only contains the imported modules.
1949         foreach ($course2cms as $cm) {
1950             if ($cm->modname === 'page') {
1951                 $this->assertEquals($cm->name, $page->name);
1952             } else if ($cm->modname === 'forum') {
1953                 $this->assertEquals($cm->name, $forum->name);
1954             } else {
1955                 $this->fail('Unknown CM found: '.$cm->name);
1956             }
1957         }
1958     }
1960     /**
1961      * Ensure import_course handles incorrect deletecontent option correctly.
1962      */
1963     public function test_import_course_invalid_deletecontent_option() {
1964         $this->resetAfterTest(true);
1966         $course1  = self::getDataGenerator()->create_course();
1967         $course2  = self::getDataGenerator()->create_course();
1969         $this->expectException('moodle_exception');
1970         $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
1971         // Import from course1 to course2, with invalid option
1972         core_course_external::import_course($course1->id, $course2->id, -1);;
1973     }
1975     /**
1976      * Test view_course function
1977      */
1978     public function test_view_course() {
1980         $this->resetAfterTest();
1982         // Course without sections.
1983         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1984         $this->setAdminUser();
1986         // Redirect events to the sink, so we can recover them later.
1987         $sink = $this->redirectEvents();
1989         $result = core_course_external::view_course($course->id, 1);
1990         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1991         $events = $sink->get_events();
1992         $event = reset($events);
1994         // Check the event details are correct.
1995         $this->assertInstanceOf('\core\event\course_viewed', $event);
1996         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1997         $this->assertEquals(1, $event->other['coursesectionnumber']);
1999         $result = core_course_external::view_course($course->id);
2000         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
2001         $events = $sink->get_events();
2002         $event = array_pop($events);
2003         $sink->close();
2005         // Check the event details are correct.
2006         $this->assertInstanceOf('\core\event\course_viewed', $event);
2007         $this->assertEquals(context_course::instance($course->id), $event->get_context());
2008         $this->assertEmpty($event->other);
2010     }
2012     /**
2013      * Test get_course_module
2014      */
2015     public function test_get_course_module() {
2016         global $DB;
2018         $this->resetAfterTest(true);
2020         $this->setAdminUser();
2021         $course = self::getDataGenerator()->create_course();
2022         $record = array(
2023             'course' => $course->id,
2024             'name' => 'First Assignment'
2025         );
2026         $options = array(
2027             'idnumber' => 'ABC',
2028             'visible' => 0
2029         );
2030         // Hidden activity.
2031         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
2033         $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
2035         // Insert a custom grade scale to be used by an outcome.
2036         $gradescale = new grade_scale();
2037         $gradescale->name        = 'gettcoursemodulescale';
2038         $gradescale->courseid    = $course->id;
2039         $gradescale->userid      = 0;
2040         $gradescale->scale       = $outcomescale;
2041         $gradescale->description = 'This scale is used to mark standard assignments.';
2042         $gradescale->insert();
2044         // Insert an outcome.
2045         $data = new stdClass();
2046         $data->courseid = $course->id;
2047         $data->fullname = 'Team work';
2048         $data->shortname = 'Team work';
2049         $data->scaleid = $gradescale->id;
2050         $outcome = new grade_outcome($data, false);
2051         $outcome->insert();
2053         $outcomegradeitem = new grade_item();
2054         $outcomegradeitem->itemname = $outcome->shortname;
2055         $outcomegradeitem->itemtype = 'mod';
2056         $outcomegradeitem->itemmodule = 'assign';
2057         $outcomegradeitem->iteminstance = $assign->id;
2058         $outcomegradeitem->outcomeid = $outcome->id;
2059         $outcomegradeitem->cmid = 0;
2060         $outcomegradeitem->courseid = $course->id;
2061         $outcomegradeitem->aggregationcoef = 0;
2062         $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
2063         $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
2064         $outcomegradeitem->scaleid = $outcome->scaleid;
2065         $outcomegradeitem->insert();
2067         $assignmentgradeitem = grade_item::fetch(
2068             array(
2069                 'itemtype' => 'mod',
2070                 'itemmodule' => 'assign',
2071                 'iteminstance' => $assign->id,
2072                 'itemnumber' => 0,
2073                 'courseid' => $course->id
2074             )
2075         );
2076         $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
2077         $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
2079         // Test admin user can see the complete hidden activity.
2080         $result = core_course_external::get_course_module($assign->cmid);
2081         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
2083         $this->assertCount(0, $result['warnings']);
2084         // Test we retrieve all the fields.
2085         $this->assertCount(28, $result['cm']);
2086         $this->assertEquals($record['name'], $result['cm']['name']);
2087         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
2088         $this->assertEquals(100, $result['cm']['grade']);
2089         $this->assertEquals(0.0, $result['cm']['gradepass']);
2090         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
2091         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
2092         $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
2094         $student = $this->getDataGenerator()->create_user();
2095         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2097         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
2098         $this->setUser($student);
2100         // The user shouldn't be able to see the activity.
2101         try {
2102             core_course_external::get_course_module($assign->cmid);
2103             $this->fail('Exception expected due to invalid permissions.');
2104         } catch (moodle_exception $e) {
2105             $this->assertEquals('requireloginerror', $e->errorcode);
2106         }
2108         // Make module visible.
2109         set_coursemodule_visible($assign->cmid, 1);
2111         // Test student user.
2112         $result = core_course_external::get_course_module($assign->cmid);
2113         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
2115         $this->assertCount(0, $result['warnings']);
2116         // Test we retrieve only the few files we can see.
2117         $this->assertCount(11, $result['cm']);
2118         $this->assertEquals($assign->cmid, $result['cm']['id']);
2119         $this->assertEquals($course->id, $result['cm']['course']);
2120         $this->assertEquals('assign', $result['cm']['modname']);
2121         $this->assertEquals($assign->id, $result['cm']['instance']);
2123     }
2125     /**
2126      * Test get_course_module_by_instance
2127      */
2128     public function test_get_course_module_by_instance() {
2129         global $DB;
2131         $this->resetAfterTest(true);
2133         $this->setAdminUser();
2134         $course = self::getDataGenerator()->create_course();
2135         $record = array(
2136             'course' => $course->id,
2137             'name' => 'First quiz',
2138             'grade' => 90.00
2139         );
2140         $options = array(
2141             'idnumber' => 'ABC',
2142             'visible' => 0
2143         );
2144         // Hidden activity.
2145         $quiz = self::getDataGenerator()->create_module('quiz', $record, $options);
2147         // Test admin user can see the complete hidden activity.
2148         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2149         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
2151         $this->assertCount(0, $result['warnings']);
2152         // Test we retrieve all the fields.
2153         $this->assertCount(26, $result['cm']);
2154         $this->assertEquals($record['name'], $result['cm']['name']);
2155         $this->assertEquals($record['grade'], $result['cm']['grade']);
2156         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
2158         $student = $this->getDataGenerator()->create_user();
2159         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2161         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
2162         $this->setUser($student);
2164         // The user shouldn't be able to see the activity.
2165         try {
2166             core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2167             $this->fail('Exception expected due to invalid permissions.');
2168         } catch (moodle_exception $e) {
2169             $this->assertEquals('requireloginerror', $e->errorcode);
2170         }
2172         // Make module visible.
2173         set_coursemodule_visible($quiz->cmid, 1);
2175         // Test student user.
2176         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2177         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
2179         $this->assertCount(0, $result['warnings']);
2180         // Test we retrieve only the few files we can see.
2181         $this->assertCount(11, $result['cm']);
2182         $this->assertEquals($quiz->cmid, $result['cm']['id']);
2183         $this->assertEquals($course->id, $result['cm']['course']);
2184         $this->assertEquals('quiz', $result['cm']['modname']);
2185         $this->assertEquals($quiz->id, $result['cm']['instance']);
2187         // Try with an invalid module name.
2188         try {
2189             core_course_external::get_course_module_by_instance('abc', $quiz->id);
2190             $this->fail('Exception expected due to invalid module name.');
2191         } catch (dml_read_exception $e) {
2192             $this->assertEquals('dmlreadexception', $e->errorcode);
2193         }
2195     }
2197     /**
2198      * Test get_activities_overview
2199      */
2200     public function test_get_activities_overview() {
2201         global $USER;
2203         $this->resetAfterTest();
2204         $course1 = self::getDataGenerator()->create_course();
2205         $course2 = self::getDataGenerator()->create_course();
2207         // Create a viewer user.
2208         $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
2209         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2210         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2212         // Create two forums - one in each course.
2213         $record = new stdClass();
2214         $record->course = $course1->id;
2215         $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
2216         $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
2218         $this->setAdminUser();
2219         // A standard post in the forum.
2220         $record = new stdClass();
2221         $record->course = $course1->id;
2222         $record->userid = $USER->id;
2223         $record->forum = $forum1->id;
2224         $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
2226         $this->setUser($viewer->id);
2227         $courses = array($course1->id , $course2->id);
2229         $result = core_course_external::get_activities_overview($courses);
2230         $this->assertDebuggingCalledCount(8);
2231         $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
2233         // There should be one entry for course1, and no others.
2234         $this->assertCount(1, $result['courses']);
2235         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2236         // Check expected overview data for the module.
2237         $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
2238         $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
2239     }
2241     /**
2242      * Test get_user_navigation_options
2243      */
2244     public function test_get_user_navigation_options() {
2245         global $USER;
2247         $this->resetAfterTest();
2248         $course1 = self::getDataGenerator()->create_course();
2249         $course2 = self::getDataGenerator()->create_course();
2251         // Create a viewer user.
2252         $viewer = self::getDataGenerator()->create_user();
2253         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2254         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2256         $this->setUser($viewer->id);
2257         $courses = array($course1->id , $course2->id, SITEID);
2259         $result = core_course_external::get_user_navigation_options($courses);
2260         $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
2262         $this->assertCount(0, $result['warnings']);
2263         $this->assertCount(3, $result['courses']);
2265         foreach ($result['courses'] as $course) {
2266             $navoptions = new stdClass;
2267             foreach ($course['options'] as $option) {
2268                 $navoptions->{$option['name']} = $option['available'];
2269             }
2270             $this->assertCount(9, $course['options']);
2271             if ($course['id'] == SITEID) {
2272                 $this->assertTrue($navoptions->blogs);
2273                 $this->assertFalse($navoptions->notes);
2274                 $this->assertFalse($navoptions->participants);
2275                 $this->assertTrue($navoptions->badges);
2276                 $this->assertTrue($navoptions->tags);
2277                 $this->assertFalse($navoptions->grades);
2278                 $this->assertFalse($navoptions->search);
2279                 $this->assertTrue($navoptions->calendar);
2280                 $this->assertTrue($navoptions->competencies);
2281             } else {
2282                 $this->assertTrue($navoptions->blogs);
2283                 $this->assertFalse($navoptions->notes);
2284                 $this->assertTrue($navoptions->participants);
2285                 $this->assertTrue($navoptions->badges);
2286                 $this->assertFalse($navoptions->tags);
2287                 $this->assertTrue($navoptions->grades);
2288                 $this->assertFalse($navoptions->search);
2289                 $this->assertFalse($navoptions->calendar);
2290                 $this->assertTrue($navoptions->competencies);
2291             }
2292         }
2293     }
2295     /**
2296      * Test get_user_administration_options
2297      */
2298     public function test_get_user_administration_options() {
2299         global $USER;
2301         $this->resetAfterTest();
2302         $course1 = self::getDataGenerator()->create_course();
2303         $course2 = self::getDataGenerator()->create_course();
2305         // Create a viewer user.
2306         $viewer = self::getDataGenerator()->create_user();
2307         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2308         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2310         $this->setUser($viewer->id);
2311         $courses = array($course1->id , $course2->id, SITEID);
2313         $result = core_course_external::get_user_administration_options($courses);
2314         $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
2316         $this->assertCount(0, $result['warnings']);
2317         $this->assertCount(3, $result['courses']);
2319         foreach ($result['courses'] as $course) {
2320             $adminoptions = new stdClass;
2321             foreach ($course['options'] as $option) {
2322                 $adminoptions->{$option['name']} = $option['available'];
2323             }
2324             if ($course['id'] == SITEID) {
2325                 $this->assertCount(16, $course['options']);
2326                 $this->assertFalse($adminoptions->update);
2327                 $this->assertFalse($adminoptions->filters);
2328                 $this->assertFalse($adminoptions->reports);
2329                 $this->assertFalse($adminoptions->backup);
2330                 $this->assertFalse($adminoptions->restore);
2331                 $this->assertFalse($adminoptions->files);
2332                 $this->assertFalse(!isset($adminoptions->tags));
2333                 $this->assertFalse($adminoptions->gradebook);
2334                 $this->assertFalse($adminoptions->outcomes);
2335                 $this->assertFalse($adminoptions->badges);
2336                 $this->assertFalse($adminoptions->import);
2337                 $this->assertFalse($adminoptions->publish);
2338                 $this->assertFalse($adminoptions->reset);
2339                 $this->assertFalse($adminoptions->roles);
2340                 $this->assertFalse($adminoptions->editcompletion);
2341             } else {
2342                 $this->assertCount(15, $course['options']);
2343                 $this->assertFalse($adminoptions->update);
2344                 $this->assertFalse($adminoptions->filters);
2345                 $this->assertFalse($adminoptions->reports);
2346                 $this->assertFalse($adminoptions->backup);
2347                 $this->assertFalse($adminoptions->restore);
2348                 $this->assertFalse($adminoptions->files);
2349                 $this->assertFalse($adminoptions->tags);
2350                 $this->assertFalse($adminoptions->gradebook);
2351                 $this->assertFalse($adminoptions->outcomes);
2352                 $this->assertTrue($adminoptions->badges);
2353                 $this->assertFalse($adminoptions->import);
2354                 $this->assertFalse($adminoptions->publish);
2355                 $this->assertFalse($adminoptions->reset);
2356                 $this->assertFalse($adminoptions->roles);
2357                 $this->assertFalse($adminoptions->editcompletion);
2358             }
2359         }
2360     }
2362     /**
2363      * Test get_courses_by_fields
2364      */
2365     public function test_get_courses_by_field() {
2366         global $DB;
2367         $this->resetAfterTest(true);
2369         $category1 = self::getDataGenerator()->create_category(array('name' => 'Cat 1'));
2370         $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
2371         $course1 = self::getDataGenerator()->create_course(
2372             array('category' => $category1->id, 'shortname' => 'c1', 'format' => 'topics'));
2373         $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
2375         $student1 = self::getDataGenerator()->create_user();
2376         $user1 = self::getDataGenerator()->create_user();
2377         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2378         self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
2379         self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
2381         self::setAdminUser();
2382         // As admins, we should be able to retrieve everything.
2383         $result = core_course_external::get_courses_by_field();
2384         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2385         $this->assertCount(3, $result['courses']);
2386         // Expect to receive all the fields.
2387         $this->assertCount(37, $result['courses'][0]);
2388         $this->assertCount(38, $result['courses'][1]);  // One more field because is not the site course.
2389         $this->assertCount(38, $result['courses'][2]);  // One more field because is not the site course.
2391         $result = core_course_external::get_courses_by_field('id', $course1->id);
2392         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2393         $this->assertCount(1, $result['courses']);
2394         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2395         // Expect to receive all the fields.
2396         $this->assertCount(38, $result['courses'][0]);
2397         // Check default values for course format topics.
2398         $this->assertCount(2, $result['courses'][0]['courseformatoptions']);
2399         foreach ($result['courses'][0]['courseformatoptions'] as $option) {
2400             if ($option['name'] == 'hiddensections') {
2401                 $this->assertEquals(0, $option['value']);
2402             } else {
2403                 $this->assertEquals('coursedisplay', $option['name']);
2404                 $this->assertEquals(0, $option['value']);
2405             }
2406         }
2408         $result = core_course_external::get_courses_by_field('id', $course2->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($course2->id, $result['courses'][0]['id']);
2413         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2414         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2415         $this->assertCount(2, $result['courses']);
2417         // Check default filters.
2418         $this->assertCount(3, $result['courses'][0]['filters']);
2419         $this->assertCount(3, $result['courses'][1]['filters']);
2421         $result = core_course_external::get_courses_by_field('category', $category1->id);
2422         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2423         $this->assertCount(1, $result['courses']);
2424         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2425         $this->assertEquals('Cat 1', $result['courses'][0]['categoryname']);
2427         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2428         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2429         $this->assertCount(1, $result['courses']);
2430         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2432         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2433         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2434         $this->assertCount(1, $result['courses']);
2435         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2437         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2438         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2439         $this->assertCount(0, $result['courses']);
2441         // Change filter value.
2442         filter_set_local_state('mediaplugin', context_course::instance($course1->id)->id, TEXTFILTER_OFF);
2444         self::setUser($student1);
2445         // All visible courses  (including front page) for normal student.
2446         $result = core_course_external::get_courses_by_field();
2447         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2448         $this->assertCount(2, $result['courses']);
2449         $this->assertCount(30, $result['courses'][0]);
2450         $this->assertCount(31, $result['courses'][1]);  // One field more (course format options), not present in site course.
2452         $result = core_course_external::get_courses_by_field('id', $course1->id);
2453         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2454         $this->assertCount(1, $result['courses']);
2455         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2456         // Expect to receive all the files that a student can see.
2457         $this->assertCount(31, $result['courses'][0]);
2459         // Check default filters.
2460         $filters = $result['courses'][0]['filters'];
2461         $this->assertCount(3, $filters);
2462         $found = false;
2463         foreach ($filters as $filter) {
2464             if ($filter['filter'] == 'mediaplugin' and $filter['localstate'] == TEXTFILTER_OFF) {
2465                 $found = true;
2466             }
2467         }
2468         $this->assertTrue($found);
2470         // Course 2 is not visible.
2471         $result = core_course_external::get_courses_by_field('id', $course2->id);
2472         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2473         $this->assertCount(0, $result['courses']);
2475         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2476         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2477         $this->assertCount(1, $result['courses']);
2479         $result = core_course_external::get_courses_by_field('category', $category1->id);
2480         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2481         $this->assertCount(1, $result['courses']);
2482         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2484         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2485         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2486         $this->assertCount(1, $result['courses']);
2487         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2489         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2490         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2491         $this->assertCount(0, $result['courses']);
2493         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2494         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2495         $this->assertCount(0, $result['courses']);
2497         self::setUser($user1);
2498         // All visible courses (including front page) for authenticated user.
2499         $result = core_course_external::get_courses_by_field();
2500         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2501         $this->assertCount(2, $result['courses']);
2502         $this->assertCount(30, $result['courses'][0]);  // Site course.
2503         $this->assertCount(13, $result['courses'][1]);  // Only public information, not enrolled.
2505         $result = core_course_external::get_courses_by_field('id', $course1->id);
2506         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2507         $this->assertCount(1, $result['courses']);
2508         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2509         // Expect to receive all the files that a authenticated can see.
2510         $this->assertCount(13, $result['courses'][0]);
2512         // Course 2 is not visible.
2513         $result = core_course_external::get_courses_by_field('id', $course2->id);
2514         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2515         $this->assertCount(0, $result['courses']);
2517         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2518         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2519         $this->assertCount(1, $result['courses']);
2521         $result = core_course_external::get_courses_by_field('category', $category1->id);
2522         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2523         $this->assertCount(1, $result['courses']);
2524         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2526         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2527         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2528         $this->assertCount(1, $result['courses']);
2529         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2531         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2532         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2533         $this->assertCount(0, $result['courses']);
2535         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2536         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2537         $this->assertCount(0, $result['courses']);
2538     }
2540     public function test_get_courses_by_field_invalid_field() {
2541         $this->expectException('invalid_parameter_exception');
2542         $result = core_course_external::get_courses_by_field('zyx', 'x');
2543     }
2545     public function test_get_courses_by_field_invalid_courses() {
2546         $result = core_course_external::get_courses_by_field('id', '-1');
2547         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2548         $this->assertCount(0, $result['courses']);
2549     }
2551     /**
2552      * Test get_courses_by_field_invalid_theme_and_lang
2553      */
2554     public function test_get_courses_by_field_invalid_theme_and_lang() {
2555         $this->resetAfterTest(true);
2556         $this->setAdminUser();
2558         $course = self::getDataGenerator()->create_course(array('theme' => 'kkt', 'lang' => 'kkl'));
2559         $result = core_course_external::get_courses_by_field('id', $course->id);
2560         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2561         $this->assertEmpty($result['courses']['0']['theme']);
2562         $this->assertEmpty($result['courses']['0']['lang']);
2563     }
2566     public function test_check_updates() {
2567         global $DB;
2568         $this->resetAfterTest(true);
2569         $this->setAdminUser();
2571         // Create different types of activities.
2572         $course  = self::getDataGenerator()->create_course();
2573         $tocreate = array('assign', 'book', 'choice', 'folder', 'forum', 'glossary', 'imscp', 'label', 'lti', 'page', 'quiz',
2574                             'resource', 'scorm', 'survey', 'url', 'wiki');
2576         $modules = array();
2577         foreach ($tocreate as $modname) {
2578             $modules[$modname]['instance'] = $this->getDataGenerator()->create_module($modname, array('course' => $course->id));
2579             $modules[$modname]['cm'] = get_coursemodule_from_id(false, $modules[$modname]['instance']->cmid);
2580             $modules[$modname]['context'] = context_module::instance($modules[$modname]['instance']->cmid);
2581         }
2583         $student = self::getDataGenerator()->create_user();
2584         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2585         self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
2586         $this->setUser($student);
2588         $since = time();
2589         $this->waitForSecond();
2590         $params = array();
2591         foreach ($modules as $modname => $data) {
2592             $params[$data['cm']->id] = array(
2593                 'contextlevel' => 'module',
2594                 'id' => $data['cm']->id,
2595                 'since' => $since
2596             );
2597         }
2599         // Check there is nothing updated because modules are fresh new.
2600         $result = core_course_external::check_updates($course->id, $params);
2601         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2602         $this->assertCount(0, $result['instances']);
2603         $this->assertCount(0, $result['warnings']);
2605         // Test with get_updates_since the same data.
2606         $result = core_course_external::get_updates_since($course->id, $since);
2607         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2608         $this->assertCount(0, $result['instances']);
2609         $this->assertCount(0, $result['warnings']);
2611         // Update a module after a second.
2612         $this->waitForSecond();
2613         set_coursemodule_name($modules['forum']['cm']->id, 'New forum name');
2615         $found = false;
2616         $result = core_course_external::check_updates($course->id, $params);
2617         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2618         $this->assertCount(1, $result['instances']);
2619         $this->assertCount(0, $result['warnings']);
2620         foreach ($result['instances'] as $module) {
2621             foreach ($module['updates'] as $update) {
2622                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2623                     $found = true;
2624                 }
2625             }
2626         }
2627         $this->assertTrue($found);
2629         // Test with get_updates_since the same data.
2630         $result = core_course_external::get_updates_since($course->id, $since);
2631         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2632         $this->assertCount(1, $result['instances']);
2633         $this->assertCount(0, $result['warnings']);
2634         $found = false;
2635         $this->assertCount(1, $result['instances']);
2636         $this->assertCount(0, $result['warnings']);
2637         foreach ($result['instances'] as $module) {
2638             foreach ($module['updates'] as $update) {
2639                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2640                     $found = true;
2641                 }
2642             }
2643         }
2644         $this->assertTrue($found);
2646         // Do not retrieve the configuration field.
2647         $filter = array('files');
2648         $found = false;
2649         $result = core_course_external::check_updates($course->id, $params, $filter);
2650         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2651         $this->assertCount(0, $result['instances']);
2652         $this->assertCount(0, $result['warnings']);
2653         $this->assertFalse($found);
2655         // Add invalid cmid.
2656         $params[] = array(
2657             'contextlevel' => 'module',
2658             'id' => -2,
2659             'since' => $since
2660         );
2661         $result = core_course_external::check_updates($course->id, $params);
2662         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2663         $this->assertCount(1, $result['warnings']);
2664         $this->assertEquals(-2, $result['warnings'][0]['itemid']);
2665     }
2667     /**
2668      * Test cases for the get_enrolled_courses_by_timeline_classification test.
2669      */
2670     public function get_get_enrolled_courses_by_timeline_classification_test_cases() {
2671         $now = time();
2672         $day = 86400;
2674         $coursedata = [
2675             [
2676                 'shortname' => 'apast',
2677                 'startdate' => $now - ($day * 2),
2678                 'enddate' => $now - $day
2679             ],
2680             [
2681                 'shortname' => 'bpast',
2682                 'startdate' => $now - ($day * 2),
2683                 'enddate' => $now - $day
2684             ],
2685             [
2686                 'shortname' => 'cpast',
2687                 'startdate' => $now - ($day * 2),
2688                 'enddate' => $now - $day
2689             ],
2690             [
2691                 'shortname' => 'dpast',
2692                 'startdate' => $now - ($day * 2),
2693                 'enddate' => $now - $day
2694             ],
2695             [
2696                 'shortname' => 'epast',
2697                 'startdate' => $now - ($day * 2),
2698                 'enddate' => $now - $day
2699             ],
2700             [
2701                 'shortname' => 'ainprogress',
2702                 'startdate' => $now - $day,
2703                 'enddate' => $now + $day
2704             ],
2705             [
2706                 'shortname' => 'binprogress',
2707                 'startdate' => $now - $day,
2708                 'enddate' => $now + $day
2709             ],
2710             [
2711                 'shortname' => 'cinprogress',
2712                 'startdate' => $now - $day,
2713                 'enddate' => $now + $day
2714             ],
2715             [
2716                 'shortname' => 'dinprogress',
2717                 'startdate' => $now - $day,
2718                 'enddate' => $now + $day
2719             ],
2720             [
2721                 'shortname' => 'einprogress',
2722                 'startdate' => $now - $day,
2723                 'enddate' => $now + $day
2724             ],
2725             [
2726                 'shortname' => 'afuture',
2727                 'startdate' => $now + $day
2728             ],
2729             [
2730                 'shortname' => 'bfuture',
2731                 'startdate' => $now + $day
2732             ],
2733             [
2734                 'shortname' => 'cfuture',
2735                 'startdate' => $now + $day
2736             ],
2737             [
2738                 'shortname' => 'dfuture',
2739                 'startdate' => $now + $day
2740             ],
2741             [
2742                 'shortname' => 'efuture',
2743                 'startdate' => $now + $day
2744             ]
2745         ];
2747         // Raw enrolled courses result set should be returned in this order:
2748         // afuture, ainprogress, apast, bfuture, binprogress, bpast, cfuture, cinprogress, cpast,
2749         // dfuture, dinprogress, dpast, efuture, einprogress, epast
2750         //
2751         // By classification the offset values for each record should be:
2752         // COURSE_TIMELINE_FUTURE
2753         // 0 (afuture), 3 (bfuture), 6 (cfuture), 9 (dfuture), 12 (efuture)
2754         // COURSE_TIMELINE_INPROGRESS
2755         // 1 (ainprogress), 4 (binprogress), 7 (cinprogress), 10 (dinprogress), 13 (einprogress)
2756         // COURSE_TIMELINE_PAST
2757         // 2 (apast), 5 (bpast), 8 (cpast), 11 (dpast), 14 (epast).
2758         //
2759         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2760         // filtering is done.
2761         // E.g. In our example if an offset of 2 is given then it would mean the first
2762         // two courses (afuture, ainprogress) are ignored.
2763         return [
2764             'empty set' => [
2765                 'coursedata' => [],
2766                 'classification' => 'future',
2767                 'limit' => 2,
2768                 'offset' => 0,
2769                 'expectedcourses' => [],
2770                 'expectednextoffset' => 0
2771             ],
2772             // COURSE_TIMELINE_FUTURE.
2773             'future not limit no offset' => [
2774                 'coursedata' => $coursedata,
2775                 'classification' => 'future',
2776                 'limit' => 0,
2777                 'offset' => 0,
2778                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2779                 'expectednextoffset' => 15
2780             ],
2781             'future no offset' => [
2782                 'coursedata' => $coursedata,
2783                 'classification' => 'future',
2784                 'limit' => 2,
2785                 'offset' => 0,
2786                 'expectedcourses' => ['afuture', 'bfuture'],
2787                 'expectednextoffset' => 4
2788             ],
2789             'future offset' => [
2790                 'coursedata' => $coursedata,
2791                 'classification' => 'future',
2792                 'limit' => 2,
2793                 'offset' => 2,
2794                 'expectedcourses' => ['bfuture', 'cfuture'],
2795                 'expectednextoffset' => 7
2796             ],
2797             'future exact limit' => [
2798                 'coursedata' => $coursedata,
2799                 'classification' => 'future',
2800                 'limit' => 5,
2801                 'offset' => 0,
2802                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2803                 'expectednextoffset' => 13
2804             ],
2805             'future limit less results' => [
2806                 'coursedata' => $coursedata,
2807                 'classification' => 'future',
2808                 'limit' => 10,
2809                 'offset' => 0,
2810                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2811                 'expectednextoffset' => 15
2812             ],
2813             'future limit less results with offset' => [
2814                 'coursedata' => $coursedata,
2815                 'classification' => 'future',
2816                 'limit' => 10,
2817                 'offset' => 5,
2818                 'expectedcourses' => ['cfuture', 'dfuture', 'efuture'],
2819                 'expectednextoffset' => 15
2820             ],
2821             'all no limit or offset' => [
2822                 'coursedata' => $coursedata,
2823                 'classification' => 'all',
2824                 'limit' => 0,
2825                 'offset' => 0,
2826                 'expectedcourses' => [
2827                     'afuture',
2828                     'ainprogress',
2829                     'apast',
2830                     'bfuture',
2831                     'binprogress',
2832                     'bpast',
2833                     'cfuture',
2834                     'cinprogress',
2835                     'cpast',
2836                     'dfuture',
2837                     'dinprogress',
2838                     'dpast',
2839                     'efuture',
2840                     'einprogress',
2841                     'epast'
2842                 ],
2843                 'expectednextoffset' => 15
2844             ],
2845             'all limit no offset' => [
2846                 'coursedata' => $coursedata,
2847                 'classification' => 'all',
2848                 'limit' => 5,
2849                 'offset' => 0,
2850                 'expectedcourses' => [
2851                     'afuture',
2852                     'ainprogress',
2853                     'apast',
2854                     'bfuture',
2855                     'binprogress'
2856                 ],
2857                 'expectednextoffset' => 5
2858             ],
2859             'all limit and offset' => [
2860                 'coursedata' => $coursedata,
2861                 'classification' => 'all',
2862                 'limit' => 5,
2863                 'offset' => 5,
2864                 'expectedcourses' => [
2865                     'bpast',
2866                     'cfuture',
2867                     'cinprogress',
2868                     'cpast',
2869                     'dfuture'
2870                 ],
2871                 'expectednextoffset' => 10
2872             ],
2873             'all offset past result set' => [
2874                 'coursedata' => $coursedata,
2875                 'classification' => 'all',
2876                 'limit' => 5,
2877                 'offset' => 50,
2878                 'expectedcourses' => [],
2879                 'expectednextoffset' => 50
2880             ],
2881         ];
2882     }
2884     /**
2885      * Test the get_enrolled_courses_by_timeline_classification function.
2886      *
2887      * @dataProvider get_get_enrolled_courses_by_timeline_classification_test_cases()
2888      * @param array $coursedata Courses to create
2889      * @param string $classification Timeline classification
2890      * @param int $limit Maximum number of results
2891      * @param int $offset Offset the unfiltered courses result set by this amount
2892      * @param array $expectedcourses Expected courses in result
2893      * @param int $expectednextoffset Expected next offset value in result
2894      */
2895     public function test_get_enrolled_courses_by_timeline_classification(
2896         $coursedata,
2897         $classification,
2898         $limit,
2899         $offset,
2900         $expectedcourses,
2901         $expectednextoffset
2902     ) {
2903         $this->resetAfterTest();
2904         $generator = $this->getDataGenerator();
2906         $courses = array_map(function($coursedata) use ($generator) {
2907             return $generator->create_course($coursedata);
2908         }, $coursedata);
2910         $student = $generator->create_user();
2912         foreach ($courses as $course) {
2913             $generator->enrol_user($student->id, $course->id, 'student');
2914         }
2916         $this->setUser($student);
2918         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2919         // filtering is done.
2920         // E.g. In our example if an offset of 2 is given then it would mean the first
2921         // two courses (afuture, ainprogress) are ignored.
2922         $result = core_course_external::get_enrolled_courses_by_timeline_classification(
2923             $classification,
2924             $limit,
2925             $offset,
2926             'shortname ASC'
2927         );
2928         $result = external_api::clean_returnvalue(
2929             core_course_external::get_enrolled_courses_by_timeline_classification_returns(),
2930             $result
2931         );
2933         $actual = array_map(function($course) {
2934             return $course['shortname'];
2935         }, $result['courses']);
2937         $this->assertEquals($expectedcourses, $actual);
2938         $this->assertEquals($expectednextoffset, $result['nextoffset']);
2939     }
2941     /**
2942      * Test the get_recent_courses function.
2943      */
2944     public function test_get_recent_courses() {
2945         global $USER, $DB;
2947         $this->resetAfterTest();
2948         $generator = $this->getDataGenerator();
2950         set_config('hiddenuserfields', 'lastaccess');
2952         $courses = array();
2953         for ($i = 1; $i < 12; $i++) {
2954             $courses[]  = $generator->create_course();
2955         };
2957         $student = $generator->create_user();
2958         $teacher = $generator->create_user();
2960         foreach ($courses as $course) {
2961             $generator->enrol_user($student->id, $course->id, 'student');
2962         }
2964         $generator->enrol_user($teacher->id, $courses[0]->id, 'teacher');
2966         $this->setUser($student);
2968         $result = core_course_external::get_recent_courses($USER->id);
2970         // No course accessed.
2971         $this->assertCount(0, $result);
2973         foreach ($courses as $course) {
2974             core_course_external::view_course($course->id);
2975         }
2977         // Every course accessed.
2978         $result = core_course_external::get_recent_courses($USER->id);
2979         $this->assertCount( 11, $result);
2981         // Every course accessed, result limited to 10 courses.
2982         $result = core_course_external::get_recent_courses($USER->id, 10);
2983         $this->assertCount(10, $result);
2985         $guestcourse = $generator->create_course(
2986                 (object)array('shortname' => 'guestcourse',
2987                 'enrol_guest_status_0' => ENROL_INSTANCE_ENABLED,
2988                 'enrol_guest_password_0' => ''));
2989         core_course_external::view_course($guestcourse->id);
2991         // Every course accessed, even the not enrolled one.
2992         $result = core_course_external::get_recent_courses($USER->id);
2993         $this->assertCount(12, $result);
2995         // Offset 5, return 7 out of 12.
2996         $result = core_course_external::get_recent_courses($USER->id, 0, 5);
2997         $this->assertCount(7, $result);
2999         // Offset 5 and limit 3, return 3 out of 12.
3000         $result = core_course_external::get_recent_courses($USER->id, 3, 5);
3001         $this->assertCount(3, $result);
3003         // Sorted by course id ASC.
3004         $result = core_course_external::get_recent_courses($USER->id, 0, 0, 'id ASC');
3005         $this->assertEquals($courses[0]->id, array_shift($result)->id);
3007         // Sorted by course id DESC.
3008         $result = core_course_external::get_recent_courses($USER->id, 0, 0, 'id DESC');
3009         $this->assertEquals($guestcourse->id, array_shift($result)->id);
3011         // If last access is hidden, only get the courses where has viewhiddenuserfields capability.
3012         $this->setUser($teacher);
3013         $teacherroleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher'));
3014         $usercontext = context_user::instance($student->id);
3015         $this->assignUserCapability('moodle/user:viewdetails', $usercontext, $teacherroleid);
3017         // Sorted by course id DESC.
3018         $result = core_course_external::get_recent_courses($student->id);
3019         $this->assertCount(1, $result);
3020         $this->assertEquals($courses[0]->id, array_shift($result)->id);
3021     }