Merge branch 'MDL-63337-master' of git://github.com/bmbrands/moodle
[moodle.git] / course / tests / externallib_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * External course functions unit tests
19  *
20  * @package    core_course
21  * @category   external
22  * @copyright  2012 Jerome Mouneyrac
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
32 /**
33  * External course functions unit tests
34  *
35  * @package    core_course
36  * @category   external
37  * @copyright  2012 Jerome Mouneyrac
38  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  */
40 class core_course_externallib_testcase extends externallib_advanced_testcase {
42     /**
43      * Tests set up
44      */
45     protected function setUp() {
46         global $CFG;
47         require_once($CFG->dirroot . '/course/externallib.php');
48     }
50     /**
51      * Test create_categories
52      */
53     public function test_create_categories() {
55         global $DB;
57         $this->resetAfterTest(true);
59         // Set the required capabilities by the external function
60         $contextid = context_system::instance()->id;
61         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
63         // Create base categories.
64         $category1 = new stdClass();
65         $category1->name = 'Root Test Category 1';
66         $category2 = new stdClass();
67         $category2->name = 'Root Test Category 2';
68         $category2->idnumber = 'rootcattest2';
69         $category2->desc = 'Description for root test category 1';
70         $category2->theme = 'bootstrapbase';
71         $categories = array(
72             array('name' => $category1->name, 'parent' => 0),
73             array('name' => $category2->name, 'parent' => 0, 'idnumber' => $category2->idnumber,
74                 'description' => $category2->desc, 'theme' => $category2->theme)
75         );
77         $createdcats = core_course_external::create_categories($categories);
79         // We need to execute the return values cleaning process to simulate the web service server.
80         $createdcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdcats);
82         // Initially confirm that base data was inserted correctly.
83         $this->assertEquals($category1->name, $createdcats[0]['name']);
84         $this->assertEquals($category2->name, $createdcats[1]['name']);
86         // Save the ids.
87         $category1->id = $createdcats[0]['id'];
88         $category2->id = $createdcats[1]['id'];
90         // Create on sub category.
91         $category3 = new stdClass();
92         $category3->name = 'Sub Root Test Category 3';
93         $subcategories = array(
94             array('name' => $category3->name, 'parent' => $category1->id)
95         );
97         $createdsubcats = core_course_external::create_categories($subcategories);
99         // We need to execute the return values cleaning process to simulate the web service server.
100         $createdsubcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdsubcats);
102         // Confirm that sub categories were inserted correctly.
103         $this->assertEquals($category3->name, $createdsubcats[0]['name']);
105         // Save the ids.
106         $category3->id = $createdsubcats[0]['id'];
108         // Calling the ws function should provide a new sortorder to give category1,
109         // category2, category3. New course categories are ordered by id not name.
110         $category1 = $DB->get_record('course_categories', array('id' => $category1->id));
111         $category2 = $DB->get_record('course_categories', array('id' => $category2->id));
112         $category3 = $DB->get_record('course_categories', array('id' => $category3->id));
114         // sortorder sequence (and sortorder) must be:
115         // category 1
116         //   category 3
117         // category 2
118         $this->assertGreaterThan($category1->sortorder, $category3->sortorder);
119         $this->assertGreaterThan($category3->sortorder, $category2->sortorder);
121         // Call without required capability
122         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
123         $this->expectException('required_capability_exception');
124         $createdsubcats = core_course_external::create_categories($subcategories);
126     }
128     /**
129      * Test delete categories
130      */
131     public function test_delete_categories() {
132         global $DB;
134         $this->resetAfterTest(true);
136         // Set the required capabilities by the external function
137         $contextid = context_system::instance()->id;
138         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
140         $category1  = self::getDataGenerator()->create_category();
141         $category2  = self::getDataGenerator()->create_category(
142                 array('parent' => $category1->id));
143         $category3  = self::getDataGenerator()->create_category();
144         $category4  = self::getDataGenerator()->create_category(
145                 array('parent' => $category3->id));
146         $category5  = self::getDataGenerator()->create_category(
147                 array('parent' => $category4->id));
149         //delete category 1 and 2 + delete category 4, category 5 moved under category 3
150         core_course_external::delete_categories(array(
151             array('id' => $category1->id, 'recursive' => 1),
152             array('id' => $category4->id)
153         ));
155         //check $category 1 and 2 are deleted
156         $notdeletedcount = $DB->count_records_select('course_categories',
157             'id IN ( ' . $category1->id . ',' . $category2->id . ',' . $category4->id . ')');
158         $this->assertEquals(0, $notdeletedcount);
160         //check that $category5 as $category3 for parent
161         $dbcategory5 = $DB->get_record('course_categories', array('id' => $category5->id));
162         $this->assertEquals($dbcategory5->path, $category3->path . '/' . $category5->id);
164          // Call without required capability
165         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
166         $this->expectException('required_capability_exception');
167         $createdsubcats = core_course_external::delete_categories(
168                 array(array('id' => $category3->id)));
169     }
171     /**
172      * Test get categories
173      */
174     public function test_get_categories() {
175         global $DB;
177         $this->resetAfterTest(true);
179         $generatedcats = array();
180         $category1data['idnumber'] = 'idnumbercat1';
181         $category1data['name'] = 'Category 1 for PHPunit test';
182         $category1data['description'] = 'Category 1 description';
183         $category1data['descriptionformat'] = FORMAT_MOODLE;
184         $category1  = self::getDataGenerator()->create_category($category1data);
185         $generatedcats[$category1->id] = $category1;
186         $category2  = self::getDataGenerator()->create_category(
187                 array('parent' => $category1->id));
188         $generatedcats[$category2->id] = $category2;
189         $category6  = self::getDataGenerator()->create_category(
190                 array('parent' => $category1->id, 'visible' => 0));
191         $generatedcats[$category6->id] = $category6;
192         $category3  = self::getDataGenerator()->create_category();
193         $generatedcats[$category3->id] = $category3;
194         $category4  = self::getDataGenerator()->create_category(
195                 array('parent' => $category3->id));
196         $generatedcats[$category4->id] = $category4;
197         $category5  = self::getDataGenerator()->create_category(
198                 array('parent' => $category4->id));
199         $generatedcats[$category5->id] = $category5;
201         // Set the required capabilities by the external function.
202         $context = context_system::instance();
203         $roleid = $this->assignUserCapability('moodle/category:manage', $context->id);
204         $this->assignUserCapability('moodle/category:viewhiddencategories', $context->id, $roleid);
206         // Retrieve category1 + sub-categories except not visible ones
207         $categories = core_course_external::get_categories(array(
208             array('key' => 'id', 'value' => $category1->id),
209             array('key' => 'visible', 'value' => 1)), 1);
211         // We need to execute the return values cleaning process to simulate the web service server.
212         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
214         // Check we retrieve the good total number of categories.
215         $this->assertEquals(2, count($categories));
217         // Check the return values
218         foreach ($categories as $category) {
219             $generatedcat = $generatedcats[$category['id']];
220             $this->assertEquals($category['idnumber'], $generatedcat->idnumber);
221             $this->assertEquals($category['name'], $generatedcat->name);
222             // Description was converted to the HTML format.
223             $this->assertEquals($category['description'], format_text($generatedcat->description, FORMAT_MOODLE, array('para' => false)));
224             $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
225         }
227         // Check categories by ids.
228         $ids = implode(',', array_keys($generatedcats));
229         $categories = core_course_external::get_categories(array(
230             array('key' => 'ids', 'value' => $ids)), 0);
232         // We need to execute the return values cleaning process to simulate the web service server.
233         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
235         // Check we retrieve the good total number of categories.
236         $this->assertEquals(6, count($categories));
237         // Check ids.
238         $returnedids = [];
239         foreach ($categories as $category) {
240             $returnedids[] = $category['id'];
241         }
242         // Sort the arrays upon comparision.
243         $this->assertEquals(array_keys($generatedcats), $returnedids, '', 0.0, 10, true);
245         // Check different params.
246         $categories = core_course_external::get_categories(array(
247             array('key' => 'id', 'value' => $category1->id),
248             array('key' => 'ids', 'value' => $category1->id),
249             array('key' => 'idnumber', 'value' => $category1->idnumber),
250             array('key' => 'visible', 'value' => 1)), 0);
252         // We need to execute the return values cleaning process to simulate the web service server.
253         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
255         $this->assertEquals(1, count($categories));
257         // Same query, but forcing a parameters clean.
258         $categories = core_course_external::get_categories(array(
259             array('key' => 'id', 'value' => "$category1->id"),
260             array('key' => 'idnumber', 'value' => $category1->idnumber),
261             array('key' => 'name', 'value' => $category1->name . "<br/>"),
262             array('key' => 'visible', 'value' => '1')), 0);
263         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
265         $this->assertEquals(1, count($categories));
267         // Retrieve categories from parent.
268         $categories = core_course_external::get_categories(array(
269             array('key' => 'parent', 'value' => $category3->id)), 1);
270         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
272         $this->assertEquals(2, count($categories));
274         // Retrieve all categories.
275         $categories = core_course_external::get_categories();
277         // We need to execute the return values cleaning process to simulate the web service server.
278         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
280         $this->assertEquals($DB->count_records('course_categories'), count($categories));
282         $this->unassignUserCapability('moodle/category:viewhiddencategories', $context->id, $roleid);
284         // Ensure maxdepthcategory is 2 and retrieve all categories without category:viewhiddencategories capability.
285         // It should retrieve all visible categories as well.
286         set_config('maxcategorydepth', 2);
287         $categories = core_course_external::get_categories();
289         // We need to execute the return values cleaning process to simulate the web service server.
290         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
292         $this->assertEquals($DB->count_records('course_categories', array('visible' => 1)), count($categories));
294         // Call without required capability (it will fail cause of the search on idnumber).
295         $this->expectException('moodle_exception');
296         $categories = core_course_external::get_categories(array(
297             array('key' => 'id', 'value' => $category1->id),
298             array('key' => 'idnumber', 'value' => $category1->idnumber),
299             array('key' => 'visible', 'value' => 1)), 0);
300     }
302     /**
303      * Test update_categories
304      */
305     public function test_update_categories() {
306         global $DB;
308         $this->resetAfterTest(true);
310         // Set the required capabilities by the external function
311         $contextid = context_system::instance()->id;
312         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
314         // Create base categories.
315         $category1data['idnumber'] = 'idnumbercat1';
316         $category1data['name'] = 'Category 1 for PHPunit test';
317         $category1data['description'] = 'Category 1 description';
318         $category1data['descriptionformat'] = FORMAT_MOODLE;
319         $category1  = self::getDataGenerator()->create_category($category1data);
320         $category2  = self::getDataGenerator()->create_category(
321                 array('parent' => $category1->id));
322         $category3  = self::getDataGenerator()->create_category();
323         $category4  = self::getDataGenerator()->create_category(
324                 array('parent' => $category3->id));
325         $category5  = self::getDataGenerator()->create_category(
326                 array('parent' => $category4->id));
328         // We update all category1 attribut.
329         // Then we move cat4 and cat5 parent: cat3 => cat1
330         $categories = array(
331             array('id' => $category1->id,
332                 'name' => $category1->name . '_updated',
333                 'idnumber' => $category1->idnumber . '_updated',
334                 'description' => $category1->description . '_updated',
335                 'descriptionformat' => FORMAT_HTML,
336                 'theme' => $category1->theme),
337             array('id' => $category4->id, 'parent' => $category1->id));
339         core_course_external::update_categories($categories);
341         // Check the values were updated.
342         $dbcategories = $DB->get_records_select('course_categories',
343                 'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
344                 . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
345         $this->assertEquals($category1->name . '_updated',
346                 $dbcategories[$category1->id]->name);
347         $this->assertEquals($category1->idnumber . '_updated',
348                 $dbcategories[$category1->id]->idnumber);
349         $this->assertEquals($category1->description . '_updated',
350                 $dbcategories[$category1->id]->description);
351         $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
353         // Check that category4 and category5 have been properly moved.
354         $this->assertEquals('/' . $category1->id . '/' . $category4->id,
355                 $dbcategories[$category4->id]->path);
356         $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
357                 $dbcategories[$category5->id]->path);
359         // Call without required capability.
360         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
361         $this->expectException('required_capability_exception');
362         core_course_external::update_categories($categories);
363     }
365     /**
366      * Test create_courses numsections
367      */
368     public function test_create_course_numsections() {
369         global $DB;
371         $this->resetAfterTest(true);
373         // Set the required capabilities by the external function.
374         $contextid = context_system::instance()->id;
375         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
376         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
378         $numsections = 10;
379         $category  = self::getDataGenerator()->create_category();
381         // Create base categories.
382         $course1['fullname'] = 'Test course 1';
383         $course1['shortname'] = 'Testcourse1';
384         $course1['categoryid'] = $category->id;
385         $course1['courseformatoptions'][] = array('name' => 'numsections', 'value' => $numsections);
387         $courses = array($course1);
389         $createdcourses = core_course_external::create_courses($courses);
390         foreach ($createdcourses as $createdcourse) {
391             $existingsections = $DB->get_records('course_sections', array('course' => $createdcourse['id']));
392             $modinfo = get_fast_modinfo($createdcourse['id']);
393             $sections = $modinfo->get_section_info_all();
394             $this->assertEquals(count($sections), $numsections + 1); // Includes generic section.
395             $this->assertEquals(count($existingsections), $numsections + 1); // Includes generic section.
396         }
397     }
399     /**
400      * Test create_courses
401      */
402     public function test_create_courses() {
403         global $DB;
405         $this->resetAfterTest(true);
407         // Enable course completion.
408         set_config('enablecompletion', 1);
409         // Enable course themes.
410         set_config('allowcoursethemes', 1);
412         // Set the required capabilities by the external function
413         $contextid = context_system::instance()->id;
414         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
415         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
416         $this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
418         $category  = self::getDataGenerator()->create_category();
420         // Create base categories.
421         $course1['fullname'] = 'Test course 1';
422         $course1['shortname'] = 'Testcourse1';
423         $course1['categoryid'] = $category->id;
424         $course2['fullname'] = 'Test course 2';
425         $course2['shortname'] = 'Testcourse2';
426         $course2['categoryid'] = $category->id;
427         $course2['idnumber'] = 'testcourse2idnumber';
428         $course2['summary'] = 'Description for course 2';
429         $course2['summaryformat'] = FORMAT_MOODLE;
430         $course2['format'] = 'weeks';
431         $course2['showgrades'] = 1;
432         $course2['newsitems'] = 3;
433         $course2['startdate'] = 1420092000; // 01/01/2015.
434         $course2['enddate'] = 1422669600; // 01/31/2015.
435         $course2['numsections'] = 4;
436         $course2['maxbytes'] = 100000;
437         $course2['showreports'] = 1;
438         $course2['visible'] = 0;
439         $course2['hiddensections'] = 0;
440         $course2['groupmode'] = 0;
441         $course2['groupmodeforce'] = 0;
442         $course2['defaultgroupingid'] = 0;
443         $course2['enablecompletion'] = 1;
444         $course2['completionnotify'] = 1;
445         $course2['lang'] = 'en';
446         $course2['forcetheme'] = 'bootstrapbase';
447         $course2['courseformatoptions'][] = array('name' => 'automaticenddate', 'value' => 0);
448         $course3['fullname'] = 'Test course 3';
449         $course3['shortname'] = 'Testcourse3';
450         $course3['categoryid'] = $category->id;
451         $course3['format'] = 'topics';
452         $course3options = array('numsections' => 8,
453             'hiddensections' => 1,
454             'coursedisplay' => 1);
455         $course3['courseformatoptions'] = array();
456         foreach ($course3options as $key => $value) {
457             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
458         }
459         $courses = array($course1, $course2, $course3);
461         $createdcourses = core_course_external::create_courses($courses);
463         // We need to execute the return values cleaning process to simulate the web service server.
464         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
466         // Check that right number of courses were created.
467         $this->assertEquals(3, count($createdcourses));
469         // Check that the courses were correctly created.
470         foreach ($createdcourses as $createdcourse) {
471             $courseinfo = course_get_format($createdcourse['id'])->get_course();
473             if ($createdcourse['shortname'] == $course2['shortname']) {
474                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
475                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
476                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
477                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
478                 $this->assertEquals($courseinfo->summary, $course2['summary']);
479                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
480                 $this->assertEquals($courseinfo->format, $course2['format']);
481                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
482                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
483                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
484                 $this->assertEquals($courseinfo->enddate, $course2['enddate']);
485                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(), $course2['numsections']);
486                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
487                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
488                 $this->assertEquals($courseinfo->visible, $course2['visible']);
489                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
490                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
491                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
492                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
493                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
494                 $this->assertEquals($courseinfo->lang, $course2['lang']);
495                 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
497                 // We enabled completion at the beginning of the test.
498                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
500             } else if ($createdcourse['shortname'] == $course1['shortname']) {
501                 $courseconfig = get_config('moodlecourse');
502                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
503                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
504                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
505                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
506                 $this->assertEquals($courseinfo->format, $courseconfig->format);
507                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
508                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
509                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
510                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
511                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
512                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
513                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
514             } else if ($createdcourse['shortname'] == $course3['shortname']) {
515                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
516                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
517                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
518                 $this->assertEquals($courseinfo->format, $course3['format']);
519                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
520                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(),
521                     $course3options['numsections']);
522                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
523             } else {
524                 throw new moodle_exception('Unexpected shortname');
525             }
526         }
528         // Call without required capability
529         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
530         $this->expectException('required_capability_exception');
531         $createdsubcats = core_course_external::create_courses($courses);
532     }
534     /**
535      * Test delete_courses
536      */
537     public function test_delete_courses() {
538         global $DB, $USER;
540         $this->resetAfterTest(true);
542         // Admin can delete a course.
543         $this->setAdminUser();
544         // Validate_context() will fail as the email is not set by $this->setAdminUser().
545         $USER->email = 'emailtopass@example.com';
547         $course1  = self::getDataGenerator()->create_course();
548         $course2  = self::getDataGenerator()->create_course();
549         $course3  = self::getDataGenerator()->create_course();
551         // Delete courses.
552         $result = core_course_external::delete_courses(array($course1->id, $course2->id));
553         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
554         // Check for 0 warnings.
555         $this->assertEquals(0, count($result['warnings']));
557         // Check $course 1 and 2 are deleted.
558         $notdeletedcount = $DB->count_records_select('course',
559             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
560         $this->assertEquals(0, $notdeletedcount);
562         // Try to delete non-existent course.
563         $result = core_course_external::delete_courses(array($course1->id));
564         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
565         // Check for 1 warnings.
566         $this->assertEquals(1, count($result['warnings']));
568         // Try to delete Frontpage course.
569         $result = core_course_external::delete_courses(array(0));
570         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
571         // Check for 1 warnings.
572         $this->assertEquals(1, count($result['warnings']));
574          // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
575         $student1 = self::getDataGenerator()->create_user();
576         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
577         $this->getDataGenerator()->enrol_user($student1->id,
578                                               $course3->id,
579                                               $studentrole->id);
580         $this->setUser($student1);
581         $result = core_course_external::delete_courses(array($course3->id));
582         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
583         // Check for 1 warnings.
584         $this->assertEquals(1, count($result['warnings']));
586          // Fail when the user is not allow to access the course (enrolled) or is not admin.
587         $this->setGuestUser();
588         $this->expectException('require_login_exception');
590         $result = core_course_external::delete_courses(array($course3->id));
591         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
592     }
594     /**
595      * Test get_courses
596      */
597     public function test_get_courses () {
598         global $DB;
600         $this->resetAfterTest(true);
602         $generatedcourses = array();
603         $coursedata['idnumber'] = 'idnumbercourse1';
604         // Adding tags here to check that format_string is applied.
605         $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
606         $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
607         $coursedata['summary'] = 'Course 1 description';
608         $coursedata['summaryformat'] = FORMAT_MOODLE;
609         $course1  = self::getDataGenerator()->create_course($coursedata);
611         $generatedcourses[$course1->id] = $course1;
612         $course2  = self::getDataGenerator()->create_course();
613         $generatedcourses[$course2->id] = $course2;
614         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
615         $generatedcourses[$course3->id] = $course3;
617         // Set the required capabilities by the external function.
618         $context = context_system::instance();
619         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
620         $this->assignUserCapability('moodle/course:update',
621                 context_course::instance($course1->id)->id, $roleid);
622         $this->assignUserCapability('moodle/course:update',
623                 context_course::instance($course2->id)->id, $roleid);
624         $this->assignUserCapability('moodle/course:update',
625                 context_course::instance($course3->id)->id, $roleid);
627         $courses = core_course_external::get_courses(array('ids' =>
628             array($course1->id, $course2->id)));
630         // We need to execute the return values cleaning process to simulate the web service server.
631         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
633         // Check we retrieve the good total number of categories.
634         $this->assertEquals(2, count($courses));
636         foreach ($courses as $course) {
637             $coursecontext = context_course::instance($course['id']);
638             $dbcourse = $generatedcourses[$course['id']];
639             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
640             $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id));
641             $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse),
642                 $coursecontext->id));
643             // Summary was converted to the HTML format.
644             $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
645             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
646             $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id));
647             $this->assertEquals($course['categoryid'], $dbcourse->category);
648             $this->assertEquals($course['format'], $dbcourse->format);
649             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
650             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
651             $this->assertEquals($course['startdate'], $dbcourse->startdate);
652             $this->assertEquals($course['enddate'], $dbcourse->enddate);
653             $this->assertEquals($course['numsections'], course_get_format($dbcourse)->get_last_section_number());
654             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
655             $this->assertEquals($course['showreports'], $dbcourse->showreports);
656             $this->assertEquals($course['visible'], $dbcourse->visible);
657             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
658             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
659             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
660             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
661             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
662             $this->assertEquals($course['lang'], $dbcourse->lang);
663             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
664             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
665             if ($dbcourse->format === 'topics') {
666                 $this->assertEquals($course['courseformatoptions'], array(
667                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
668                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
669                 ));
670             }
671         }
673         // Get all courses in the DB
674         $courses = core_course_external::get_courses(array());
676         // We need to execute the return values cleaning process to simulate the web service server.
677         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
679         $this->assertEquals($DB->count_records('course'), count($courses));
680     }
682     /**
683      * Test get_courses without capability
684      */
685     public function test_get_courses_without_capability() {
686         $this->resetAfterTest(true);
688         $course1 = $this->getDataGenerator()->create_course();
689         $this->setUser($this->getDataGenerator()->create_user());
691         // No permissions are required to get the site course.
692         $courses = core_course_external::get_courses(array('ids' => [SITEID]));
693         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
695         $this->assertEquals(1, count($courses));
696         $this->assertEquals('PHPUnit test site', $courses[0]['fullname']);
697         $this->assertEquals('site', $courses[0]['format']);
699         // Requesting course without being enrolled or capability to view it will throw an exception.
700         try {
701             core_course_external::get_courses(array('ids' => [$course1->id]));
702             $this->fail('Exception expected');
703         } catch (moodle_exception $e) {
704             $this->assertEquals(1, preg_match('/Course or activity not accessible. \(Not enrolled\)/', $e->getMessage()));
705         }
706     }
708     /**
709      * Test search_courses
710      */
711     public function test_search_courses () {
713         global $DB;
715         $this->resetAfterTest(true);
716         $this->setAdminUser();
717         $generatedcourses = array();
718         $coursedata1['fullname'] = 'FIRST COURSE';
719         $course1  = self::getDataGenerator()->create_course($coursedata1);
721         $page = new moodle_page();
722         $page->set_course($course1);
723         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
725         $coursedata2['fullname'] = 'SECOND COURSE';
726         $course2  = self::getDataGenerator()->create_course($coursedata2);
728         $page = new moodle_page();
729         $page->set_course($course2);
730         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
731         // Search by name.
732         $results = core_course_external::search_courses('search', 'FIRST');
733         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
734         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
735         $this->assertCount(1, $results['courses']);
737         // Create the forum.
738         $record = new stdClass();
739         $record->introformat = FORMAT_HTML;
740         $record->course = $course2->id;
741         // Set Aggregate type = Average of ratings.
742         $forum = self::getDataGenerator()->create_module('forum', $record);
744         // Search by module.
745         $results = core_course_external::search_courses('modulelist', 'forum');
746         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
747         $this->assertEquals(1, $results['total']);
749         // Enable coursetag option.
750         set_config('block_tags_showcoursetags', true);
751         // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
752         core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
753                 array('TAG-LABEL ON SECOND COURSE'));
754         $taginstance = $DB->get_record('tag_instance',
755                 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
756         // Search by tagid.
757         $results = core_course_external::search_courses('tagid', $taginstance->tagid);
758         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
759         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
761         // Search by block (use news_items default block).
762         $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
763         $results = core_course_external::search_courses('blocklist', $blockid);
764         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
765         $this->assertEquals(2, $results['total']);
767         // Now as a normal user.
768         $user = self::getDataGenerator()->create_user();
770         // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
771         $coursedata3['fullname'] = 'HIDDEN COURSE';
772         $coursedata3['visible'] = 0;
773         $course3  = self::getDataGenerator()->create_course($coursedata3);
774         $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
776         $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
777         $this->setUser($user);
779         $results = core_course_external::search_courses('search', 'FIRST');
780         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
781         $this->assertCount(1, $results['courses']);
782         $this->assertEquals(1, $results['total']);
783         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
785         // Check that we can see both without the limit to enrolled setting.
786         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
787         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
788         $this->assertCount(2, $results['courses']);
789         $this->assertEquals(2, $results['total']);
791         // Check that we only see our enrolled course when limiting.
792         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
793         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
794         $this->assertCount(1, $results['courses']);
795         $this->assertEquals(1, $results['total']);
796         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
798         // Search by block (use news_items default block). Should fail (only admins allowed).
799         $this->expectException('required_capability_exception');
800         $results = core_course_external::search_courses('blocklist', $blockid);
802     }
804     /**
805      * Create a course with contents
806      * @return array A list with the course object and course modules objects
807      */
808     private function prepare_get_course_contents_test() {
809         global $DB, $CFG;
811         $CFG->allowstealth = 1; // Allow stealth activities.
813         $course  = self::getDataGenerator()->create_course(['numsections' => 4]);
814         $forumdescription = 'This is the forum description';
815         $forum = $this->getDataGenerator()->create_module('forum',
816             array('course' => $course->id, 'intro' => $forumdescription),
817             array('showdescription' => true));
818         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
819         $data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
820         $datacm = get_coursemodule_from_instance('page', $data->id);
821         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
822         $pagecm = get_coursemodule_from_instance('page', $page->id);
823         // This is an stealth page (set by visibleoncoursepage).
824         $pagestealth = $this->getDataGenerator()->create_module('page', array('course' => $course->id, 'visibleoncoursepage' => 0));
825         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
826                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
827         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
828             'intro' => $labeldescription));
829         $labelcm = get_coursemodule_from_instance('label', $label->id);
830         $tomorrow = time() + DAYSECS;
831         // Module with availability restrictions not met.
832         $url = $this->getDataGenerator()->create_module('url',
833             array('course' => $course->id, 'name' => 'URL: % & $ ../', 'section' => 2),
834             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}'));
835         $urlcm = get_coursemodule_from_instance('url', $url->id);
836         // Module for the last section.
837         $this->getDataGenerator()->create_module('url',
838             array('course' => $course->id, 'name' => 'URL for last section', 'section' => 3));
839         // Module for section 1 with availability restrictions met.
840         $yesterday = time() - DAYSECS;
841         $this->getDataGenerator()->create_module('url',
842             array('course' => $course->id, 'name' => 'URL restrictions met', 'section' => 1),
843             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":'. $yesterday .'}],"showc":[true]}'));
845         // Set the required capabilities by the external function.
846         $context = context_course::instance($course->id);
847         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
848         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
849         $this->assignUserCapability('mod/data:view', $context->id, $roleid);
851         $conditions = array('course' => $course->id, 'section' => 2);
852         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
854         // Add date availability condition not met for section 3.
855         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}';
856         $DB->set_field('course_sections', 'availability', $availability,
857                 array('course' => $course->id, 'section' => 3));
859         // Create resource for last section.
860         $pageinhiddensection = $this->getDataGenerator()->create_module('page',
861             array('course' => $course->id, 'name' => 'Page in hidden section', 'section' => 4));
862         // Set not visible last section.
863         $DB->set_field('course_sections', 'visible', 0,
864                 array('course' => $course->id, 'section' => 4));
866         rebuild_course_cache($course->id, true);
868         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
869     }
871     /**
872      * Test get_course_contents
873      */
874     public function test_get_course_contents() {
875         $this->resetAfterTest(true);
877         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
879         // We first run the test as admin.
880         $this->setAdminUser();
881         $sections = core_course_external::get_course_contents($course->id, array());
882         // We need to execute the return values cleaning process to simulate the web service server.
883         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
885         $modinfo = get_fast_modinfo($course);
886         $testexecuted = 0;
887         foreach ($sections[0]['modules'] as $module) {
888             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
889                 $cm = $modinfo->cms[$forumcm->id];
890                 $formattedtext = format_text($cm->content, FORMAT_HTML,
891                     array('noclean' => true, 'para' => false, 'filter' => false));
892                 $this->assertEquals($formattedtext, $module['description']);
893                 $this->assertEquals($forumcm->instance, $module['instance']);
894                 $testexecuted = $testexecuted + 1;
895             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
896                 $cm = $modinfo->cms[$labelcm->id];
897                 $formattedtext = format_text($cm->content, FORMAT_HTML,
898                     array('noclean' => true, 'para' => false, 'filter' => false));
899                 $this->assertEquals($formattedtext, $module['description']);
900                 $this->assertEquals($labelcm->instance, $module['instance']);
901                 $testexecuted = $testexecuted + 1;
902             }
903         }
904         $this->assertEquals(2, $testexecuted);
905         $this->assertEquals(0, $sections[0]['section']);
907         $this->assertCount(5, $sections[0]['modules']);
908         $this->assertCount(1, $sections[1]['modules']);
909         $this->assertCount(1, $sections[2]['modules']);
910         $this->assertCount(1, $sections[3]['modules']); // One module for the section with availability restrictions.
911         $this->assertCount(1, $sections[4]['modules']); // One module for the hidden section with a visible activity.
912         $this->assertNotEmpty($sections[3]['availabilityinfo']);
913         $this->assertEquals(1, $sections[1]['section']);
914         $this->assertEquals(2, $sections[2]['section']);
915         $this->assertEquals(3, $sections[3]['section']);
916         $this->assertEquals(4, $sections[4]['section']);
917         $this->assertContains('<iframe', $sections[2]['summary']);
918         $this->assertContains('</iframe>', $sections[2]['summary']);
919         $this->assertNotEmpty($sections[2]['modules'][0]['availabilityinfo']);
920         try {
921             $sections = core_course_external::get_course_contents($course->id,
922                                                                     array(array("name" => "invalid", "value" => 1)));
923             $this->fail('Exception expected due to invalid option.');
924         } catch (moodle_exception $e) {
925             $this->assertEquals('errorinvalidparam', $e->errorcode);
926         }
927     }
930     /**
931      * Test get_course_contents as student
932      */
933     public function test_get_course_contents_student() {
934         global $DB;
935         $this->resetAfterTest(true);
937         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
939         $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
940         $user = self::getDataGenerator()->create_user();
941         self::getDataGenerator()->enrol_user($user->id, $course->id, $studentroleid);
942         $this->setUser($user);
944         $sections = core_course_external::get_course_contents($course->id, array());
945         // We need to execute the return values cleaning process to simulate the web service server.
946         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
948         $this->assertCount(4, $sections); // Nothing for the not visible section.
949         $this->assertCount(5, $sections[0]['modules']);
950         $this->assertCount(1, $sections[1]['modules']);
951         $this->assertCount(1, $sections[2]['modules']);
952         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
954         $this->assertNotEmpty($sections[3]['availabilityinfo']);
955         $this->assertEquals(1, $sections[1]['section']);
956         $this->assertEquals(2, $sections[2]['section']);
957         $this->assertEquals(3, $sections[3]['section']);
958         // The module with the availability restriction met is returning contents.
959         $this->assertNotEmpty($sections[1]['modules'][0]['contents']);
960         // The module with the availability restriction not met is not returning contents.
961         $this->assertArrayNotHasKey('contents', $sections[2]['modules'][0]);
963         // Now include flag for returning stealth information (fake section).
964         $sections = core_course_external::get_course_contents($course->id,
965             array(array("name" => "includestealthmodules", "value" => 1)));
966         // We need to execute the return values cleaning process to simulate the web service server.
967         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
969         $this->assertCount(5, $sections); // Include fake section with stealth activities.
970         $this->assertCount(5, $sections[0]['modules']);
971         $this->assertCount(1, $sections[1]['modules']);
972         $this->assertCount(1, $sections[2]['modules']);
973         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
974         $this->assertCount(1, $sections[4]['modules']); // One stealh module.
975         $this->assertEquals(-1, $sections[4]['id']);
976     }
978     /**
979      * Test get_course_contents excluding modules
980      */
981     public function test_get_course_contents_excluding_modules() {
982         $this->resetAfterTest(true);
984         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
986         // Test exclude modules.
987         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
989         // We need to execute the return values cleaning process to simulate the web service server.
990         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
992         $this->assertEmpty($sections[0]['modules']);
993         $this->assertEmpty($sections[1]['modules']);
994     }
996     /**
997      * Test get_course_contents excluding contents
998      */
999     public function test_get_course_contents_excluding_contents() {
1000         $this->resetAfterTest(true);
1002         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1004         // Test exclude modules.
1005         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
1007         // We need to execute the return values cleaning process to simulate the web service server.
1008         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1010         foreach ($sections as $section) {
1011             foreach ($section['modules'] as $module) {
1012                 // Only resources return contents.
1013                 if (isset($module['contents'])) {
1014                     $this->assertEmpty($module['contents']);
1015                 }
1016             }
1017         }
1018     }
1020     /**
1021      * Test get_course_contents filtering by section number
1022      */
1023     public function test_get_course_contents_section_number() {
1024         $this->resetAfterTest(true);
1026         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1028         // Test exclude modules.
1029         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
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(1, $sections);
1035         $this->assertCount(5, $sections[0]['modules']);
1036     }
1038     /**
1039      * Test get_course_contents filtering by cmid
1040      */
1041     public function test_get_course_contents_cmid() {
1042         $this->resetAfterTest(true);
1044         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1046         // Test exclude modules.
1047         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
1049         // We need to execute the return values cleaning process to simulate the web service server.
1050         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1052         $this->assertCount(4, $sections);
1053         $this->assertCount(1, $sections[0]['modules']);
1054         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1055     }
1058     /**
1059      * Test get_course_contents filtering by cmid and section
1060      */
1061     public function test_get_course_contents_section_cmid() {
1062         $this->resetAfterTest(true);
1064         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1066         // Test exclude modules.
1067         $sections = core_course_external::get_course_contents($course->id, array(
1068                                                                         array("name" => "cmid", "value" => $forumcm->id),
1069                                                                         array("name" => "sectionnumber", "value" => 0)
1070                                                                         ));
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         $this->assertCount(1, $sections);
1076         $this->assertCount(1, $sections[0]['modules']);
1077         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1078     }
1080     /**
1081      * Test get_course_contents filtering by modname
1082      */
1083     public function test_get_course_contents_modname() {
1084         $this->resetAfterTest(true);
1086         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1088         // Test exclude modules.
1089         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
1091         // We need to execute the return values cleaning process to simulate the web service server.
1092         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1094         $this->assertCount(4, $sections);
1095         $this->assertCount(1, $sections[0]['modules']);
1096         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1097     }
1099     /**
1100      * Test get_course_contents filtering by modname
1101      */
1102     public function test_get_course_contents_modid() {
1103         $this->resetAfterTest(true);
1105         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1107         // Test exclude modules.
1108         $sections = core_course_external::get_course_contents($course->id, array(
1109                                                                             array("name" => "modname", "value" => "page"),
1110                                                                             array("name" => "modid", "value" => $pagecm->instance),
1111                                                                             ));
1113         // We need to execute the return values cleaning process to simulate the web service server.
1114         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1116         $this->assertCount(4, $sections);
1117         $this->assertCount(1, $sections[0]['modules']);
1118         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
1119         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
1120     }
1122     /**
1123      * Test duplicate_course
1124      */
1125     public function test_duplicate_course() {
1126         $this->resetAfterTest(true);
1128         // Create one course with three modules.
1129         $course  = self::getDataGenerator()->create_course();
1130         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
1131         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
1132         $forumcontext = context_module::instance($forum->cmid);
1133         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
1134         $datacontext = context_module::instance($data->cmid);
1135         $datacm = get_coursemodule_from_instance('page', $data->id);
1136         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
1137         $pagecontext = context_module::instance($page->cmid);
1138         $pagecm = get_coursemodule_from_instance('page', $page->id);
1140         // Set the required capabilities by the external function.
1141         $coursecontext = context_course::instance($course->id);
1142         $categorycontext = context_coursecat::instance($course->category);
1143         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
1144         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
1145         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
1146         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
1147         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
1148         // Optional capabilities to copy user data.
1149         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
1150         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
1152         $newcourse['fullname'] = 'Course duplicate';
1153         $newcourse['shortname'] = 'courseduplicate';
1154         $newcourse['categoryid'] = $course->category;
1155         $newcourse['visible'] = true;
1156         $newcourse['options'][] = array('name' => 'users', 'value' => true);
1158         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
1159                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
1161         // We need to execute the return values cleaning process to simulate the web service server.
1162         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1164         // Check that the course has been duplicated.
1165         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1166     }
1168     /**
1169      * Test update_courses
1170      */
1171     public function test_update_courses() {
1172         global $DB, $CFG, $USER, $COURSE;
1174         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1175         // trick because we are both updating and getting (for testing) course information
1176         // in the same request and core_course_external::update_courses()
1177         // is overwriting $COURSE all over the time with OLD values, so later
1178         // use of get_course() fetches those OLD values instead of the updated ones.
1179         // See MDL-39723 for more info.
1180         $origcourse = clone($COURSE);
1182         $this->resetAfterTest(true);
1184         // Set the required capabilities by the external function.
1185         $contextid = context_system::instance()->id;
1186         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1187         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1188         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1189         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1190         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1191         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1192         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1193         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1194         $this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
1196         // Create category and course.
1197         $category1  = self::getDataGenerator()->create_category();
1198         $category2  = self::getDataGenerator()->create_category();
1199         $originalcourse1 = self::getDataGenerator()->create_course();
1200         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1201         $originalcourse2 = self::getDataGenerator()->create_course();
1202         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1204         // Course values to be updated.
1205         $course1['id'] = $originalcourse1->id;
1206         $course1['fullname'] = 'Updated test course 1';
1207         $course1['shortname'] = 'Udestedtestcourse1';
1208         $course1['categoryid'] = $category1->id;
1209         $course2['id'] = $originalcourse2->id;
1210         $course2['fullname'] = 'Updated test course 2';
1211         $course2['shortname'] = 'Updestedtestcourse2';
1212         $course2['categoryid'] = $category2->id;
1213         $course2['idnumber'] = 'Updatedidnumber2';
1214         $course2['summary'] = 'Updaated description for course 2';
1215         $course2['summaryformat'] = FORMAT_HTML;
1216         $course2['format'] = 'topics';
1217         $course2['showgrades'] = 1;
1218         $course2['newsitems'] = 3;
1219         $course2['startdate'] = 1420092000; // 01/01/2015.
1220         $course2['enddate'] = 1422669600; // 01/31/2015.
1221         $course2['maxbytes'] = 100000;
1222         $course2['showreports'] = 1;
1223         $course2['visible'] = 0;
1224         $course2['hiddensections'] = 0;
1225         $course2['groupmode'] = 0;
1226         $course2['groupmodeforce'] = 0;
1227         $course2['defaultgroupingid'] = 0;
1228         $course2['enablecompletion'] = 1;
1229         $course2['lang'] = 'en';
1230         $course2['forcetheme'] = 'bootstrapbase';
1231         $courses = array($course1, $course2);
1233         $updatedcoursewarnings = core_course_external::update_courses($courses);
1234         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1235                                                                     $updatedcoursewarnings);
1236         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1238         // Check that right number of courses were created.
1239         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1241         // Check that the courses were correctly created.
1242         foreach ($courses as $course) {
1243             $courseinfo = course_get_format($course['id'])->get_course();
1244             if ($course['id'] == $course2['id']) {
1245                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1246                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1247                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1248                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1249                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1250                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1251                 $this->assertEquals($course2['format'], $courseinfo->format);
1252                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1253                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1254                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1255                 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
1256                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1257                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1258                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1259                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1260                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1261                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1262                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1263                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1265                 if (!empty($CFG->allowcoursethemes)) {
1266                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1267                 }
1269                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1270             } else if ($course['id'] == $course1['id']) {
1271                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1272                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1273                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1274                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1275                 $this->assertEquals('topics', $courseinfo->format);
1276                 $this->assertEquals(5, course_get_format($course['id'])->get_last_section_number());
1277                 $this->assertEquals(0, $courseinfo->newsitems);
1278                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1279             } else {
1280                 throw new moodle_exception('Unexpected shortname');
1281             }
1282         }
1284         $courses = array($course1);
1285         // Try update course without update capability.
1286         $user = self::getDataGenerator()->create_user();
1287         $this->setUser($user);
1288         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1289         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1290         $updatedcoursewarnings = core_course_external::update_courses($courses);
1291         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1292                                                                     $updatedcoursewarnings);
1293         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1295         // Try update course category without capability.
1296         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1297         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1298         $user = self::getDataGenerator()->create_user();
1299         $this->setUser($user);
1300         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1301         $course1['categoryid'] = $category2->id;
1302         $courses = array($course1);
1303         $updatedcoursewarnings = core_course_external::update_courses($courses);
1304         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1305                                                                     $updatedcoursewarnings);
1306         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1308         // Try update course fullname without capability.
1309         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1310         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1311         $user = self::getDataGenerator()->create_user();
1312         $this->setUser($user);
1313         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1314         $updatedcoursewarnings = core_course_external::update_courses($courses);
1315         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1316                                                                     $updatedcoursewarnings);
1317         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1318         $course1['fullname'] = 'Testing fullname without permission';
1319         $courses = array($course1);
1320         $updatedcoursewarnings = core_course_external::update_courses($courses);
1321         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1322                                                                     $updatedcoursewarnings);
1323         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1325         // Try update course shortname without capability.
1326         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1327         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1328         $user = self::getDataGenerator()->create_user();
1329         $this->setUser($user);
1330         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1331         $updatedcoursewarnings = core_course_external::update_courses($courses);
1332         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1333                                                                     $updatedcoursewarnings);
1334         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1335         $course1['shortname'] = 'Testing shortname without permission';
1336         $courses = array($course1);
1337         $updatedcoursewarnings = core_course_external::update_courses($courses);
1338         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1339                                                                     $updatedcoursewarnings);
1340         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1342         // Try update course idnumber without capability.
1343         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1344         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1345         $user = self::getDataGenerator()->create_user();
1346         $this->setUser($user);
1347         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1348         $updatedcoursewarnings = core_course_external::update_courses($courses);
1349         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1350                                                                     $updatedcoursewarnings);
1351         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1352         $course1['idnumber'] = 'NEWIDNUMBER';
1353         $courses = array($course1);
1354         $updatedcoursewarnings = core_course_external::update_courses($courses);
1355         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1356                                                                     $updatedcoursewarnings);
1357         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1359         // Try update course summary without capability.
1360         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1361         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1362         $user = self::getDataGenerator()->create_user();
1363         $this->setUser($user);
1364         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1365         $updatedcoursewarnings = core_course_external::update_courses($courses);
1366         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1367                                                                     $updatedcoursewarnings);
1368         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1369         $course1['summary'] = 'New summary';
1370         $courses = array($course1);
1371         $updatedcoursewarnings = core_course_external::update_courses($courses);
1372         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1373                                                                     $updatedcoursewarnings);
1374         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1376         // Try update course with invalid summary format.
1377         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1378         $user = self::getDataGenerator()->create_user();
1379         $this->setUser($user);
1380         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1381         $updatedcoursewarnings = core_course_external::update_courses($courses);
1382         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1383                                                                     $updatedcoursewarnings);
1384         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1385         $course1['summaryformat'] = 10;
1386         $courses = array($course1);
1387         $updatedcoursewarnings = core_course_external::update_courses($courses);
1388         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1389                                                                     $updatedcoursewarnings);
1390         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1392         // Try update course visibility without capability.
1393         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1394         $user = self::getDataGenerator()->create_user();
1395         $this->setUser($user);
1396         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1397         $course1['summaryformat'] = FORMAT_MOODLE;
1398         $courses = array($course1);
1399         $updatedcoursewarnings = core_course_external::update_courses($courses);
1400         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1401                                                                     $updatedcoursewarnings);
1402         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1403         $course1['visible'] = 0;
1404         $courses = array($course1);
1405         $updatedcoursewarnings = core_course_external::update_courses($courses);
1406         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1407                                                                     $updatedcoursewarnings);
1408         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1409     }
1411     /**
1412      * Test delete course_module.
1413      */
1414     public function test_delete_modules() {
1415         global $DB;
1417         // Ensure we reset the data after this test.
1418         $this->resetAfterTest(true);
1420         // Create a user.
1421         $user = self::getDataGenerator()->create_user();
1423         // Set the tests to run as the user.
1424         self::setUser($user);
1426         // Create a course to add the modules.
1427         $course = self::getDataGenerator()->create_course();
1429         // Create two test modules.
1430         $record = new stdClass();
1431         $record->course = $course->id;
1432         $module1 = self::getDataGenerator()->create_module('forum', $record);
1433         $module2 = self::getDataGenerator()->create_module('assign', $record);
1435         // Check the forum was correctly created.
1436         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1438         // Check the assignment was correctly created.
1439         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1441         // Check data exists in the course modules table.
1442         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1443                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1445         // Enrol the user in the course.
1446         $enrol = enrol_get_plugin('manual');
1447         $enrolinstances = enrol_get_instances($course->id, true);
1448         foreach ($enrolinstances as $courseenrolinstance) {
1449             if ($courseenrolinstance->enrol == "manual") {
1450                 $instance = $courseenrolinstance;
1451                 break;
1452             }
1453         }
1454         $enrol->enrol_user($instance, $user->id);
1456         // Assign capabilities to delete module 1.
1457         $modcontext = context_module::instance($module1->cmid);
1458         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1460         // Assign capabilities to delete module 2.
1461         $modcontext = context_module::instance($module2->cmid);
1462         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1463         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1465         // Deleting these module instances.
1466         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1468         // Check the forum was deleted.
1469         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1471         // Check the assignment was deleted.
1472         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1474         // Check we retrieve no data in the course modules table.
1475         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1476                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1478         // Call with non-existent course module id and ensure exception thrown.
1479         try {
1480             core_course_external::delete_modules(array('1337'));
1481             $this->fail('Exception expected due to missing course module.');
1482         } catch (dml_missing_record_exception $e) {
1483             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1484         }
1486         // Create two modules.
1487         $module1 = self::getDataGenerator()->create_module('forum', $record);
1488         $module2 = self::getDataGenerator()->create_module('assign', $record);
1490         // Since these modules were recreated the user will not have capabilities
1491         // to delete them, ensure exception is thrown if they try.
1492         try {
1493             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1494             $this->fail('Exception expected due to missing capability.');
1495         } catch (moodle_exception $e) {
1496             $this->assertEquals('nopermissions', $e->errorcode);
1497         }
1499         // Unenrol user from the course.
1500         $enrol->unenrol_user($instance, $user->id);
1502         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1503         try {
1504             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1505             $this->fail('Exception expected due to being unenrolled from the course.');
1506         } catch (moodle_exception $e) {
1507             $this->assertEquals('requireloginerror', $e->errorcode);
1508         }
1509     }
1511     /**
1512      * Test import_course into an empty course
1513      */
1514     public function test_import_course_empty() {
1515         global $USER;
1517         $this->resetAfterTest(true);
1519         $course1  = self::getDataGenerator()->create_course();
1520         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1521         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1523         $course2  = self::getDataGenerator()->create_course();
1525         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1526         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1528         // Verify the state of the courses before we do the import.
1529         $this->assertCount(2, $course1cms);
1530         $this->assertEmpty($course2cms);
1532         // Setup the user to run the operation (ugly hack because validate_context() will
1533         // fail as the email is not set by $this->setAdminUser()).
1534         $this->setAdminUser();
1535         $USER->email = 'emailtopass@example.com';
1537         // Import from course1 to course2.
1538         core_course_external::import_course($course1->id, $course2->id, 0);
1540         // Verify that now we have two modules in both courses.
1541         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1542         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1543         $this->assertCount(2, $course1cms);
1544         $this->assertCount(2, $course2cms);
1546         // Verify that the names transfered across correctly.
1547         foreach ($course2cms as $cm) {
1548             if ($cm->modname === 'page') {
1549                 $this->assertEquals($cm->name, $page->name);
1550             } else if ($cm->modname === 'forum') {
1551                 $this->assertEquals($cm->name, $forum->name);
1552             } else {
1553                 $this->fail('Unknown CM found.');
1554             }
1555         }
1556     }
1558     /**
1559      * Test import_course into an filled course
1560      */
1561     public function test_import_course_filled() {
1562         global $USER;
1564         $this->resetAfterTest(true);
1566         // Add forum and page to course1.
1567         $course1  = self::getDataGenerator()->create_course();
1568         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1569         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1571         // Add quiz to course 2.
1572         $course2  = self::getDataGenerator()->create_course();
1573         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1575         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1576         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1578         // Verify the state of the courses before we do the import.
1579         $this->assertCount(2, $course1cms);
1580         $this->assertCount(1, $course2cms);
1582         // Setup the user to run the operation (ugly hack because validate_context() will
1583         // fail as the email is not set by $this->setAdminUser()).
1584         $this->setAdminUser();
1585         $USER->email = 'emailtopass@example.com';
1587         // Import from course1 to course2 without deleting content.
1588         core_course_external::import_course($course1->id, $course2->id, 0);
1590         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1592         // Verify that now we have three modules in course2.
1593         $this->assertCount(3, $course2cms);
1595         // Verify that the names transfered across correctly.
1596         foreach ($course2cms as $cm) {
1597             if ($cm->modname === 'page') {
1598                 $this->assertEquals($cm->name, $page->name);
1599             } else if ($cm->modname === 'forum') {
1600                 $this->assertEquals($cm->name, $forum->name);
1601             } else if ($cm->modname === 'quiz') {
1602                 $this->assertEquals($cm->name, $quiz->name);
1603             } else {
1604                 $this->fail('Unknown CM found.');
1605             }
1606         }
1607     }
1609     /**
1610      * Test import_course with only blocks set to backup
1611      */
1612     public function test_import_course_blocksonly() {
1613         global $USER, $DB;
1615         $this->resetAfterTest(true);
1617         // Add forum and page to course1.
1618         $course1  = self::getDataGenerator()->create_course();
1619         $course1ctx = context_course::instance($course1->id);
1620         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1621         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1623         $course2  = self::getDataGenerator()->create_course();
1624         $course2ctx = context_course::instance($course2->id);
1625         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1626         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1628         // Setup the user to run the operation (ugly hack because validate_context() will
1629         // fail as the email is not set by $this->setAdminUser()).
1630         $this->setAdminUser();
1631         $USER->email = 'emailtopass@example.com';
1633         // Import from course1 to course2 without deleting content, but excluding
1634         // activities.
1635         $options = array(
1636             array('name' => 'activities', 'value' => 0),
1637             array('name' => 'blocks', 'value' => 1),
1638             array('name' => 'filters', 'value' => 0),
1639         );
1641         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1643         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1644         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1645         // Check that course modules haven't changed, but that blocks have.
1646         $this->assertEquals($initialcmcount, $newcmcount);
1647         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1648     }
1650     /**
1651      * Test import_course into an filled course, deleting content.
1652      */
1653     public function test_import_course_deletecontent() {
1654         global $USER;
1655         $this->resetAfterTest(true);
1657         // Add forum and page to course1.
1658         $course1  = self::getDataGenerator()->create_course();
1659         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1660         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1662         // Add quiz to course 2.
1663         $course2  = self::getDataGenerator()->create_course();
1664         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1666         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1667         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1669         // Verify the state of the courses before we do the import.
1670         $this->assertCount(2, $course1cms);
1671         $this->assertCount(1, $course2cms);
1673         // Setup the user to run the operation (ugly hack because validate_context() will
1674         // fail as the email is not set by $this->setAdminUser()).
1675         $this->setAdminUser();
1676         $USER->email = 'emailtopass@example.com';
1678         // Import from course1 to course2,  deleting content.
1679         core_course_external::import_course($course1->id, $course2->id, 1);
1681         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1683         // Verify that now we have two modules in course2.
1684         $this->assertCount(2, $course2cms);
1686         // Verify that the course only contains the imported modules.
1687         foreach ($course2cms as $cm) {
1688             if ($cm->modname === 'page') {
1689                 $this->assertEquals($cm->name, $page->name);
1690             } else if ($cm->modname === 'forum') {
1691                 $this->assertEquals($cm->name, $forum->name);
1692             } else {
1693                 $this->fail('Unknown CM found: '.$cm->name);
1694             }
1695         }
1696     }
1698     /**
1699      * Ensure import_course handles incorrect deletecontent option correctly.
1700      */
1701     public function test_import_course_invalid_deletecontent_option() {
1702         $this->resetAfterTest(true);
1704         $course1  = self::getDataGenerator()->create_course();
1705         $course2  = self::getDataGenerator()->create_course();
1707         $this->expectException('moodle_exception');
1708         $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
1709         // Import from course1 to course2, with invalid option
1710         core_course_external::import_course($course1->id, $course2->id, -1);;
1711     }
1713     /**
1714      * Test view_course function
1715      */
1716     public function test_view_course() {
1718         $this->resetAfterTest();
1720         // Course without sections.
1721         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1722         $this->setAdminUser();
1724         // Redirect events to the sink, so we can recover them later.
1725         $sink = $this->redirectEvents();
1727         $result = core_course_external::view_course($course->id, 1);
1728         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1729         $events = $sink->get_events();
1730         $event = reset($events);
1732         // Check the event details are correct.
1733         $this->assertInstanceOf('\core\event\course_viewed', $event);
1734         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1735         $this->assertEquals(1, $event->other['coursesectionnumber']);
1737         $result = core_course_external::view_course($course->id);
1738         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1739         $events = $sink->get_events();
1740         $event = array_pop($events);
1741         $sink->close();
1743         // Check the event details are correct.
1744         $this->assertInstanceOf('\core\event\course_viewed', $event);
1745         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1746         $this->assertEmpty($event->other);
1748     }
1750     /**
1751      * Test get_course_module
1752      */
1753     public function test_get_course_module() {
1754         global $DB;
1756         $this->resetAfterTest(true);
1758         $this->setAdminUser();
1759         $course = self::getDataGenerator()->create_course();
1760         $record = array(
1761             'course' => $course->id,
1762             'name' => 'First Assignment'
1763         );
1764         $options = array(
1765             'idnumber' => 'ABC',
1766             'visible' => 0
1767         );
1768         // Hidden activity.
1769         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
1771         $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
1773         // Insert a custom grade scale to be used by an outcome.
1774         $gradescale = new grade_scale();
1775         $gradescale->name        = 'gettcoursemodulescale';
1776         $gradescale->courseid    = $course->id;
1777         $gradescale->userid      = 0;
1778         $gradescale->scale       = $outcomescale;
1779         $gradescale->description = 'This scale is used to mark standard assignments.';
1780         $gradescale->insert();
1782         // Insert an outcome.
1783         $data = new stdClass();
1784         $data->courseid = $course->id;
1785         $data->fullname = 'Team work';
1786         $data->shortname = 'Team work';
1787         $data->scaleid = $gradescale->id;
1788         $outcome = new grade_outcome($data, false);
1789         $outcome->insert();
1791         $outcomegradeitem = new grade_item();
1792         $outcomegradeitem->itemname = $outcome->shortname;
1793         $outcomegradeitem->itemtype = 'mod';
1794         $outcomegradeitem->itemmodule = 'assign';
1795         $outcomegradeitem->iteminstance = $assign->id;
1796         $outcomegradeitem->outcomeid = $outcome->id;
1797         $outcomegradeitem->cmid = 0;
1798         $outcomegradeitem->courseid = $course->id;
1799         $outcomegradeitem->aggregationcoef = 0;
1800         $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
1801         $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
1802         $outcomegradeitem->scaleid = $outcome->scaleid;
1803         $outcomegradeitem->insert();
1805         $assignmentgradeitem = grade_item::fetch(
1806             array(
1807                 'itemtype' => 'mod',
1808                 'itemmodule' => 'assign',
1809                 'iteminstance' => $assign->id,
1810                 'itemnumber' => 0,
1811                 'courseid' => $course->id
1812             )
1813         );
1814         $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
1815         $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
1817         // Test admin user can see the complete hidden activity.
1818         $result = core_course_external::get_course_module($assign->cmid);
1819         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1821         $this->assertCount(0, $result['warnings']);
1822         // Test we retrieve all the fields.
1823         $this->assertCount(28, $result['cm']);
1824         $this->assertEquals($record['name'], $result['cm']['name']);
1825         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1826         $this->assertEquals(100, $result['cm']['grade']);
1827         $this->assertEquals(0.0, $result['cm']['gradepass']);
1828         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
1829         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
1830         $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
1832         $student = $this->getDataGenerator()->create_user();
1833         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1835         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1836         $this->setUser($student);
1838         // The user shouldn't be able to see the activity.
1839         try {
1840             core_course_external::get_course_module($assign->cmid);
1841             $this->fail('Exception expected due to invalid permissions.');
1842         } catch (moodle_exception $e) {
1843             $this->assertEquals('requireloginerror', $e->errorcode);
1844         }
1846         // Make module visible.
1847         set_coursemodule_visible($assign->cmid, 1);
1849         // Test student user.
1850         $result = core_course_external::get_course_module($assign->cmid);
1851         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1853         $this->assertCount(0, $result['warnings']);
1854         // Test we retrieve only the few files we can see.
1855         $this->assertCount(11, $result['cm']);
1856         $this->assertEquals($assign->cmid, $result['cm']['id']);
1857         $this->assertEquals($course->id, $result['cm']['course']);
1858         $this->assertEquals('assign', $result['cm']['modname']);
1859         $this->assertEquals($assign->id, $result['cm']['instance']);
1861     }
1863     /**
1864      * Test get_course_module_by_instance
1865      */
1866     public function test_get_course_module_by_instance() {
1867         global $DB;
1869         $this->resetAfterTest(true);
1871         $this->setAdminUser();
1872         $course = self::getDataGenerator()->create_course();
1873         $record = array(
1874             'course' => $course->id,
1875             'name' => 'First quiz',
1876             'grade' => 90.00
1877         );
1878         $options = array(
1879             'idnumber' => 'ABC',
1880             'visible' => 0
1881         );
1882         // Hidden activity.
1883         $quiz = self::getDataGenerator()->create_module('quiz', $record, $options);
1885         // Test admin user can see the complete hidden activity.
1886         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
1887         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1889         $this->assertCount(0, $result['warnings']);
1890         // Test we retrieve all the fields.
1891         $this->assertCount(26, $result['cm']);
1892         $this->assertEquals($record['name'], $result['cm']['name']);
1893         $this->assertEquals($record['grade'], $result['cm']['grade']);
1894         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1896         $student = $this->getDataGenerator()->create_user();
1897         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1899         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1900         $this->setUser($student);
1902         // The user shouldn't be able to see the activity.
1903         try {
1904             core_course_external::get_course_module_by_instance('quiz', $quiz->id);
1905             $this->fail('Exception expected due to invalid permissions.');
1906         } catch (moodle_exception $e) {
1907             $this->assertEquals('requireloginerror', $e->errorcode);
1908         }
1910         // Make module visible.
1911         set_coursemodule_visible($quiz->cmid, 1);
1913         // Test student user.
1914         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
1915         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1917         $this->assertCount(0, $result['warnings']);
1918         // Test we retrieve only the few files we can see.
1919         $this->assertCount(11, $result['cm']);
1920         $this->assertEquals($quiz->cmid, $result['cm']['id']);
1921         $this->assertEquals($course->id, $result['cm']['course']);
1922         $this->assertEquals('quiz', $result['cm']['modname']);
1923         $this->assertEquals($quiz->id, $result['cm']['instance']);
1925         // Try with an invalid module name.
1926         try {
1927             core_course_external::get_course_module_by_instance('abc', $quiz->id);
1928             $this->fail('Exception expected due to invalid module name.');
1929         } catch (dml_read_exception $e) {
1930             $this->assertEquals('dmlreadexception', $e->errorcode);
1931         }
1933     }
1935     /**
1936      * Test get_activities_overview
1937      */
1938     public function test_get_activities_overview() {
1939         global $USER;
1941         $this->resetAfterTest();
1942         $course1 = self::getDataGenerator()->create_course();
1943         $course2 = self::getDataGenerator()->create_course();
1945         // Create a viewer user.
1946         $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
1947         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1948         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1950         // Create two forums - one in each course.
1951         $record = new stdClass();
1952         $record->course = $course1->id;
1953         $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
1954         $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
1956         $this->setAdminUser();
1957         // A standard post in the forum.
1958         $record = new stdClass();
1959         $record->course = $course1->id;
1960         $record->userid = $USER->id;
1961         $record->forum = $forum1->id;
1962         $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1964         $this->setUser($viewer->id);
1965         $courses = array($course1->id , $course2->id);
1967         $result = core_course_external::get_activities_overview($courses);
1968         $this->assertDebuggingCalledCount(8);
1969         $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
1971         // There should be one entry for course1, and no others.
1972         $this->assertCount(1, $result['courses']);
1973         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1974         // Check expected overview data for the module.
1975         $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
1976         $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
1977     }
1979     /**
1980      * Test get_user_navigation_options
1981      */
1982     public function test_get_user_navigation_options() {
1983         global $USER;
1985         $this->resetAfterTest();
1986         $course1 = self::getDataGenerator()->create_course();
1987         $course2 = self::getDataGenerator()->create_course();
1989         // Create a viewer user.
1990         $viewer = self::getDataGenerator()->create_user();
1991         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1992         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1994         $this->setUser($viewer->id);
1995         $courses = array($course1->id , $course2->id, SITEID);
1997         $result = core_course_external::get_user_navigation_options($courses);
1998         $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
2000         $this->assertCount(0, $result['warnings']);
2001         $this->assertCount(3, $result['courses']);
2003         foreach ($result['courses'] as $course) {
2004             $navoptions = new stdClass;
2005             foreach ($course['options'] as $option) {
2006                 $navoptions->{$option['name']} = $option['available'];
2007             }
2008             $this->assertCount(9, $course['options']);
2009             if ($course['id'] == SITEID) {
2010                 $this->assertTrue($navoptions->blogs);
2011                 $this->assertFalse($navoptions->notes);
2012                 $this->assertFalse($navoptions->participants);
2013                 $this->assertTrue($navoptions->badges);
2014                 $this->assertTrue($navoptions->tags);
2015                 $this->assertFalse($navoptions->grades);
2016                 $this->assertFalse($navoptions->search);
2017                 $this->assertTrue($navoptions->calendar);
2018                 $this->assertTrue($navoptions->competencies);
2019             } else {
2020                 $this->assertTrue($navoptions->blogs);
2021                 $this->assertFalse($navoptions->notes);
2022                 $this->assertTrue($navoptions->participants);
2023                 $this->assertTrue($navoptions->badges);
2024                 $this->assertFalse($navoptions->tags);
2025                 $this->assertTrue($navoptions->grades);
2026                 $this->assertFalse($navoptions->search);
2027                 $this->assertFalse($navoptions->calendar);
2028                 $this->assertTrue($navoptions->competencies);
2029             }
2030         }
2031     }
2033     /**
2034      * Test get_user_administration_options
2035      */
2036     public function test_get_user_administration_options() {
2037         global $USER;
2039         $this->resetAfterTest();
2040         $course1 = self::getDataGenerator()->create_course();
2041         $course2 = self::getDataGenerator()->create_course();
2043         // Create a viewer user.
2044         $viewer = self::getDataGenerator()->create_user();
2045         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2046         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2048         $this->setUser($viewer->id);
2049         $courses = array($course1->id , $course2->id, SITEID);
2051         $result = core_course_external::get_user_administration_options($courses);
2052         $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
2054         $this->assertCount(0, $result['warnings']);
2055         $this->assertCount(3, $result['courses']);
2057         foreach ($result['courses'] as $course) {
2058             $adminoptions = new stdClass;
2059             foreach ($course['options'] as $option) {
2060                 $adminoptions->{$option['name']} = $option['available'];
2061             }
2062             if ($course['id'] == SITEID) {
2063                 $this->assertCount(16, $course['options']);
2064                 $this->assertFalse($adminoptions->update);
2065                 $this->assertFalse($adminoptions->filters);
2066                 $this->assertFalse($adminoptions->reports);
2067                 $this->assertFalse($adminoptions->backup);
2068                 $this->assertFalse($adminoptions->restore);
2069                 $this->assertFalse($adminoptions->files);
2070                 $this->assertFalse(!isset($adminoptions->tags));
2071                 $this->assertFalse($adminoptions->gradebook);
2072                 $this->assertFalse($adminoptions->outcomes);
2073                 $this->assertFalse($adminoptions->badges);
2074                 $this->assertFalse($adminoptions->import);
2075                 $this->assertFalse($adminoptions->publish);
2076                 $this->assertFalse($adminoptions->reset);
2077                 $this->assertFalse($adminoptions->roles);
2078                 $this->assertFalse($adminoptions->editcompletion);
2079             } else {
2080                 $this->assertCount(15, $course['options']);
2081                 $this->assertFalse($adminoptions->update);
2082                 $this->assertFalse($adminoptions->filters);
2083                 $this->assertFalse($adminoptions->reports);
2084                 $this->assertFalse($adminoptions->backup);
2085                 $this->assertFalse($adminoptions->restore);
2086                 $this->assertFalse($adminoptions->files);
2087                 $this->assertFalse($adminoptions->tags);
2088                 $this->assertFalse($adminoptions->gradebook);
2089                 $this->assertFalse($adminoptions->outcomes);
2090                 $this->assertTrue($adminoptions->badges);
2091                 $this->assertFalse($adminoptions->import);
2092                 $this->assertFalse($adminoptions->publish);
2093                 $this->assertFalse($adminoptions->reset);
2094                 $this->assertFalse($adminoptions->roles);
2095                 $this->assertFalse($adminoptions->editcompletion);
2096             }
2097         }
2098     }
2100     /**
2101      * Test get_courses_by_fields
2102      */
2103     public function test_get_courses_by_field() {
2104         global $DB;
2105         $this->resetAfterTest(true);
2107         $category1 = self::getDataGenerator()->create_category(array('name' => 'Cat 1'));
2108         $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
2109         $course1 = self::getDataGenerator()->create_course(
2110             array('category' => $category1->id, 'shortname' => 'c1', 'format' => 'topics'));
2111         $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
2113         $student1 = self::getDataGenerator()->create_user();
2114         $user1 = self::getDataGenerator()->create_user();
2115         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2116         self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
2117         self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
2119         self::setAdminUser();
2120         // As admins, we should be able to retrieve everything.
2121         $result = core_course_external::get_courses_by_field();
2122         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2123         $this->assertCount(3, $result['courses']);
2124         // Expect to receive all the fields.
2125         $this->assertCount(37, $result['courses'][0]);
2126         $this->assertCount(38, $result['courses'][1]);  // One more field because is not the site course.
2127         $this->assertCount(38, $result['courses'][2]);  // One more field because is not the site course.
2129         $result = core_course_external::get_courses_by_field('id', $course1->id);
2130         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2131         $this->assertCount(1, $result['courses']);
2132         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2133         // Expect to receive all the fields.
2134         $this->assertCount(38, $result['courses'][0]);
2135         // Check default values for course format topics.
2136         $this->assertCount(2, $result['courses'][0]['courseformatoptions']);
2137         foreach ($result['courses'][0]['courseformatoptions'] as $option) {
2138             if ($option['name'] == 'hiddensections') {
2139                 $this->assertEquals(0, $option['value']);
2140             } else {
2141                 $this->assertEquals('coursedisplay', $option['name']);
2142                 $this->assertEquals(0, $option['value']);
2143             }
2144         }
2146         $result = core_course_external::get_courses_by_field('id', $course2->id);
2147         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2148         $this->assertCount(1, $result['courses']);
2149         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2151         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2152         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2153         $this->assertCount(2, $result['courses']);
2155         // Check default filters.
2156         $this->assertCount(3, $result['courses'][0]['filters']);
2157         $this->assertCount(3, $result['courses'][1]['filters']);
2159         $result = core_course_external::get_courses_by_field('category', $category1->id);
2160         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2161         $this->assertCount(1, $result['courses']);
2162         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2163         $this->assertEquals('Cat 1', $result['courses'][0]['categoryname']);
2165         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2166         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2167         $this->assertCount(1, $result['courses']);
2168         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2170         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2171         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2172         $this->assertCount(1, $result['courses']);
2173         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2175         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2176         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2177         $this->assertCount(0, $result['courses']);
2179         // Change filter value.
2180         filter_set_local_state('mediaplugin', context_course::instance($course1->id)->id, TEXTFILTER_OFF);
2182         self::setUser($student1);
2183         // All visible courses  (including front page) for normal student.
2184         $result = core_course_external::get_courses_by_field();
2185         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2186         $this->assertCount(2, $result['courses']);
2187         $this->assertCount(30, $result['courses'][0]);
2188         $this->assertCount(31, $result['courses'][1]);  // One field more (course format options), not present in site course.
2190         $result = core_course_external::get_courses_by_field('id', $course1->id);
2191         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2192         $this->assertCount(1, $result['courses']);
2193         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2194         // Expect to receive all the files that a student can see.
2195         $this->assertCount(31, $result['courses'][0]);
2197         // Check default filters.
2198         $filters = $result['courses'][0]['filters'];
2199         $this->assertCount(3, $filters);
2200         $found = false;
2201         foreach ($filters as $filter) {
2202             if ($filter['filter'] == 'mediaplugin' and $filter['localstate'] == TEXTFILTER_OFF) {
2203                 $found = true;
2204             }
2205         }
2206         $this->assertTrue($found);
2208         // Course 2 is not visible.
2209         $result = core_course_external::get_courses_by_field('id', $course2->id);
2210         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2211         $this->assertCount(0, $result['courses']);
2213         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2214         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2215         $this->assertCount(1, $result['courses']);
2217         $result = core_course_external::get_courses_by_field('category', $category1->id);
2218         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2219         $this->assertCount(1, $result['courses']);
2220         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2222         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2223         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2224         $this->assertCount(1, $result['courses']);
2225         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2227         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2228         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2229         $this->assertCount(0, $result['courses']);
2231         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2232         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2233         $this->assertCount(0, $result['courses']);
2235         self::setUser($user1);
2236         // All visible courses (including front page) for authenticated user.
2237         $result = core_course_external::get_courses_by_field();
2238         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2239         $this->assertCount(2, $result['courses']);
2240         $this->assertCount(30, $result['courses'][0]);  // Site course.
2241         $this->assertCount(13, $result['courses'][1]);  // Only public information, not enrolled.
2243         $result = core_course_external::get_courses_by_field('id', $course1->id);
2244         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2245         $this->assertCount(1, $result['courses']);
2246         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2247         // Expect to receive all the files that a authenticated can see.
2248         $this->assertCount(13, $result['courses'][0]);
2250         // Course 2 is not visible.
2251         $result = core_course_external::get_courses_by_field('id', $course2->id);
2252         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2253         $this->assertCount(0, $result['courses']);
2255         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2256         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2257         $this->assertCount(1, $result['courses']);
2259         $result = core_course_external::get_courses_by_field('category', $category1->id);
2260         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2261         $this->assertCount(1, $result['courses']);
2262         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2264         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2265         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2266         $this->assertCount(1, $result['courses']);
2267         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2269         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2270         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2271         $this->assertCount(0, $result['courses']);
2273         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2274         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2275         $this->assertCount(0, $result['courses']);
2276     }
2278     public function test_get_courses_by_field_invalid_field() {
2279         $this->expectException('invalid_parameter_exception');
2280         $result = core_course_external::get_courses_by_field('zyx', 'x');
2281     }
2283     public function test_get_courses_by_field_invalid_courses() {
2284         $result = core_course_external::get_courses_by_field('id', '-1');
2285         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2286         $this->assertCount(0, $result['courses']);
2287     }
2289     /**
2290      * Test get_courses_by_field_invalid_theme_and_lang
2291      */
2292     public function test_get_courses_by_field_invalid_theme_and_lang() {
2293         $this->resetAfterTest(true);
2294         $this->setAdminUser();
2296         $course = self::getDataGenerator()->create_course(array('theme' => 'kkt', 'lang' => 'kkl'));
2297         $result = core_course_external::get_courses_by_field('id', $course->id);
2298         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2299         $this->assertEmpty($result['courses']['0']['theme']);
2300         $this->assertEmpty($result['courses']['0']['lang']);
2301     }
2304     public function test_check_updates() {
2305         global $DB;
2306         $this->resetAfterTest(true);
2307         $this->setAdminUser();
2309         // Create different types of activities.
2310         $course  = self::getDataGenerator()->create_course();
2311         $tocreate = array('assign', 'book', 'choice', 'folder', 'forum', 'glossary', 'imscp', 'label', 'lti', 'page', 'quiz',
2312                             'resource', 'scorm', 'survey', 'url', 'wiki');
2314         $modules = array();
2315         foreach ($tocreate as $modname) {
2316             $modules[$modname]['instance'] = $this->getDataGenerator()->create_module($modname, array('course' => $course->id));
2317             $modules[$modname]['cm'] = get_coursemodule_from_id(false, $modules[$modname]['instance']->cmid);
2318             $modules[$modname]['context'] = context_module::instance($modules[$modname]['instance']->cmid);
2319         }
2321         $student = self::getDataGenerator()->create_user();
2322         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2323         self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
2324         $this->setUser($student);
2326         $since = time();
2327         $this->waitForSecond();
2328         $params = array();
2329         foreach ($modules as $modname => $data) {
2330             $params[$data['cm']->id] = array(
2331                 'contextlevel' => 'module',
2332                 'id' => $data['cm']->id,
2333                 'since' => $since
2334             );
2335         }
2337         // Check there is nothing updated because modules are fresh new.
2338         $result = core_course_external::check_updates($course->id, $params);
2339         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2340         $this->assertCount(0, $result['instances']);
2341         $this->assertCount(0, $result['warnings']);
2343         // Test with get_updates_since the same data.
2344         $result = core_course_external::get_updates_since($course->id, $since);
2345         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2346         $this->assertCount(0, $result['instances']);
2347         $this->assertCount(0, $result['warnings']);
2349         // Update a module after a second.
2350         $this->waitForSecond();
2351         set_coursemodule_name($modules['forum']['cm']->id, 'New forum name');
2353         $found = false;
2354         $result = core_course_external::check_updates($course->id, $params);
2355         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2356         $this->assertCount(1, $result['instances']);
2357         $this->assertCount(0, $result['warnings']);
2358         foreach ($result['instances'] as $module) {
2359             foreach ($module['updates'] as $update) {
2360                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2361                     $found = true;
2362                 }
2363             }
2364         }
2365         $this->assertTrue($found);
2367         // Test with get_updates_since the same data.
2368         $result = core_course_external::get_updates_since($course->id, $since);
2369         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2370         $this->assertCount(1, $result['instances']);
2371         $this->assertCount(0, $result['warnings']);
2372         $found = false;
2373         $this->assertCount(1, $result['instances']);
2374         $this->assertCount(0, $result['warnings']);
2375         foreach ($result['instances'] as $module) {
2376             foreach ($module['updates'] as $update) {
2377                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2378                     $found = true;
2379                 }
2380             }
2381         }
2382         $this->assertTrue($found);
2384         // Do not retrieve the configuration field.
2385         $filter = array('files');
2386         $found = false;
2387         $result = core_course_external::check_updates($course->id, $params, $filter);
2388         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2389         $this->assertCount(0, $result['instances']);
2390         $this->assertCount(0, $result['warnings']);
2391         $this->assertFalse($found);
2393         // Add invalid cmid.
2394         $params[] = array(
2395             'contextlevel' => 'module',
2396             'id' => -2,
2397             'since' => $since
2398         );
2399         $result = core_course_external::check_updates($course->id, $params);
2400         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2401         $this->assertCount(1, $result['warnings']);
2402         $this->assertEquals(-2, $result['warnings'][0]['itemid']);
2403     }
2405     /**
2406      * Test cases for the get_enrolled_courses_by_timeline_classification test.
2407      */
2408     public function get_get_enrolled_courses_by_timeline_classification_test_cases() {
2409         $now = time();
2410         $day = 86400;
2412         $coursedata = [
2413             [
2414                 'shortname' => 'apast',
2415                 'startdate' => $now - ($day * 2),
2416                 'enddate' => $now - $day
2417             ],
2418             [
2419                 'shortname' => 'bpast',
2420                 'startdate' => $now - ($day * 2),
2421                 'enddate' => $now - $day
2422             ],
2423             [
2424                 'shortname' => 'cpast',
2425                 'startdate' => $now - ($day * 2),
2426                 'enddate' => $now - $day
2427             ],
2428             [
2429                 'shortname' => 'dpast',
2430                 'startdate' => $now - ($day * 2),
2431                 'enddate' => $now - $day
2432             ],
2433             [
2434                 'shortname' => 'epast',
2435                 'startdate' => $now - ($day * 2),
2436                 'enddate' => $now - $day
2437             ],
2438             [
2439                 'shortname' => 'ainprogress',
2440                 'startdate' => $now - $day,
2441                 'enddate' => $now + $day
2442             ],
2443             [
2444                 'shortname' => 'binprogress',
2445                 'startdate' => $now - $day,
2446                 'enddate' => $now + $day
2447             ],
2448             [
2449                 'shortname' => 'cinprogress',
2450                 'startdate' => $now - $day,
2451                 'enddate' => $now + $day
2452             ],
2453             [
2454                 'shortname' => 'dinprogress',
2455                 'startdate' => $now - $day,
2456                 'enddate' => $now + $day
2457             ],
2458             [
2459                 'shortname' => 'einprogress',
2460                 'startdate' => $now - $day,
2461                 'enddate' => $now + $day
2462             ],
2463             [
2464                 'shortname' => 'afuture',
2465                 'startdate' => $now + $day
2466             ],
2467             [
2468                 'shortname' => 'bfuture',
2469                 'startdate' => $now + $day
2470             ],
2471             [
2472                 'shortname' => 'cfuture',
2473                 'startdate' => $now + $day
2474             ],
2475             [
2476                 'shortname' => 'dfuture',
2477                 'startdate' => $now + $day
2478             ],
2479             [
2480                 'shortname' => 'efuture',
2481                 'startdate' => $now + $day
2482             ]
2483         ];
2485         // Raw enrolled courses result set should be returned in this order:
2486         // afuture, ainprogress, apast, bfuture, binprogress, bpast, cfuture, cinprogress, cpast,
2487         // dfuture, dinprogress, dpast, efuture, einprogress, epast
2488         //
2489         // By classification the offset values for each record should be:
2490         // COURSE_TIMELINE_FUTURE
2491         // 0 (afuture), 3 (bfuture), 6 (cfuture), 9 (dfuture), 12 (efuture)
2492         // COURSE_TIMELINE_INPROGRESS
2493         // 1 (ainprogress), 4 (binprogress), 7 (cinprogress), 10 (dinprogress), 13 (einprogress)
2494         // COURSE_TIMELINE_PAST
2495         // 2 (apast), 5 (bpast), 8 (cpast), 11 (dpast), 14 (epast).
2496         //
2497         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2498         // filtering is done.
2499         // E.g. In our example if an offset of 2 is given then it would mean the first
2500         // two courses (afuture, ainprogress) are ignored.
2501         return [
2502             'empty set' => [
2503                 'coursedata' => [],
2504                 'classification' => 'future',
2505                 'limit' => 2,
2506                 'offset' => 0,
2507                 'expectedcourses' => [],
2508                 'expectednextoffset' => 0
2509             ],
2510             // COURSE_TIMELINE_FUTURE.
2511             'future not limit no offset' => [
2512                 'coursedata' => $coursedata,
2513                 'classification' => 'future',
2514                 'limit' => 0,
2515                 'offset' => 0,
2516                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2517                 'expectednextoffset' => 15
2518             ],
2519             'future no offset' => [
2520                 'coursedata' => $coursedata,
2521                 'classification' => 'future',
2522                 'limit' => 2,
2523                 'offset' => 0,
2524                 'expectedcourses' => ['afuture', 'bfuture'],
2525                 'expectednextoffset' => 4
2526             ],
2527             'future offset' => [
2528                 'coursedata' => $coursedata,
2529                 'classification' => 'future',
2530                 'limit' => 2,
2531                 'offset' => 2,
2532                 'expectedcourses' => ['bfuture', 'cfuture'],
2533                 'expectednextoffset' => 7
2534             ],
2535             'future exact limit' => [
2536                 'coursedata' => $coursedata,
2537                 'classification' => 'future',
2538                 'limit' => 5,
2539                 'offset' => 0,
2540                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2541                 'expectednextoffset' => 13
2542             ],
2543             'future limit less results' => [
2544                 'coursedata' => $coursedata,
2545                 'classification' => 'future',
2546                 'limit' => 10,
2547                 'offset' => 0,
2548                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2549                 'expectednextoffset' => 15
2550             ],
2551             'future limit less results with offset' => [
2552                 'coursedata' => $coursedata,
2553                 'classification' => 'future',
2554                 'limit' => 10,
2555                 'offset' => 5,
2556                 'expectedcourses' => ['cfuture', 'dfuture', 'efuture'],
2557                 'expectednextoffset' => 15
2558             ],
2559             'all no limit or offset' => [
2560                 'coursedata' => $coursedata,
2561                 'classification' => 'all',
2562                 'limit' => 0,
2563                 'offset' => 0,
2564                 'expectedcourses' => [
2565                     'afuture',
2566                     'ainprogress',
2567                     'apast',
2568                     'bfuture',
2569                     'binprogress',
2570                     'bpast',
2571                     'cfuture',
2572                     'cinprogress',
2573                     'cpast',
2574                     'dfuture',
2575                     'dinprogress',
2576                     'dpast',
2577                     'efuture',
2578                     'einprogress',
2579                     'epast'
2580                 ],
2581                 'expectednextoffset' => 15
2582             ],
2583             'all limit no offset' => [
2584                 'coursedata' => $coursedata,
2585                 'classification' => 'all',
2586                 'limit' => 5,
2587                 'offset' => 0,
2588                 'expectedcourses' => [
2589                     'afuture',
2590                     'ainprogress',
2591                     'apast',
2592                     'bfuture',
2593                     'binprogress'
2594                 ],
2595                 'expectednextoffset' => 5
2596             ],
2597             'all limit and offset' => [
2598                 'coursedata' => $coursedata,
2599                 'classification' => 'all',
2600                 'limit' => 5,
2601                 'offset' => 5,
2602                 'expectedcourses' => [
2603                     'bpast',
2604                     'cfuture',
2605                     'cinprogress',
2606                     'cpast',
2607                     'dfuture'
2608                 ],
2609                 'expectednextoffset' => 10
2610             ],
2611             'all offset past result set' => [
2612                 'coursedata' => $coursedata,
2613                 'classification' => 'all',
2614                 'limit' => 5,
2615                 'offset' => 50,
2616                 'expectedcourses' => [],
2617                 'expectednextoffset' => 50
2618             ],
2619         ];
2620     }
2622     /**
2623      * Test the get_enrolled_courses_by_timeline_classification function.
2624      *
2625      * @dataProvider get_get_enrolled_courses_by_timeline_classification_test_cases()
2626      * @param array $coursedata Courses to create
2627      * @param string $classification Timeline classification
2628      * @param int $limit Maximum number of results
2629      * @param int $offset Offset the unfiltered courses result set by this amount
2630      * @param array $expectedcourses Expected courses in result
2631      * @param int $expectednextoffset Expected next offset value in result
2632      */
2633     public function test_get_enrolled_courses_by_timeline_classification(
2634         $coursedata,
2635         $classification,
2636         $limit,
2637         $offset,
2638         $expectedcourses,
2639         $expectednextoffset
2640     ) {
2641         $this->resetAfterTest();
2642         $generator = $this->getDataGenerator();
2644         $courses = array_map(function($coursedata) use ($generator) {
2645             return $generator->create_course($coursedata);
2646         }, $coursedata);
2648         $student = $generator->create_user();
2650         foreach ($courses as $course) {
2651             $generator->enrol_user($student->id, $course->id, 'student');
2652         }
2654         $this->setUser($student);
2656         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2657         // filtering is done.
2658         // E.g. In our example if an offset of 2 is given then it would mean the first
2659         // two courses (afuture, ainprogress) are ignored.
2660         $result = core_course_external::get_enrolled_courses_by_timeline_classification(
2661             $classification,
2662             $limit,
2663             $offset,
2664             'shortname ASC'
2665         );
2666         $result = external_api::clean_returnvalue(
2667             core_course_external::get_enrolled_courses_by_timeline_classification_returns(),
2668             $result
2669         );
2671         $actual = array_map(function($course) {
2672             return $course['shortname'];
2673         }, $result['courses']);
2675         $this->assertEquals($expectedcourses, $actual);
2676         $this->assertEquals($expectednextoffset, $result['nextoffset']);
2677     }