9015dbe654ab45e6ec4bc9d8ab1c6677509cc3ab
[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);
205         // Retrieve category1 + sub-categories except not visible ones
206         $categories = core_course_external::get_categories(array(
207             array('key' => 'id', 'value' => $category1->id),
208             array('key' => 'visible', 'value' => 1)), 1);
210         // We need to execute the return values cleaning process to simulate the web service server.
211         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
213         // Check we retrieve the good total number of categories.
214         $this->assertEquals(2, count($categories));
216         // Check the return values
217         foreach ($categories as $category) {
218             $generatedcat = $generatedcats[$category['id']];
219             $this->assertEquals($category['idnumber'], $generatedcat->idnumber);
220             $this->assertEquals($category['name'], $generatedcat->name);
221             // Description was converted to the HTML format.
222             $this->assertEquals($category['description'], format_text($generatedcat->description, FORMAT_MOODLE, array('para' => false)));
223             $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
224         }
226         // Check categories by ids.
227         $ids = implode(',', array_keys($generatedcats));
228         $categories = core_course_external::get_categories(array(
229             array('key' => 'ids', 'value' => $ids)), 0);
231         // We need to execute the return values cleaning process to simulate the web service server.
232         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
234         // Check we retrieve the good total number of categories.
235         $this->assertEquals(6, count($categories));
236         // Check ids.
237         $returnedids = [];
238         foreach ($categories as $category) {
239             $returnedids[] = $category['id'];
240         }
241         // Sort the arrays upon comparision.
242         $this->assertEquals(array_keys($generatedcats), $returnedids, '', 0.0, 10, true);
244         // Check different params.
245         $categories = core_course_external::get_categories(array(
246             array('key' => 'id', 'value' => $category1->id),
247             array('key' => 'ids', 'value' => $category1->id),
248             array('key' => 'idnumber', 'value' => $category1->idnumber),
249             array('key' => 'visible', 'value' => 1)), 0);
251         // We need to execute the return values cleaning process to simulate the web service server.
252         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
254         $this->assertEquals(1, count($categories));
256         // Same query, but forcing a parameters clean.
257         $categories = core_course_external::get_categories(array(
258             array('key' => 'id', 'value' => "$category1->id"),
259             array('key' => 'idnumber', 'value' => $category1->idnumber),
260             array('key' => 'name', 'value' => $category1->name . "<br/>"),
261             array('key' => 'visible', 'value' => '1')), 0);
262         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
264         $this->assertEquals(1, count($categories));
266         // Retrieve categories from parent.
267         $categories = core_course_external::get_categories(array(
268             array('key' => 'parent', 'value' => $category3->id)), 1);
269         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
271         $this->assertEquals(2, count($categories));
273         // Retrieve all categories.
274         $categories = core_course_external::get_categories();
276         // We need to execute the return values cleaning process to simulate the web service server.
277         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
279         $this->assertEquals($DB->count_records('course_categories'), count($categories));
281         // Call without required capability (it will fail cause of the search on idnumber).
282         $this->unassignUserCapability('moodle/category:manage', $context->id, $roleid);
283         $this->expectException('moodle_exception');
284         $categories = core_course_external::get_categories(array(
285             array('key' => 'id', 'value' => $category1->id),
286             array('key' => 'idnumber', 'value' => $category1->idnumber),
287             array('key' => 'visible', 'value' => 1)), 0);
288     }
290     /**
291      * Test update_categories
292      */
293     public function test_update_categories() {
294         global $DB;
296         $this->resetAfterTest(true);
298         // Set the required capabilities by the external function
299         $contextid = context_system::instance()->id;
300         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
302         // Create base categories.
303         $category1data['idnumber'] = 'idnumbercat1';
304         $category1data['name'] = 'Category 1 for PHPunit test';
305         $category1data['description'] = 'Category 1 description';
306         $category1data['descriptionformat'] = FORMAT_MOODLE;
307         $category1  = self::getDataGenerator()->create_category($category1data);
308         $category2  = self::getDataGenerator()->create_category(
309                 array('parent' => $category1->id));
310         $category3  = self::getDataGenerator()->create_category();
311         $category4  = self::getDataGenerator()->create_category(
312                 array('parent' => $category3->id));
313         $category5  = self::getDataGenerator()->create_category(
314                 array('parent' => $category4->id));
316         // We update all category1 attribut.
317         // Then we move cat4 and cat5 parent: cat3 => cat1
318         $categories = array(
319             array('id' => $category1->id,
320                 'name' => $category1->name . '_updated',
321                 'idnumber' => $category1->idnumber . '_updated',
322                 'description' => $category1->description . '_updated',
323                 'descriptionformat' => FORMAT_HTML,
324                 'theme' => $category1->theme),
325             array('id' => $category4->id, 'parent' => $category1->id));
327         core_course_external::update_categories($categories);
329         // Check the values were updated.
330         $dbcategories = $DB->get_records_select('course_categories',
331                 'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
332                 . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
333         $this->assertEquals($category1->name . '_updated',
334                 $dbcategories[$category1->id]->name);
335         $this->assertEquals($category1->idnumber . '_updated',
336                 $dbcategories[$category1->id]->idnumber);
337         $this->assertEquals($category1->description . '_updated',
338                 $dbcategories[$category1->id]->description);
339         $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
341         // Check that category4 and category5 have been properly moved.
342         $this->assertEquals('/' . $category1->id . '/' . $category4->id,
343                 $dbcategories[$category4->id]->path);
344         $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
345                 $dbcategories[$category5->id]->path);
347         // Call without required capability.
348         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
349         $this->expectException('required_capability_exception');
350         core_course_external::update_categories($categories);
351     }
353     /**
354      * Test create_courses
355      */
356     public function test_create_courses() {
357         global $DB;
359         $this->resetAfterTest(true);
361         // Enable course completion.
362         set_config('enablecompletion', 1);
363         // Enable course themes.
364         set_config('allowcoursethemes', 1);
366         // Set the required capabilities by the external function
367         $contextid = context_system::instance()->id;
368         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
369         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
371         $category  = self::getDataGenerator()->create_category();
373         // Create base categories.
374         $course1['fullname'] = 'Test course 1';
375         $course1['shortname'] = 'Testcourse1';
376         $course1['categoryid'] = $category->id;
377         $course2['fullname'] = 'Test course 2';
378         $course2['shortname'] = 'Testcourse2';
379         $course2['categoryid'] = $category->id;
380         $course2['idnumber'] = 'testcourse2idnumber';
381         $course2['summary'] = 'Description for course 2';
382         $course2['summaryformat'] = FORMAT_MOODLE;
383         $course2['format'] = 'weeks';
384         $course2['showgrades'] = 1;
385         $course2['newsitems'] = 3;
386         $course2['startdate'] = 1420092000; // 01/01/2015.
387         $course2['enddate'] = 1422669600; // 01/31/2015.
388         $course2['numsections'] = 4;
389         $course2['maxbytes'] = 100000;
390         $course2['showreports'] = 1;
391         $course2['visible'] = 0;
392         $course2['hiddensections'] = 0;
393         $course2['groupmode'] = 0;
394         $course2['groupmodeforce'] = 0;
395         $course2['defaultgroupingid'] = 0;
396         $course2['enablecompletion'] = 1;
397         $course2['completionnotify'] = 1;
398         $course2['lang'] = 'en';
399         $course2['forcetheme'] = 'bootstrapbase';
400         $course3['fullname'] = 'Test course 3';
401         $course3['shortname'] = 'Testcourse3';
402         $course3['categoryid'] = $category->id;
403         $course3['format'] = 'topics';
404         $course3options = array('numsections' => 8,
405             'hiddensections' => 1,
406             'coursedisplay' => 1);
407         $course3['courseformatoptions'] = array();
408         foreach ($course3options as $key => $value) {
409             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
410         }
411         $courses = array($course1, $course2, $course3);
413         $createdcourses = core_course_external::create_courses($courses);
415         // We need to execute the return values cleaning process to simulate the web service server.
416         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
418         // Check that right number of courses were created.
419         $this->assertEquals(3, count($createdcourses));
421         // Check that the courses were correctly created.
422         foreach ($createdcourses as $createdcourse) {
423             $courseinfo = course_get_format($createdcourse['id'])->get_course();
425             if ($createdcourse['shortname'] == $course2['shortname']) {
426                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
427                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
428                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
429                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
430                 $this->assertEquals($courseinfo->summary, $course2['summary']);
431                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
432                 $this->assertEquals($courseinfo->format, $course2['format']);
433                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
434                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
435                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
436                 $this->assertEquals($courseinfo->enddate, $course2['enddate']);
437                 $this->assertEquals($courseinfo->numsections, $course2['numsections']);
438                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
439                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
440                 $this->assertEquals($courseinfo->visible, $course2['visible']);
441                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
442                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
443                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
444                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
445                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
446                 $this->assertEquals($courseinfo->lang, $course2['lang']);
447                 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
449                 // We enabled completion at the beginning of the test.
450                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
452             } else if ($createdcourse['shortname'] == $course1['shortname']) {
453                 $courseconfig = get_config('moodlecourse');
454                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
455                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
456                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
457                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
458                 $this->assertEquals($courseinfo->format, $courseconfig->format);
459                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
460                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
461                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
462                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
463                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
464                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
465                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
466             } else if ($createdcourse['shortname'] == $course3['shortname']) {
467                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
468                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
469                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
470                 $this->assertEquals($courseinfo->format, $course3['format']);
471                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
472                 $this->assertEquals($courseinfo->numsections, $course3options['numsections']);
473                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
474             } else {
475                 throw moodle_exception('Unexpected shortname');
476             }
477         }
479         // Call without required capability
480         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
481         $this->expectException('required_capability_exception');
482         $createdsubcats = core_course_external::create_courses($courses);
483     }
485     /**
486      * Test delete_courses
487      */
488     public function test_delete_courses() {
489         global $DB, $USER;
491         $this->resetAfterTest(true);
493         // Admin can delete a course.
494         $this->setAdminUser();
495         // Validate_context() will fail as the email is not set by $this->setAdminUser().
496         $USER->email = 'emailtopass@example.com';
498         $course1  = self::getDataGenerator()->create_course();
499         $course2  = self::getDataGenerator()->create_course();
500         $course3  = self::getDataGenerator()->create_course();
502         // Delete courses.
503         $result = core_course_external::delete_courses(array($course1->id, $course2->id));
504         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
505         // Check for 0 warnings.
506         $this->assertEquals(0, count($result['warnings']));
508         // Check $course 1 and 2 are deleted.
509         $notdeletedcount = $DB->count_records_select('course',
510             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
511         $this->assertEquals(0, $notdeletedcount);
513         // Try to delete non-existent course.
514         $result = core_course_external::delete_courses(array($course1->id));
515         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
516         // Check for 1 warnings.
517         $this->assertEquals(1, count($result['warnings']));
519         // Try to delete Frontpage course.
520         $result = core_course_external::delete_courses(array(0));
521         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
522         // Check for 1 warnings.
523         $this->assertEquals(1, count($result['warnings']));
525          // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
526         $student1 = self::getDataGenerator()->create_user();
527         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
528         $this->getDataGenerator()->enrol_user($student1->id,
529                                               $course3->id,
530                                               $studentrole->id);
531         $this->setUser($student1);
532         $result = core_course_external::delete_courses(array($course3->id));
533         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
534         // Check for 1 warnings.
535         $this->assertEquals(1, count($result['warnings']));
537          // Fail when the user is not allow to access the course (enrolled) or is not admin.
538         $this->setGuestUser();
539         $this->expectException('require_login_exception');
541         $result = core_course_external::delete_courses(array($course3->id));
542         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
543     }
545     /**
546      * Test get_courses
547      */
548     public function test_get_courses () {
549         global $DB;
551         $this->resetAfterTest(true);
553         $generatedcourses = array();
554         $coursedata['idnumber'] = 'idnumbercourse1';
555         // Adding tags here to check that format_string is applied.
556         $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
557         $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
558         $coursedata['summary'] = 'Course 1 description';
559         $coursedata['summaryformat'] = FORMAT_MOODLE;
560         $course1  = self::getDataGenerator()->create_course($coursedata);
561         $generatedcourses[$course1->id] = $course1;
562         $course2  = self::getDataGenerator()->create_course();
563         $generatedcourses[$course2->id] = $course2;
564         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
565         $generatedcourses[$course3->id] = $course3;
567         // Set the required capabilities by the external function.
568         $context = context_system::instance();
569         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
570         $this->assignUserCapability('moodle/course:update',
571                 context_course::instance($course1->id)->id, $roleid);
572         $this->assignUserCapability('moodle/course:update',
573                 context_course::instance($course2->id)->id, $roleid);
574         $this->assignUserCapability('moodle/course:update',
575                 context_course::instance($course3->id)->id, $roleid);
577         $courses = core_course_external::get_courses(array('ids' =>
578             array($course1->id, $course2->id)));
580         // We need to execute the return values cleaning process to simulate the web service server.
581         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
583         // Check we retrieve the good total number of categories.
584         $this->assertEquals(2, count($courses));
586         foreach ($courses as $course) {
587             $coursecontext = context_course::instance($course['id']);
588             $dbcourse = $generatedcourses[$course['id']];
589             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
590             $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id));
591             $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse),
592                 $coursecontext->id));
593             // Summary was converted to the HTML format.
594             $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
595             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
596             $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id));
597             $this->assertEquals($course['categoryid'], $dbcourse->category);
598             $this->assertEquals($course['format'], $dbcourse->format);
599             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
600             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
601             $this->assertEquals($course['startdate'], $dbcourse->startdate);
602             $this->assertEquals($course['enddate'], $dbcourse->enddate);
603             $this->assertEquals($course['numsections'], $dbcourse->numsections);
604             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
605             $this->assertEquals($course['showreports'], $dbcourse->showreports);
606             $this->assertEquals($course['visible'], $dbcourse->visible);
607             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
608             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
609             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
610             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
611             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
612             $this->assertEquals($course['lang'], $dbcourse->lang);
613             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
614             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
615             if ($dbcourse->format === 'topics') {
616                 $this->assertEquals($course['courseformatoptions'], array(
617                     array('name' => 'numsections', 'value' => $dbcourse->numsections),
618                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
619                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
620                 ));
621             }
622         }
624         // Get all courses in the DB
625         $courses = core_course_external::get_courses(array());
627         // We need to execute the return values cleaning process to simulate the web service server.
628         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
630         $this->assertEquals($DB->count_records('course'), count($courses));
631     }
633     /**
634      * Test search_courses
635      */
636     public function test_search_courses () {
638         global $DB;
640         $this->resetAfterTest(true);
641         $this->setAdminUser();
642         $generatedcourses = array();
643         $coursedata1['fullname'] = 'FIRST COURSE';
644         $course1  = self::getDataGenerator()->create_course($coursedata1);
645         $coursedata2['fullname'] = 'SECOND COURSE';
646         $course2  = self::getDataGenerator()->create_course($coursedata2);
647         // Search by name.
648         $results = core_course_external::search_courses('search', 'FIRST');
649         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
650         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
651         $this->assertCount(1, $results['courses']);
653         // Create the forum.
654         $record = new stdClass();
655         $record->introformat = FORMAT_HTML;
656         $record->course = $course2->id;
657         // Set Aggregate type = Average of ratings.
658         $forum = self::getDataGenerator()->create_module('forum', $record);
660         // Search by module.
661         $results = core_course_external::search_courses('modulelist', 'forum');
662         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
663         $this->assertEquals(1, $results['total']);
665         // Enable coursetag option.
666         set_config('block_tags_showcoursetags', true);
667         // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
668         core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
669                 array('TAG-LABEL ON SECOND COURSE'));
670         $taginstance = $DB->get_record('tag_instance',
671                 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
672         // Search by tagid.
673         $results = core_course_external::search_courses('tagid', $taginstance->tagid);
674         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
675         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
677         // Search by block (use news_items default block).
678         $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
679         $results = core_course_external::search_courses('blocklist', $blockid);
680         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
681         $this->assertEquals(2, $results['total']);
683         // Now as a normal user.
684         $user = self::getDataGenerator()->create_user();
686         // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
687         $coursedata3['fullname'] = 'HIDDEN COURSE';
688         $coursedata3['visible'] = 0;
689         $course3  = self::getDataGenerator()->create_course($coursedata3);
690         $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
692         $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
693         $this->setUser($user);
695         $results = core_course_external::search_courses('search', 'FIRST');
696         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
697         $this->assertCount(1, $results['courses']);
698         $this->assertEquals(1, $results['total']);
699         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
701         // Check that we can see both without the limit to enrolled setting.
702         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
703         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
704         $this->assertCount(2, $results['courses']);
705         $this->assertEquals(2, $results['total']);
707         // Check that we only see our enrolled course when limiting.
708         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
709         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
710         $this->assertCount(1, $results['courses']);
711         $this->assertEquals(1, $results['total']);
712         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
714         // Search by block (use news_items default block). Should fail (only admins allowed).
715         $this->expectException('required_capability_exception');
716         $results = core_course_external::search_courses('blocklist', $blockid);
718     }
720     /**
721      * Create a course with contents
722      * @return array A list with the course object and course modules objects
723      */
724     private function prepare_get_course_contents_test() {
725         global $DB;
726         $course  = self::getDataGenerator()->create_course();
727         $forumdescription = 'This is the forum description';
728         $forum = $this->getDataGenerator()->create_module('forum',
729             array('course' => $course->id, 'intro' => $forumdescription),
730             array('showdescription' => true));
731         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
732         $data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
733         $datacm = get_coursemodule_from_instance('page', $data->id);
734         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
735         $pagecm = get_coursemodule_from_instance('page', $page->id);
736         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
737                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
738         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
739             'intro' => $labeldescription));
740         $labelcm = get_coursemodule_from_instance('label', $label->id);
741         $url = $this->getDataGenerator()->create_module('url', array('course' => $course->id,
742             'name' => 'URL: % & $ ../', 'section' => 2));
743         $urlcm = get_coursemodule_from_instance('url', $url->id);
745         // Set the required capabilities by the external function.
746         $context = context_course::instance($course->id);
747         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
748         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
749         $this->assignUserCapability('mod/data:view', $context->id, $roleid);
751         $conditions = array('course' => $course->id, 'section' => 2);
752         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
753         rebuild_course_cache($course->id, true);
755         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
756     }
758     /**
759      * Test get_course_contents
760      */
761     public function test_get_course_contents() {
762         $this->resetAfterTest(true);
764         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
766         $sections = core_course_external::get_course_contents($course->id, array());
767         // We need to execute the return values cleaning process to simulate the web service server.
768         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
770         // Check that forum and label descriptions are correctly returned.
771         $firstsection = array_shift($sections);
772         $lastsection = array_pop($sections);
774         $modinfo = get_fast_modinfo($course);
775         $testexecuted = 0;
776         foreach ($firstsection['modules'] as $module) {
777             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
778                 $cm = $modinfo->cms[$forumcm->id];
779                 $formattedtext = format_text($cm->content, FORMAT_HTML,
780                     array('noclean' => true, 'para' => false, 'filter' => false));
781                 $this->assertEquals($formattedtext, $module['description']);
782                 $this->assertEquals($forumcm->instance, $module['instance']);
783                 $testexecuted = $testexecuted + 1;
784             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
785                 $cm = $modinfo->cms[$labelcm->id];
786                 $formattedtext = format_text($cm->content, FORMAT_HTML,
787                     array('noclean' => true, 'para' => false, 'filter' => false));
788                 $this->assertEquals($formattedtext, $module['description']);
789                 $this->assertEquals($labelcm->instance, $module['instance']);
790                 $testexecuted = $testexecuted + 1;
791             }
792         }
793         $this->assertEquals(2, $testexecuted);
794         $this->assertEquals(0, $firstsection['section']);
796         // Check that the only return section has the 5 created modules.
797         $this->assertCount(4, $firstsection['modules']);
798         $this->assertCount(1, $lastsection['modules']);
799         $this->assertEquals(2, $lastsection['section']);
800         $this->assertContains('<iframe', $lastsection['summary']);
801         $this->assertContains('</iframe>', $lastsection['summary']);
803         try {
804             $sections = core_course_external::get_course_contents($course->id,
805                                                                     array(array("name" => "invalid", "value" => 1)));
806             $this->fail('Exception expected due to invalid option.');
807         } catch (moodle_exception $e) {
808             $this->assertEquals('errorinvalidparam', $e->errorcode);
809         }
810     }
813     /**
814      * Test get_course_contents excluding modules
815      */
816     public function test_get_course_contents_excluding_modules() {
817         $this->resetAfterTest(true);
819         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
821         // Test exclude modules.
822         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
824         // We need to execute the return values cleaning process to simulate the web service server.
825         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
827         $firstsection = array_shift($sections);
828         $lastsection = array_pop($sections);
830         $this->assertEmpty($firstsection['modules']);
831         $this->assertEmpty($lastsection['modules']);
832     }
834     /**
835      * Test get_course_contents excluding contents
836      */
837     public function test_get_course_contents_excluding_contents() {
838         $this->resetAfterTest(true);
840         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
842         // Test exclude modules.
843         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
845         // We need to execute the return values cleaning process to simulate the web service server.
846         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
848         foreach ($sections as $section) {
849             foreach ($section['modules'] as $module) {
850                 // Only resources return contents.
851                 if (isset($module['contents'])) {
852                     $this->assertEmpty($module['contents']);
853                 }
854             }
855         }
856     }
858     /**
859      * Test get_course_contents filtering by section number
860      */
861     public function test_get_course_contents_section_number() {
862         $this->resetAfterTest(true);
864         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
866         // Test exclude modules.
867         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
869         // We need to execute the return values cleaning process to simulate the web service server.
870         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
872         $this->assertCount(1, $sections);
873         $this->assertCount(4, $sections[0]['modules']);
874     }
876     /**
877      * Test get_course_contents filtering by cmid
878      */
879     public function test_get_course_contents_cmid() {
880         $this->resetAfterTest(true);
882         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
884         // Test exclude modules.
885         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
887         // We need to execute the return values cleaning process to simulate the web service server.
888         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
890         $this->assertCount(2, $sections);
891         $this->assertCount(1, $sections[0]['modules']);
892         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
893     }
896     /**
897      * Test get_course_contents filtering by cmid and section
898      */
899     public function test_get_course_contents_section_cmid() {
900         $this->resetAfterTest(true);
902         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
904         // Test exclude modules.
905         $sections = core_course_external::get_course_contents($course->id, array(
906                                                                         array("name" => "cmid", "value" => $forumcm->id),
907                                                                         array("name" => "sectionnumber", "value" => 0)
908                                                                         ));
910         // We need to execute the return values cleaning process to simulate the web service server.
911         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
913         $this->assertCount(1, $sections);
914         $this->assertCount(1, $sections[0]['modules']);
915         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
916     }
918     /**
919      * Test get_course_contents filtering by modname
920      */
921     public function test_get_course_contents_modname() {
922         $this->resetAfterTest(true);
924         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
926         // Test exclude modules.
927         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
929         // We need to execute the return values cleaning process to simulate the web service server.
930         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
932         $this->assertCount(2, $sections);
933         $this->assertCount(1, $sections[0]['modules']);
934         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
935     }
937     /**
938      * Test get_course_contents filtering by modname
939      */
940     public function test_get_course_contents_modid() {
941         $this->resetAfterTest(true);
943         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
945         // Test exclude modules.
946         $sections = core_course_external::get_course_contents($course->id, array(
947                                                                             array("name" => "modname", "value" => "page"),
948                                                                             array("name" => "modid", "value" => $pagecm->instance),
949                                                                             ));
951         // We need to execute the return values cleaning process to simulate the web service server.
952         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
954         $this->assertCount(2, $sections);
955         $this->assertCount(1, $sections[0]['modules']);
956         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
957         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
958     }
960     /**
961      * Test duplicate_course
962      */
963     public function test_duplicate_course() {
964         $this->resetAfterTest(true);
966         // Create one course with three modules.
967         $course  = self::getDataGenerator()->create_course();
968         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
969         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
970         $forumcontext = context_module::instance($forum->cmid);
971         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
972         $datacontext = context_module::instance($data->cmid);
973         $datacm = get_coursemodule_from_instance('page', $data->id);
974         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
975         $pagecontext = context_module::instance($page->cmid);
976         $pagecm = get_coursemodule_from_instance('page', $page->id);
978         // Set the required capabilities by the external function.
979         $coursecontext = context_course::instance($course->id);
980         $categorycontext = context_coursecat::instance($course->category);
981         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
982         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
983         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
984         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
985         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
986         // Optional capabilities to copy user data.
987         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
988         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
990         $newcourse['fullname'] = 'Course duplicate';
991         $newcourse['shortname'] = 'courseduplicate';
992         $newcourse['categoryid'] = $course->category;
993         $newcourse['visible'] = true;
994         $newcourse['options'][] = array('name' => 'users', 'value' => true);
996         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
997                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
999         // We need to execute the return values cleaning process to simulate the web service server.
1000         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1002         // Check that the course has been duplicated.
1003         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1004     }
1006     /**
1007      * Test update_courses
1008      */
1009     public function test_update_courses() {
1010         global $DB, $CFG, $USER, $COURSE;
1012         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1013         // trick because we are both updating and getting (for testing) course information
1014         // in the same request and core_course_external::update_courses()
1015         // is overwriting $COURSE all over the time with OLD values, so later
1016         // use of get_course() fetches those OLD values instead of the updated ones.
1017         // See MDL-39723 for more info.
1018         $origcourse = clone($COURSE);
1020         $this->resetAfterTest(true);
1022         // Set the required capabilities by the external function.
1023         $contextid = context_system::instance()->id;
1024         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1025         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1026         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1027         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1028         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1029         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1030         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1031         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1033         // Create category and course.
1034         $category1  = self::getDataGenerator()->create_category();
1035         $category2  = self::getDataGenerator()->create_category();
1036         $originalcourse1 = self::getDataGenerator()->create_course();
1037         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1038         $originalcourse2 = self::getDataGenerator()->create_course();
1039         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1041         // Course values to be updated.
1042         $course1['id'] = $originalcourse1->id;
1043         $course1['fullname'] = 'Updated test course 1';
1044         $course1['shortname'] = 'Udestedtestcourse1';
1045         $course1['categoryid'] = $category1->id;
1046         $course2['id'] = $originalcourse2->id;
1047         $course2['fullname'] = 'Updated test course 2';
1048         $course2['shortname'] = 'Updestedtestcourse2';
1049         $course2['categoryid'] = $category2->id;
1050         $course2['idnumber'] = 'Updatedidnumber2';
1051         $course2['summary'] = 'Updaated description for course 2';
1052         $course2['summaryformat'] = FORMAT_HTML;
1053         $course2['format'] = 'topics';
1054         $course2['showgrades'] = 1;
1055         $course2['newsitems'] = 3;
1056         $course2['startdate'] = 1420092000; // 01/01/2015.
1057         $course2['enddate'] = 1422669600; // 01/31/2015.
1058         $course2['numsections'] = 4;
1059         $course2['maxbytes'] = 100000;
1060         $course2['showreports'] = 1;
1061         $course2['visible'] = 0;
1062         $course2['hiddensections'] = 0;
1063         $course2['groupmode'] = 0;
1064         $course2['groupmodeforce'] = 0;
1065         $course2['defaultgroupingid'] = 0;
1066         $course2['enablecompletion'] = 1;
1067         $course2['lang'] = 'en';
1068         $course2['forcetheme'] = 'bootstrapbase';
1069         $courses = array($course1, $course2);
1071         $updatedcoursewarnings = core_course_external::update_courses($courses);
1072         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1073                                                                     $updatedcoursewarnings);
1074         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1076         // Check that right number of courses were created.
1077         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1079         // Check that the courses were correctly created.
1080         foreach ($courses as $course) {
1081             $courseinfo = course_get_format($course['id'])->get_course();
1082             if ($course['id'] == $course2['id']) {
1083                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1084                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1085                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1086                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1087                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1088                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1089                 $this->assertEquals($course2['format'], $courseinfo->format);
1090                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1091                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1092                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1093                 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
1094                 $this->assertEquals($course2['numsections'], $courseinfo->numsections);
1095                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1096                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1097                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1098                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1099                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1100                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1101                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1102                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1104                 if (!empty($CFG->allowcoursethemes)) {
1105                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1106                 }
1108                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1109             } else if ($course['id'] == $course1['id']) {
1110                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1111                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1112                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1113                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1114                 $this->assertEquals('topics', $courseinfo->format);
1115                 $this->assertEquals(5, $courseinfo->numsections);
1116                 $this->assertEquals(0, $courseinfo->newsitems);
1117                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1118             } else {
1119                 throw moodle_exception('Unexpected shortname');
1120             }
1121         }
1123         $courses = array($course1);
1124         // Try update course without update capability.
1125         $user = self::getDataGenerator()->create_user();
1126         $this->setUser($user);
1127         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1128         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1129         $updatedcoursewarnings = core_course_external::update_courses($courses);
1130         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1131                                                                     $updatedcoursewarnings);
1132         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1134         // Try update course category without capability.
1135         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1136         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1137         $user = self::getDataGenerator()->create_user();
1138         $this->setUser($user);
1139         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1140         $course1['categoryid'] = $category2->id;
1141         $courses = array($course1);
1142         $updatedcoursewarnings = core_course_external::update_courses($courses);
1143         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1144                                                                     $updatedcoursewarnings);
1145         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1147         // Try update course fullname without capability.
1148         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1149         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1150         $user = self::getDataGenerator()->create_user();
1151         $this->setUser($user);
1152         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1153         $updatedcoursewarnings = core_course_external::update_courses($courses);
1154         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1155                                                                     $updatedcoursewarnings);
1156         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1157         $course1['fullname'] = 'Testing fullname without permission';
1158         $courses = array($course1);
1159         $updatedcoursewarnings = core_course_external::update_courses($courses);
1160         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1161                                                                     $updatedcoursewarnings);
1162         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1164         // Try update course shortname without capability.
1165         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1166         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1167         $user = self::getDataGenerator()->create_user();
1168         $this->setUser($user);
1169         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1170         $updatedcoursewarnings = core_course_external::update_courses($courses);
1171         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1172                                                                     $updatedcoursewarnings);
1173         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1174         $course1['shortname'] = 'Testing shortname without permission';
1175         $courses = array($course1);
1176         $updatedcoursewarnings = core_course_external::update_courses($courses);
1177         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1178                                                                     $updatedcoursewarnings);
1179         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1181         // Try update course idnumber without capability.
1182         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1183         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1184         $user = self::getDataGenerator()->create_user();
1185         $this->setUser($user);
1186         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1187         $updatedcoursewarnings = core_course_external::update_courses($courses);
1188         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1189                                                                     $updatedcoursewarnings);
1190         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1191         $course1['idnumber'] = 'NEWIDNUMBER';
1192         $courses = array($course1);
1193         $updatedcoursewarnings = core_course_external::update_courses($courses);
1194         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1195                                                                     $updatedcoursewarnings);
1196         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1198         // Try update course summary without capability.
1199         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1200         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1201         $user = self::getDataGenerator()->create_user();
1202         $this->setUser($user);
1203         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1204         $updatedcoursewarnings = core_course_external::update_courses($courses);
1205         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1206                                                                     $updatedcoursewarnings);
1207         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1208         $course1['summary'] = 'New summary';
1209         $courses = array($course1);
1210         $updatedcoursewarnings = core_course_external::update_courses($courses);
1211         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1212                                                                     $updatedcoursewarnings);
1213         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1215         // Try update course with invalid summary format.
1216         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1217         $user = self::getDataGenerator()->create_user();
1218         $this->setUser($user);
1219         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1220         $updatedcoursewarnings = core_course_external::update_courses($courses);
1221         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1222                                                                     $updatedcoursewarnings);
1223         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1224         $course1['summaryformat'] = 10;
1225         $courses = array($course1);
1226         $updatedcoursewarnings = core_course_external::update_courses($courses);
1227         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1228                                                                     $updatedcoursewarnings);
1229         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1231         // Try update course visibility without capability.
1232         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1233         $user = self::getDataGenerator()->create_user();
1234         $this->setUser($user);
1235         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1236         $course1['summaryformat'] = FORMAT_MOODLE;
1237         $courses = array($course1);
1238         $updatedcoursewarnings = core_course_external::update_courses($courses);
1239         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1240                                                                     $updatedcoursewarnings);
1241         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1242         $course1['visible'] = 0;
1243         $courses = array($course1);
1244         $updatedcoursewarnings = core_course_external::update_courses($courses);
1245         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1246                                                                     $updatedcoursewarnings);
1247         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1248     }
1250     /**
1251      * Test delete course_module.
1252      */
1253     public function test_delete_modules() {
1254         global $DB;
1256         // Ensure we reset the data after this test.
1257         $this->resetAfterTest(true);
1259         // Create a user.
1260         $user = self::getDataGenerator()->create_user();
1262         // Set the tests to run as the user.
1263         self::setUser($user);
1265         // Create a course to add the modules.
1266         $course = self::getDataGenerator()->create_course();
1268         // Create two test modules.
1269         $record = new stdClass();
1270         $record->course = $course->id;
1271         $module1 = self::getDataGenerator()->create_module('forum', $record);
1272         $module2 = self::getDataGenerator()->create_module('assign', $record);
1274         // Check the forum was correctly created.
1275         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1277         // Check the assignment was correctly created.
1278         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1280         // Check data exists in the course modules table.
1281         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1282                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1284         // Enrol the user in the course.
1285         $enrol = enrol_get_plugin('manual');
1286         $enrolinstances = enrol_get_instances($course->id, true);
1287         foreach ($enrolinstances as $courseenrolinstance) {
1288             if ($courseenrolinstance->enrol == "manual") {
1289                 $instance = $courseenrolinstance;
1290                 break;
1291             }
1292         }
1293         $enrol->enrol_user($instance, $user->id);
1295         // Assign capabilities to delete module 1.
1296         $modcontext = context_module::instance($module1->cmid);
1297         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1299         // Assign capabilities to delete module 2.
1300         $modcontext = context_module::instance($module2->cmid);
1301         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1302         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1304         // Deleting these module instances.
1305         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1307         // Check the forum was deleted.
1308         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1310         // Check the assignment was deleted.
1311         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1313         // Check we retrieve no data in the course modules table.
1314         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1315                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1317         // Call with non-existent course module id and ensure exception thrown.
1318         try {
1319             core_course_external::delete_modules(array('1337'));
1320             $this->fail('Exception expected due to missing course module.');
1321         } catch (dml_missing_record_exception $e) {
1322             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1323         }
1325         // Create two modules.
1326         $module1 = self::getDataGenerator()->create_module('forum', $record);
1327         $module2 = self::getDataGenerator()->create_module('assign', $record);
1329         // Since these modules were recreated the user will not have capabilities
1330         // to delete them, ensure exception is thrown if they try.
1331         try {
1332             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1333             $this->fail('Exception expected due to missing capability.');
1334         } catch (moodle_exception $e) {
1335             $this->assertEquals('nopermissions', $e->errorcode);
1336         }
1338         // Unenrol user from the course.
1339         $enrol->unenrol_user($instance, $user->id);
1341         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1342         try {
1343             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1344             $this->fail('Exception expected due to being unenrolled from the course.');
1345         } catch (moodle_exception $e) {
1346             $this->assertEquals('requireloginerror', $e->errorcode);
1347         }
1348     }
1350     /**
1351      * Test import_course into an empty course
1352      */
1353     public function test_import_course_empty() {
1354         global $USER;
1356         $this->resetAfterTest(true);
1358         $course1  = self::getDataGenerator()->create_course();
1359         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1360         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1362         $course2  = self::getDataGenerator()->create_course();
1364         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1365         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1367         // Verify the state of the courses before we do the import.
1368         $this->assertCount(2, $course1cms);
1369         $this->assertEmpty($course2cms);
1371         // Setup the user to run the operation (ugly hack because validate_context() will
1372         // fail as the email is not set by $this->setAdminUser()).
1373         $this->setAdminUser();
1374         $USER->email = 'emailtopass@example.com';
1376         // Import from course1 to course2.
1377         core_course_external::import_course($course1->id, $course2->id, 0);
1379         // Verify that now we have two modules in both courses.
1380         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1381         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1382         $this->assertCount(2, $course1cms);
1383         $this->assertCount(2, $course2cms);
1385         // Verify that the names transfered across correctly.
1386         foreach ($course2cms as $cm) {
1387             if ($cm->modname === 'page') {
1388                 $this->assertEquals($cm->name, $page->name);
1389             } else if ($cm->modname === 'forum') {
1390                 $this->assertEquals($cm->name, $forum->name);
1391             } else {
1392                 $this->fail('Unknown CM found.');
1393             }
1394         }
1395     }
1397     /**
1398      * Test import_course into an filled course
1399      */
1400     public function test_import_course_filled() {
1401         global $USER;
1403         $this->resetAfterTest(true);
1405         // Add forum and page to course1.
1406         $course1  = self::getDataGenerator()->create_course();
1407         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1408         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1410         // Add quiz to course 2.
1411         $course2  = self::getDataGenerator()->create_course();
1412         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1414         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1415         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1417         // Verify the state of the courses before we do the import.
1418         $this->assertCount(2, $course1cms);
1419         $this->assertCount(1, $course2cms);
1421         // Setup the user to run the operation (ugly hack because validate_context() will
1422         // fail as the email is not set by $this->setAdminUser()).
1423         $this->setAdminUser();
1424         $USER->email = 'emailtopass@example.com';
1426         // Import from course1 to course2 without deleting content.
1427         core_course_external::import_course($course1->id, $course2->id, 0);
1429         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1431         // Verify that now we have three modules in course2.
1432         $this->assertCount(3, $course2cms);
1434         // Verify that the names transfered across correctly.
1435         foreach ($course2cms as $cm) {
1436             if ($cm->modname === 'page') {
1437                 $this->assertEquals($cm->name, $page->name);
1438             } else if ($cm->modname === 'forum') {
1439                 $this->assertEquals($cm->name, $forum->name);
1440             } else if ($cm->modname === 'quiz') {
1441                 $this->assertEquals($cm->name, $quiz->name);
1442             } else {
1443                 $this->fail('Unknown CM found.');
1444             }
1445         }
1446     }
1448     /**
1449      * Test import_course with only blocks set to backup
1450      */
1451     public function test_import_course_blocksonly() {
1452         global $USER, $DB;
1454         $this->resetAfterTest(true);
1456         // Add forum and page to course1.
1457         $course1  = self::getDataGenerator()->create_course();
1458         $course1ctx = context_course::instance($course1->id);
1459         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1460         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1462         $course2  = self::getDataGenerator()->create_course();
1463         $course2ctx = context_course::instance($course2->id);
1464         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1465         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1467         // Setup the user to run the operation (ugly hack because validate_context() will
1468         // fail as the email is not set by $this->setAdminUser()).
1469         $this->setAdminUser();
1470         $USER->email = 'emailtopass@example.com';
1472         // Import from course1 to course2 without deleting content, but excluding
1473         // activities.
1474         $options = array(
1475             array('name' => 'activities', 'value' => 0),
1476             array('name' => 'blocks', 'value' => 1),
1477             array('name' => 'filters', 'value' => 0),
1478         );
1480         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1482         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1483         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1484         // Check that course modules haven't changed, but that blocks have.
1485         $this->assertEquals($initialcmcount, $newcmcount);
1486         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1487     }
1489     /**
1490      * Test import_course into an filled course, deleting content.
1491      */
1492     public function test_import_course_deletecontent() {
1493         global $USER;
1494         $this->resetAfterTest(true);
1496         // Add forum and page to course1.
1497         $course1  = self::getDataGenerator()->create_course();
1498         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1499         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1501         // Add quiz to course 2.
1502         $course2  = self::getDataGenerator()->create_course();
1503         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1505         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1506         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1508         // Verify the state of the courses before we do the import.
1509         $this->assertCount(2, $course1cms);
1510         $this->assertCount(1, $course2cms);
1512         // Setup the user to run the operation (ugly hack because validate_context() will
1513         // fail as the email is not set by $this->setAdminUser()).
1514         $this->setAdminUser();
1515         $USER->email = 'emailtopass@example.com';
1517         // Import from course1 to course2,  deleting content.
1518         core_course_external::import_course($course1->id, $course2->id, 1);
1520         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1522         // Verify that now we have two modules in course2.
1523         $this->assertCount(2, $course2cms);
1525         // Verify that the course only contains the imported modules.
1526         foreach ($course2cms as $cm) {
1527             if ($cm->modname === 'page') {
1528                 $this->assertEquals($cm->name, $page->name);
1529             } else if ($cm->modname === 'forum') {
1530                 $this->assertEquals($cm->name, $forum->name);
1531             } else {
1532                 $this->fail('Unknown CM found: '.$cm->name);
1533             }
1534         }
1535     }
1537     /**
1538      * Ensure import_course handles incorrect deletecontent option correctly.
1539      */
1540     public function test_import_course_invalid_deletecontent_option() {
1541         $this->resetAfterTest(true);
1543         $course1  = self::getDataGenerator()->create_course();
1544         $course2  = self::getDataGenerator()->create_course();
1546         $this->expectException('moodle_exception');
1547         $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
1548         // Import from course1 to course2, with invalid option
1549         core_course_external::import_course($course1->id, $course2->id, -1);;
1550     }
1552     /**
1553      * Test view_course function
1554      */
1555     public function test_view_course() {
1557         $this->resetAfterTest();
1559         // Course without sections.
1560         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1561         $this->setAdminUser();
1563         // Redirect events to the sink, so we can recover them later.
1564         $sink = $this->redirectEvents();
1566         $result = core_course_external::view_course($course->id, 1);
1567         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1568         $events = $sink->get_events();
1569         $event = reset($events);
1571         // Check the event details are correct.
1572         $this->assertInstanceOf('\core\event\course_viewed', $event);
1573         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1574         $this->assertEquals(1, $event->other['coursesectionnumber']);
1576         $result = core_course_external::view_course($course->id);
1577         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1578         $events = $sink->get_events();
1579         $event = array_pop($events);
1580         $sink->close();
1582         // Check the event details are correct.
1583         $this->assertInstanceOf('\core\event\course_viewed', $event);
1584         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1585         $this->assertEmpty($event->other);
1587     }
1589     /**
1590      * Test get_course_module
1591      */
1592     public function test_get_course_module() {
1593         global $DB;
1595         $this->resetAfterTest(true);
1597         $this->setAdminUser();
1598         $course = self::getDataGenerator()->create_course();
1599         $record = array(
1600             'course' => $course->id,
1601             'name' => 'First Assignment'
1602         );
1603         $options = array(
1604             'idnumber' => 'ABC',
1605             'visible' => 0
1606         );
1607         // Hidden activity.
1608         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
1610         // Test admin user can see the complete hidden activity.
1611         $result = core_course_external::get_course_module($assign->cmid);
1612         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1614         $this->assertCount(0, $result['warnings']);
1615         // Test we retrieve all the fields.
1616         $this->assertCount(26, $result['cm']);
1617         $this->assertEquals($record['name'], $result['cm']['name']);
1618         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1619         $this->assertEquals(100, $result['cm']['grade']);
1620         $this->assertEquals(0.0, $result['cm']['gradepass']);
1621         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
1622         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
1623         $this->assertArrayNotHasKey('outcomes', $result['cm']);
1625         $student = $this->getDataGenerator()->create_user();
1626         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1628         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1629         $this->setUser($student);
1631         // The user shouldn't be able to see the activity.
1632         try {
1633             core_course_external::get_course_module($assign->cmid);
1634             $this->fail('Exception expected due to invalid permissions.');
1635         } catch (moodle_exception $e) {
1636             $this->assertEquals('requireloginerror', $e->errorcode);
1637         }
1639         // Make module visible.
1640         set_coursemodule_visible($assign->cmid, 1);
1642         // Test student user.
1643         $result = core_course_external::get_course_module($assign->cmid);
1644         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1646         $this->assertCount(0, $result['warnings']);
1647         // Test we retrieve only the few files we can see.
1648         $this->assertCount(11, $result['cm']);
1649         $this->assertEquals($assign->cmid, $result['cm']['id']);
1650         $this->assertEquals($course->id, $result['cm']['course']);
1651         $this->assertEquals('assign', $result['cm']['modname']);
1652         $this->assertEquals($assign->id, $result['cm']['instance']);
1654     }
1656     /**
1657      * Test get_course_module_by_instance
1658      */
1659     public function test_get_course_module_by_instance() {
1660         global $DB;
1662         $this->resetAfterTest(true);
1664         $this->setAdminUser();
1665         $course = self::getDataGenerator()->create_course();
1666         $record = array(
1667             'course' => $course->id,
1668             'name' => 'First Chat'
1669         );
1670         $options = array(
1671             'idnumber' => 'ABC',
1672             'visible' => 0
1673         );
1674         // Hidden activity.
1675         $chat = self::getDataGenerator()->create_module('chat', $record, $options);
1677         // Test admin user can see the complete hidden activity.
1678         $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1679         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1681         $this->assertCount(0, $result['warnings']);
1682         // Test we retrieve all the fields.
1683         $this->assertCount(22, $result['cm']);
1684         $this->assertEquals($record['name'], $result['cm']['name']);
1685         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1687         $student = $this->getDataGenerator()->create_user();
1688         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1690         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1691         $this->setUser($student);
1693         // The user shouldn't be able to see the activity.
1694         try {
1695             core_course_external::get_course_module_by_instance('chat', $chat->id);
1696             $this->fail('Exception expected due to invalid permissions.');
1697         } catch (moodle_exception $e) {
1698             $this->assertEquals('requireloginerror', $e->errorcode);
1699         }
1701         // Make module visible.
1702         set_coursemodule_visible($chat->cmid, 1);
1704         // Test student user.
1705         $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1706         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1708         $this->assertCount(0, $result['warnings']);
1709         // Test we retrieve only the few files we can see.
1710         $this->assertCount(11, $result['cm']);
1711         $this->assertEquals($chat->cmid, $result['cm']['id']);
1712         $this->assertEquals($course->id, $result['cm']['course']);
1713         $this->assertEquals('chat', $result['cm']['modname']);
1714         $this->assertEquals($chat->id, $result['cm']['instance']);
1716         // Try with an invalid module name.
1717         try {
1718             core_course_external::get_course_module_by_instance('abc', $chat->id);
1719             $this->fail('Exception expected due to invalid module name.');
1720         } catch (dml_read_exception $e) {
1721             $this->assertEquals('dmlreadexception', $e->errorcode);
1722         }
1724     }
1726     /**
1727      * Test get_activities_overview
1728      */
1729     public function test_get_activities_overview() {
1730         global $USER;
1732         $this->resetAfterTest();
1733         $course1 = self::getDataGenerator()->create_course();
1734         $course2 = self::getDataGenerator()->create_course();
1736         // Create a viewer user.
1737         $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
1738         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1739         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1741         // Create two forums - one in each course.
1742         $record = new stdClass();
1743         $record->course = $course1->id;
1744         $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
1745         $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
1747         $this->setAdminUser();
1748         // A standard post in the forum.
1749         $record = new stdClass();
1750         $record->course = $course1->id;
1751         $record->userid = $USER->id;
1752         $record->forum = $forum1->id;
1753         $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1755         $this->setUser($viewer->id);
1756         $courses = array($course1->id , $course2->id);
1758         $result = core_course_external::get_activities_overview($courses);
1759         $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
1761         // There should be one entry for course1, and no others.
1762         $this->assertCount(1, $result['courses']);
1763         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1764         // Check expected overview data for the module.
1765         $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
1766         $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
1767     }
1769     /**
1770      * Test get_user_navigation_options
1771      */
1772     public function test_get_user_navigation_options() {
1773         global $USER;
1775         $this->resetAfterTest();
1776         $course1 = self::getDataGenerator()->create_course();
1777         $course2 = self::getDataGenerator()->create_course();
1779         // Create a viewer user.
1780         $viewer = self::getDataGenerator()->create_user();
1781         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1782         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1784         $this->setUser($viewer->id);
1785         $courses = array($course1->id , $course2->id, SITEID);
1787         $result = core_course_external::get_user_navigation_options($courses);
1788         $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
1790         $this->assertCount(0, $result['warnings']);
1791         $this->assertCount(3, $result['courses']);
1793         foreach ($result['courses'] as $course) {
1794             $navoptions = new stdClass;
1795             foreach ($course['options'] as $option) {
1796                 $navoptions->{$option['name']} = $option['available'];
1797             }
1798             if ($course['id'] == SITEID) {
1799                 $this->assertCount(7, $course['options']);
1800                 $this->assertTrue($navoptions->blogs);
1801                 $this->assertFalse($navoptions->notes);
1802                 $this->assertFalse($navoptions->participants);
1803                 $this->assertTrue($navoptions->badges);
1804                 $this->assertTrue($navoptions->tags);
1805                 $this->assertFalse($navoptions->search);
1806                 $this->assertTrue($navoptions->calendar);
1807             } else {
1808                 $this->assertCount(4, $course['options']);
1809                 $this->assertTrue($navoptions->blogs);
1810                 $this->assertFalse($navoptions->notes);
1811                 $this->assertTrue($navoptions->participants);
1812                 $this->assertTrue($navoptions->badges);
1813             }
1814         }
1815     }
1817     /**
1818      * Test get_user_administration_options
1819      */
1820     public function test_get_user_administration_options() {
1821         global $USER;
1823         $this->resetAfterTest();
1824         $course1 = self::getDataGenerator()->create_course();
1825         $course2 = self::getDataGenerator()->create_course();
1827         // Create a viewer user.
1828         $viewer = self::getDataGenerator()->create_user();
1829         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1830         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1832         $this->setUser($viewer->id);
1833         $courses = array($course1->id , $course2->id, SITEID);
1835         $result = core_course_external::get_user_administration_options($courses);
1836         $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
1838         $this->assertCount(0, $result['warnings']);
1839         $this->assertCount(3, $result['courses']);
1841         foreach ($result['courses'] as $course) {
1842             $adminoptions = new stdClass;
1843             foreach ($course['options'] as $option) {
1844                 $adminoptions->{$option['name']} = $option['available'];
1845             }
1846             if ($course['id'] == SITEID) {
1847                 $this->assertCount(15, $course['options']);
1848                 $this->assertFalse($adminoptions->update);
1849                 $this->assertFalse($adminoptions->filters);
1850                 $this->assertFalse($adminoptions->reports);
1851                 $this->assertFalse($adminoptions->backup);
1852                 $this->assertFalse($adminoptions->restore);
1853                 $this->assertFalse($adminoptions->files);
1854                 $this->assertFalse(!isset($adminoptions->tags));
1855                 $this->assertFalse($adminoptions->gradebook);
1856                 $this->assertFalse($adminoptions->outcomes);
1857                 $this->assertFalse($adminoptions->badges);
1858                 $this->assertFalse($adminoptions->import);
1859                 $this->assertFalse($adminoptions->publish);
1860                 $this->assertFalse($adminoptions->reset);
1861                 $this->assertFalse($adminoptions->roles);
1862                 $this->assertFalse($adminoptions->grades);
1863             } else {
1864                 $this->assertCount(15, $course['options']);
1865                 $this->assertFalse($adminoptions->update);
1866                 $this->assertFalse($adminoptions->filters);
1867                 $this->assertFalse($adminoptions->reports);
1868                 $this->assertFalse($adminoptions->backup);
1869                 $this->assertFalse($adminoptions->restore);
1870                 $this->assertFalse($adminoptions->files);
1871                 $this->assertFalse($adminoptions->tags);
1872                 $this->assertFalse($adminoptions->gradebook);
1873                 $this->assertFalse($adminoptions->outcomes);
1874                 $this->assertTrue($adminoptions->badges);
1875                 $this->assertFalse($adminoptions->import);
1876                 $this->assertFalse($adminoptions->publish);
1877                 $this->assertFalse($adminoptions->reset);
1878                 $this->assertFalse($adminoptions->roles);
1879                 $this->assertTrue($adminoptions->grades);
1880             }
1881         }
1882     }
1884     /**
1885      * Test get_courses_by_fields
1886      */
1887     public function test_get_courses_by_field() {
1888         global $DB;
1889         $this->resetAfterTest(true);
1891         $category1 = self::getDataGenerator()->create_category();
1892         $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
1893         $course1 = self::getDataGenerator()->create_course(array('category' => $category1->id, 'shortname' => 'c1'));
1894         $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
1896         $student1 = self::getDataGenerator()->create_user();
1897         $user1 = self::getDataGenerator()->create_user();
1898         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1899         self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
1900         self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
1902         self::setAdminUser();
1903         // As admins, we should be able to retrieve everything.
1904         $result = core_course_external::get_courses_by_field();
1905         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1906         $this->assertCount(3, $result['courses']);
1907         // Expect to receive all the fields.
1908         $this->assertCount(35, $result['courses'][0]);
1909         $this->assertCount(35, $result['courses'][1]);
1910         $this->assertCount(35, $result['courses'][2]);
1912         $result = core_course_external::get_courses_by_field('id', $course1->id);
1913         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1914         $this->assertCount(1, $result['courses']);
1915         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1916         // Expect to receive all the fields.
1917         $this->assertCount(35, $result['courses'][0]);
1919         $result = core_course_external::get_courses_by_field('id', $course2->id);
1920         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1921         $this->assertCount(1, $result['courses']);
1922         $this->assertEquals($course2->id, $result['courses'][0]['id']);
1924         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
1925         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1926         $this->assertCount(2, $result['courses']);
1928         $result = core_course_external::get_courses_by_field('category', $category1->id);
1929         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1930         $this->assertCount(1, $result['courses']);
1931         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1933         $result = core_course_external::get_courses_by_field('shortname', 'c1');
1934         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1935         $this->assertCount(1, $result['courses']);
1936         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1938         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
1939         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1940         $this->assertCount(1, $result['courses']);
1941         $this->assertEquals($course2->id, $result['courses'][0]['id']);
1943         $result = core_course_external::get_courses_by_field('idnumber', 'x');
1944         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1945         $this->assertCount(0, $result['courses']);
1947         self::setUser($student1);
1948         // All visible courses  (including front page) for normal student.
1949         $result = core_course_external::get_courses_by_field();
1950         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1951         $this->assertCount(2, $result['courses']);
1952         $this->assertCount(28, $result['courses'][0]);
1953         $this->assertCount(28, $result['courses'][1]);
1955         $result = core_course_external::get_courses_by_field('id', $course1->id);
1956         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1957         $this->assertCount(1, $result['courses']);
1958         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1959         // Expect to receive all the files that a student can see.
1960         $this->assertCount(28, $result['courses'][0]);
1962         // Course 2 is not visible.
1963         $result = core_course_external::get_courses_by_field('id', $course2->id);
1964         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1965         $this->assertCount(0, $result['courses']);
1967         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
1968         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1969         $this->assertCount(1, $result['courses']);
1971         $result = core_course_external::get_courses_by_field('category', $category1->id);
1972         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1973         $this->assertCount(1, $result['courses']);
1974         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1976         $result = core_course_external::get_courses_by_field('shortname', 'c1');
1977         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1978         $this->assertCount(1, $result['courses']);
1979         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1981         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
1982         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1983         $this->assertCount(0, $result['courses']);
1985         $result = core_course_external::get_courses_by_field('idnumber', 'x');
1986         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1987         $this->assertCount(0, $result['courses']);
1989         self::setUser($user1);
1990         // All visible courses (including front page) for authenticated user.
1991         $result = core_course_external::get_courses_by_field();
1992         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1993         $this->assertCount(2, $result['courses']);
1994         $this->assertCount(28, $result['courses'][0]);  // Site course.
1995         $this->assertCount(12, $result['courses'][1]);  // Only public information, not enrolled.
1997         $result = core_course_external::get_courses_by_field('id', $course1->id);
1998         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1999         $this->assertCount(1, $result['courses']);
2000         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2001         // Expect to receive all the files that a authenticated can see.
2002         $this->assertCount(12, $result['courses'][0]);
2004         // Course 2 is not visible.
2005         $result = core_course_external::get_courses_by_field('id', $course2->id);
2006         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2007         $this->assertCount(0, $result['courses']);
2009         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2010         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2011         $this->assertCount(1, $result['courses']);
2013         $result = core_course_external::get_courses_by_field('category', $category1->id);
2014         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2015         $this->assertCount(1, $result['courses']);
2016         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2018         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2019         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2020         $this->assertCount(1, $result['courses']);
2021         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2023         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2024         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2025         $this->assertCount(0, $result['courses']);
2027         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2028         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2029         $this->assertCount(0, $result['courses']);
2030     }
2032     public function test_get_courses_by_field_invalid_field() {
2033         $this->expectException('invalid_parameter_exception');
2034         $result = core_course_external::get_courses_by_field('zyx', 'x');
2035     }
2037     public function test_get_courses_by_field_invalid_courses() {
2038         $result = core_course_external::get_courses_by_field('id', '-1');
2039         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2040         $this->assertCount(0, $result['courses']);
2041     }