MDL-33564 rss: Fixing missing param type
[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      * Tidy up open files that may be left open.
52      */
53     protected function tearDown() {
54         gc_collect_cycles();
55     }
57     /**
58      * Test create_categories
59      */
60     public function test_create_categories() {
62         global $DB;
64         $this->resetAfterTest(true);
66         // Set the required capabilities by the external function
67         $contextid = context_system::instance()->id;
68         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
70         // Create base categories.
71         $category1 = new stdClass();
72         $category1->name = 'Root Test Category 1';
73         $category2 = new stdClass();
74         $category2->name = 'Root Test Category 2';
75         $category2->idnumber = 'rootcattest2';
76         $category2->desc = 'Description for root test category 1';
77         $category2->theme = 'base';
78         $categories = array(
79             array('name' => $category1->name, 'parent' => 0),
80             array('name' => $category2->name, 'parent' => 0, 'idnumber' => $category2->idnumber,
81                 'description' => $category2->desc, 'theme' => $category2->theme)
82         );
84         $createdcats = core_course_external::create_categories($categories);
86         // We need to execute the return values cleaning process to simulate the web service server.
87         $createdcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdcats);
89         // Initially confirm that base data was inserted correctly.
90         $this->assertEquals($category1->name, $createdcats[0]['name']);
91         $this->assertEquals($category2->name, $createdcats[1]['name']);
93         // Save the ids.
94         $category1->id = $createdcats[0]['id'];
95         $category2->id = $createdcats[1]['id'];
97         // Create on sub category.
98         $category3 = new stdClass();
99         $category3->name = 'Sub Root Test Category 3';
100         $subcategories = array(
101             array('name' => $category3->name, 'parent' => $category1->id)
102         );
104         $createdsubcats = core_course_external::create_categories($subcategories);
106         // We need to execute the return values cleaning process to simulate the web service server.
107         $createdsubcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdsubcats);
109         // Confirm that sub categories were inserted correctly.
110         $this->assertEquals($category3->name, $createdsubcats[0]['name']);
112         // Save the ids.
113         $category3->id = $createdsubcats[0]['id'];
115         // Calling the ws function should provide a new sortorder to give category1,
116         // category2, category3. New course categories are ordered by id not name.
117         $category1 = $DB->get_record('course_categories', array('id' => $category1->id));
118         $category2 = $DB->get_record('course_categories', array('id' => $category2->id));
119         $category3 = $DB->get_record('course_categories', array('id' => $category3->id));
121         // sortorder sequence (and sortorder) must be:
122         // category 1
123         //   category 3
124         // category 2
125         $this->assertGreaterThan($category1->sortorder, $category3->sortorder);
126         $this->assertGreaterThan($category3->sortorder, $category2->sortorder);
128         // Call without required capability
129         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
130         $this->setExpectedException('required_capability_exception');
131         $createdsubcats = core_course_external::create_categories($subcategories);
133     }
135     /**
136      * Test delete categories
137      */
138     public function test_delete_categories() {
139         global $DB;
141         $this->resetAfterTest(true);
143         // Set the required capabilities by the external function
144         $contextid = context_system::instance()->id;
145         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
147         $category1  = self::getDataGenerator()->create_category();
148         $category2  = self::getDataGenerator()->create_category(
149                 array('parent' => $category1->id));
150         $category3  = self::getDataGenerator()->create_category();
151         $category4  = self::getDataGenerator()->create_category(
152                 array('parent' => $category3->id));
153         $category5  = self::getDataGenerator()->create_category(
154                 array('parent' => $category4->id));
156         //delete category 1 and 2 + delete category 4, category 5 moved under category 3
157         core_course_external::delete_categories(array(
158             array('id' => $category1->id, 'recursive' => 1),
159             array('id' => $category4->id)
160         ));
162         //check $category 1 and 2 are deleted
163         $notdeletedcount = $DB->count_records_select('course_categories',
164             'id IN ( ' . $category1->id . ',' . $category2->id . ',' . $category4->id . ')');
165         $this->assertEquals(0, $notdeletedcount);
167         //check that $category5 as $category3 for parent
168         $dbcategory5 = $DB->get_record('course_categories', array('id' => $category5->id));
169         $this->assertEquals($dbcategory5->path, $category3->path . '/' . $category5->id);
171          // Call without required capability
172         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
173         $this->setExpectedException('required_capability_exception');
174         $createdsubcats = core_course_external::delete_categories(
175                 array(array('id' => $category3->id)));
176     }
178     /**
179      * Test get categories
180      */
181     public function test_get_categories() {
182         global $DB;
184         $this->resetAfterTest(true);
186         $generatedcats = array();
187         $category1data['idnumber'] = 'idnumbercat1';
188         $category1data['name'] = 'Category 1 for PHPunit test';
189         $category1data['description'] = 'Category 1 description';
190         $category1data['descriptionformat'] = FORMAT_MOODLE;
191         $category1  = self::getDataGenerator()->create_category($category1data);
192         $generatedcats[$category1->id] = $category1;
193         $category2  = self::getDataGenerator()->create_category(
194                 array('parent' => $category1->id));
195         $generatedcats[$category2->id] = $category2;
196         $category6  = self::getDataGenerator()->create_category(
197                 array('parent' => $category1->id, 'visible' => 0));
198         $generatedcats[$category6->id] = $category6;
199         $category3  = self::getDataGenerator()->create_category();
200         $generatedcats[$category3->id] = $category3;
201         $category4  = self::getDataGenerator()->create_category(
202                 array('parent' => $category3->id));
203         $generatedcats[$category4->id] = $category4;
204         $category5  = self::getDataGenerator()->create_category(
205                 array('parent' => $category4->id));
206         $generatedcats[$category5->id] = $category5;
208         // Set the required capabilities by the external function.
209         $context = context_system::instance();
210         $roleid = $this->assignUserCapability('moodle/category:manage', $context->id);
212         // Retrieve category1 + sub-categories except not visible ones
213         $categories = core_course_external::get_categories(array(
214             array('key' => 'id', 'value' => $category1->id),
215             array('key' => 'visible', 'value' => 1)), 1);
217         // We need to execute the return values cleaning process to simulate the web service server.
218         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
220         // Check we retrieve the good total number of categories.
221         $this->assertEquals(2, count($categories));
223         // Check the return values
224         foreach ($categories as $category) {
225             $generatedcat = $generatedcats[$category['id']];
226             $this->assertEquals($category['idnumber'], $generatedcat->idnumber);
227             $this->assertEquals($category['name'], $generatedcat->name);
228             // Description was converted to the HTML format.
229             $this->assertEquals($category['description'], format_text($generatedcat->description, FORMAT_MOODLE, array('para' => false)));
230             $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
231         }
233         // Check different params.
234         $categories = core_course_external::get_categories(array(
235             array('key' => 'id', 'value' => $category1->id),
236             array('key' => 'idnumber', 'value' => $category1->idnumber),
237             array('key' => 'visible', 'value' => 1)), 0);
239         // We need to execute the return values cleaning process to simulate the web service server.
240         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
242         $this->assertEquals(1, count($categories));
244         // Retrieve categories from parent.
245         $categories = core_course_external::get_categories(array(
246             array('key' => 'parent', 'value' => $category3->id)), 1);
247         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
249         $this->assertEquals(2, count($categories));
251         // Retrieve all categories.
252         $categories = core_course_external::get_categories();
254         // We need to execute the return values cleaning process to simulate the web service server.
255         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
257         $this->assertEquals($DB->count_records('course_categories'), count($categories));
259         // Call without required capability (it will fail cause of the search on idnumber).
260         $this->unassignUserCapability('moodle/category:manage', $context->id, $roleid);
261         $this->setExpectedException('moodle_exception');
262         $categories = core_course_external::get_categories(array(
263             array('key' => 'id', 'value' => $category1->id),
264             array('key' => 'idnumber', 'value' => $category1->idnumber),
265             array('key' => 'visible', 'value' => 1)), 0);
266     }
268     /**
269      * Test update_categories
270      */
271     public function test_update_categories() {
272         global $DB;
274         $this->resetAfterTest(true);
276         // Set the required capabilities by the external function
277         $contextid = context_system::instance()->id;
278         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
280         // Create base categories.
281         $category1data['idnumber'] = 'idnumbercat1';
282         $category1data['name'] = 'Category 1 for PHPunit test';
283         $category1data['description'] = 'Category 1 description';
284         $category1data['descriptionformat'] = FORMAT_MOODLE;
285         $category1  = self::getDataGenerator()->create_category($category1data);
286         $category2  = self::getDataGenerator()->create_category(
287                 array('parent' => $category1->id));
288         $category3  = self::getDataGenerator()->create_category();
289         $category4  = self::getDataGenerator()->create_category(
290                 array('parent' => $category3->id));
291         $category5  = self::getDataGenerator()->create_category(
292                 array('parent' => $category4->id));
294         // We update all category1 attribut.
295         // Then we move cat4 and cat5 parent: cat3 => cat1
296         $categories = array(
297             array('id' => $category1->id,
298                 'name' => $category1->name . '_updated',
299                 'idnumber' => $category1->idnumber . '_updated',
300                 'description' => $category1->description . '_updated',
301                 'descriptionformat' => FORMAT_HTML,
302                 'theme' => $category1->theme),
303             array('id' => $category4->id, 'parent' => $category1->id));
305         core_course_external::update_categories($categories);
307         // Check the values were updated.
308         $dbcategories = $DB->get_records_select('course_categories',
309                 'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
310                 . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
311         $this->assertEquals($category1->name . '_updated',
312                 $dbcategories[$category1->id]->name);
313         $this->assertEquals($category1->idnumber . '_updated',
314                 $dbcategories[$category1->id]->idnumber);
315         $this->assertEquals($category1->description . '_updated',
316                 $dbcategories[$category1->id]->description);
317         $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
319         // Check that category4 and category5 have been properly moved.
320         $this->assertEquals('/' . $category1->id . '/' . $category4->id,
321                 $dbcategories[$category4->id]->path);
322         $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
323                 $dbcategories[$category5->id]->path);
325         // Call without required capability.
326         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
327         $this->setExpectedException('required_capability_exception');
328         core_course_external::update_categories($categories);
329     }
331     /**
332      * Test create_courses
333      */
334     public function test_create_courses() {
335         global $DB;
337         $this->resetAfterTest(true);
339         // Enable course completion.
340         set_config('enablecompletion', 1);
341         // Enable course themes.
342         set_config('allowcoursethemes', 1);
344         // Set the required capabilities by the external function
345         $contextid = context_system::instance()->id;
346         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
347         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
349         $category  = self::getDataGenerator()->create_category();
351         // Create base categories.
352         $course1['fullname'] = 'Test course 1';
353         $course1['shortname'] = 'Testcourse1';
354         $course1['categoryid'] = $category->id;
355         $course2['fullname'] = 'Test course 2';
356         $course2['shortname'] = 'Testcourse2';
357         $course2['categoryid'] = $category->id;
358         $course2['idnumber'] = 'testcourse2idnumber';
359         $course2['summary'] = 'Description for course 2';
360         $course2['summaryformat'] = FORMAT_MOODLE;
361         $course2['format'] = 'weeks';
362         $course2['showgrades'] = 1;
363         $course2['newsitems'] = 3;
364         $course2['startdate'] = 1420092000; // 01/01/2015
365         $course2['numsections'] = 4;
366         $course2['maxbytes'] = 100000;
367         $course2['showreports'] = 1;
368         $course2['visible'] = 0;
369         $course2['hiddensections'] = 0;
370         $course2['groupmode'] = 0;
371         $course2['groupmodeforce'] = 0;
372         $course2['defaultgroupingid'] = 0;
373         $course2['enablecompletion'] = 1;
374         $course2['completionnotify'] = 1;
375         $course2['lang'] = 'en';
376         $course2['forcetheme'] = 'base';
377         $course3['fullname'] = 'Test course 3';
378         $course3['shortname'] = 'Testcourse3';
379         $course3['categoryid'] = $category->id;
380         $course3['format'] = 'topics';
381         $course3options = array('numsections' => 8,
382             'hiddensections' => 1,
383             'coursedisplay' => 1);
384         $course3['courseformatoptions'] = array();
385         foreach ($course3options as $key => $value) {
386             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
387         }
388         $courses = array($course1, $course2, $course3);
390         $createdcourses = core_course_external::create_courses($courses);
392         // We need to execute the return values cleaning process to simulate the web service server.
393         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
395         // Check that right number of courses were created.
396         $this->assertEquals(3, count($createdcourses));
398         // Check that the courses were correctly created.
399         foreach ($createdcourses as $createdcourse) {
400             $courseinfo = course_get_format($createdcourse['id'])->get_course();
402             if ($createdcourse['shortname'] == $course2['shortname']) {
403                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
404                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
405                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
406                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
407                 $this->assertEquals($courseinfo->summary, $course2['summary']);
408                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
409                 $this->assertEquals($courseinfo->format, $course2['format']);
410                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
411                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
412                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
413                 $this->assertEquals($courseinfo->numsections, $course2['numsections']);
414                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
415                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
416                 $this->assertEquals($courseinfo->visible, $course2['visible']);
417                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
418                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
419                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
420                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
421                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
422                 $this->assertEquals($courseinfo->lang, $course2['lang']);
423                 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
425                 // We enabled completion at the beginning of the test.
426                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
428             } else if ($createdcourse['shortname'] == $course1['shortname']) {
429                 $courseconfig = get_config('moodlecourse');
430                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
431                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
432                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
433                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
434                 $this->assertEquals($courseinfo->format, $courseconfig->format);
435                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
436                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
437                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
438                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
439                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
440                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
441                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
442             } else if ($createdcourse['shortname'] == $course3['shortname']) {
443                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
444                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
445                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
446                 $this->assertEquals($courseinfo->format, $course3['format']);
447                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
448                 $this->assertEquals($courseinfo->numsections, $course3options['numsections']);
449                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
450             } else {
451                 throw moodle_exception('Unexpected shortname');
452             }
453         }
455         // Call without required capability
456         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
457         $this->setExpectedException('required_capability_exception');
458         $createdsubcats = core_course_external::create_courses($courses);
459     }
461     /**
462      * Test delete_courses
463      */
464     public function test_delete_courses() {
465         global $DB, $USER;
467         $this->resetAfterTest(true);
469         // Admin can delete a course.
470         $this->setAdminUser();
471         // Validate_context() will fail as the email is not set by $this->setAdminUser().
472         $USER->email = 'emailtopass@example.com';
474         $course1  = self::getDataGenerator()->create_course();
475         $course2  = self::getDataGenerator()->create_course();
476         $course3  = self::getDataGenerator()->create_course();
478         // Delete courses.
479         $result = core_course_external::delete_courses(array($course1->id, $course2->id));
480         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
481         // Check for 0 warnings.
482         $this->assertEquals(0, count($result['warnings']));
484         // Check $course 1 and 2 are deleted.
485         $notdeletedcount = $DB->count_records_select('course',
486             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
487         $this->assertEquals(0, $notdeletedcount);
489         // Try to delete non-existent course.
490         $result = core_course_external::delete_courses(array($course1->id));
491         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
492         // Check for 1 warnings.
493         $this->assertEquals(1, count($result['warnings']));
495         // Try to delete Frontpage course.
496         $result = core_course_external::delete_courses(array(0));
497         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
498         // Check for 1 warnings.
499         $this->assertEquals(1, count($result['warnings']));
501          // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
502         $student1 = self::getDataGenerator()->create_user();
503         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
504         $this->getDataGenerator()->enrol_user($student1->id,
505                                               $course3->id,
506                                               $studentrole->id);
507         $this->setUser($student1);
508         $result = core_course_external::delete_courses(array($course3->id));
509         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
510         // Check for 1 warnings.
511         $this->assertEquals(1, count($result['warnings']));
513          // Fail when the user is not allow to access the course (enrolled) or is not admin.
514         $this->setGuestUser();
515         $this->setExpectedException('require_login_exception');
517         $result = core_course_external::delete_courses(array($course3->id));
518         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
519     }
521     /**
522      * Test get_courses
523      */
524     public function test_get_courses () {
525         global $DB;
527         $this->resetAfterTest(true);
529         $generatedcourses = array();
530         $coursedata['idnumber'] = 'idnumbercourse1';
531         $coursedata['fullname'] = 'Course 1 for PHPunit test';
532         $coursedata['summary'] = 'Course 1 description';
533         $coursedata['summaryformat'] = FORMAT_MOODLE;
534         $course1  = self::getDataGenerator()->create_course($coursedata);
535         $generatedcourses[$course1->id] = $course1;
536         $course2  = self::getDataGenerator()->create_course();
537         $generatedcourses[$course2->id] = $course2;
538         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
539         $generatedcourses[$course3->id] = $course3;
541         // Set the required capabilities by the external function.
542         $context = context_system::instance();
543         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
544         $this->assignUserCapability('moodle/course:update',
545                 context_course::instance($course1->id)->id, $roleid);
546         $this->assignUserCapability('moodle/course:update',
547                 context_course::instance($course2->id)->id, $roleid);
548         $this->assignUserCapability('moodle/course:update',
549                 context_course::instance($course3->id)->id, $roleid);
551         $courses = core_course_external::get_courses(array('ids' =>
552             array($course1->id, $course2->id)));
554         // We need to execute the return values cleaning process to simulate the web service server.
555         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
557         // Check we retrieve the good total number of categories.
558         $this->assertEquals(2, count($courses));
560         foreach ($courses as $course) {
561             $dbcourse = $generatedcourses[$course['id']];
562             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
563             $this->assertEquals($course['fullname'], $dbcourse->fullname);
564             // Summary was converted to the HTML format.
565             $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
566             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
567             $this->assertEquals($course['shortname'], $dbcourse->shortname);
568             $this->assertEquals($course['categoryid'], $dbcourse->category);
569             $this->assertEquals($course['format'], $dbcourse->format);
570             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
571             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
572             $this->assertEquals($course['startdate'], $dbcourse->startdate);
573             $this->assertEquals($course['numsections'], $dbcourse->numsections);
574             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
575             $this->assertEquals($course['showreports'], $dbcourse->showreports);
576             $this->assertEquals($course['visible'], $dbcourse->visible);
577             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
578             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
579             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
580             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
581             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
582             $this->assertEquals($course['lang'], $dbcourse->lang);
583             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
584             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
585             if ($dbcourse->format === 'topics') {
586                 $this->assertEquals($course['courseformatoptions'], array(
587                     array('name' => 'numsections', 'value' => $dbcourse->numsections),
588                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
589                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
590                 ));
591             }
592         }
594         // Get all courses in the DB
595         $courses = core_course_external::get_courses(array());
597         // We need to execute the return values cleaning process to simulate the web service server.
598         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
600         $this->assertEquals($DB->count_records('course'), count($courses));
601     }
603     /**
604      * Create a course with contents
605      * @return array A list with the course object and course modules objects
606      */
607     private function prepare_get_course_contents_test() {
608         $course  = self::getDataGenerator()->create_course();
609         $forumdescription = 'This is the forum description';
610         $forum = $this->getDataGenerator()->create_module('forum',
611             array('course' => $course->id, 'intro' => $forumdescription),
612             array('showdescription' => true));
613         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
614         $data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
615         $datacm = get_coursemodule_from_instance('page', $data->id);
616         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
617         $pagecm = get_coursemodule_from_instance('page', $page->id);
618         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
619                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
620         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
621             'intro' => $labeldescription));
622         $labelcm = get_coursemodule_from_instance('label', $label->id);
623         $url = $this->getDataGenerator()->create_module('url', array('course' => $course->id,
624             'name' => 'URL: % & $ ../', 'section' => 2));
625         $urlcm = get_coursemodule_from_instance('url', $url->id);
627         // Set the required capabilities by the external function.
628         $context = context_course::instance($course->id);
629         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
630         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
632         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
633     }
635     /**
636      * Test get_course_contents
637      */
638     public function test_get_course_contents() {
639         $this->resetAfterTest(true);
641         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
643         $sections = core_course_external::get_course_contents($course->id, array());
644         // We need to execute the return values cleaning process to simulate the web service server.
645         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
647         // Check that forum and label descriptions are correctly returned.
648         $firstsection = array_shift($sections);
649         $lastsection = array_pop($sections);
651         $modinfo = get_fast_modinfo($course);
652         $testexecuted = 0;
653         foreach ($firstsection['modules'] as $module) {
654             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
655                 $cm = $modinfo->cms[$forumcm->id];
656                 $formattedtext = format_text($cm->content, FORMAT_HTML,
657                     array('noclean' => true, 'para' => false, 'filter' => false));
658                 $this->assertEquals($formattedtext, $module['description']);
659                 $this->assertEquals($forumcm->instance, $module['instance']);
660                 $testexecuted = $testexecuted + 1;
661             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
662                 $cm = $modinfo->cms[$labelcm->id];
663                 $formattedtext = format_text($cm->content, FORMAT_HTML,
664                     array('noclean' => true, 'para' => false, 'filter' => false));
665                 $this->assertEquals($formattedtext, $module['description']);
666                 $this->assertEquals($labelcm->instance, $module['instance']);
667                 $testexecuted = $testexecuted + 1;
668             }
669         }
670         $this->assertEquals(2, $testexecuted);
672         // Check that the only return section has the 5 created modules.
673         $this->assertCount(4, $firstsection['modules']);
674         $this->assertCount(1, $lastsection['modules']);
676         try {
677             $sections = core_course_external::get_course_contents($course->id,
678                                                                     array(array("name" => "invalid", "value" => 1)));
679             $this->fail('Exception expected due to invalid option.');
680         } catch (moodle_exception $e) {
681             $this->assertEquals('errorinvalidparam', $e->errorcode);
682         }
683     }
686     /**
687      * Test get_course_contents excluding modules
688      */
689     public function test_get_course_contents_excluding_modules() {
690         $this->resetAfterTest(true);
692         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
694         // Test exclude modules.
695         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
697         // We need to execute the return values cleaning process to simulate the web service server.
698         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
700         $firstsection = array_shift($sections);
701         $lastsection = array_pop($sections);
703         $this->assertEmpty($firstsection['modules']);
704         $this->assertEmpty($lastsection['modules']);
705     }
707     /**
708      * Test get_course_contents excluding contents
709      */
710     public function test_get_course_contents_excluding_contents() {
711         $this->resetAfterTest(true);
713         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
715         // Test exclude modules.
716         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
718         // We need to execute the return values cleaning process to simulate the web service server.
719         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
721         foreach ($sections as $section) {
722             foreach ($section['modules'] as $module) {
723                 // Only resources return contents.
724                 if (isset($module['contents'])) {
725                     $this->assertEmpty($module['contents']);
726                 }
727             }
728         }
729     }
731     /**
732      * Test get_course_contents filtering by section number
733      */
734     public function test_get_course_contents_section_number() {
735         $this->resetAfterTest(true);
737         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
739         // Test exclude modules.
740         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
742         // We need to execute the return values cleaning process to simulate the web service server.
743         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
745         $this->assertCount(1, $sections);
746         $this->assertCount(4, $sections[0]['modules']);
747     }
749     /**
750      * Test get_course_contents filtering by cmid
751      */
752     public function test_get_course_contents_cmid() {
753         $this->resetAfterTest(true);
755         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
757         // Test exclude modules.
758         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
760         // We need to execute the return values cleaning process to simulate the web service server.
761         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
763         $this->assertCount(2, $sections);
764         $this->assertCount(1, $sections[0]['modules']);
765         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
766     }
769     /**
770      * Test get_course_contents filtering by cmid and section
771      */
772     public function test_get_course_contents_section_cmid() {
773         $this->resetAfterTest(true);
775         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
777         // Test exclude modules.
778         $sections = core_course_external::get_course_contents($course->id, array(
779                                                                         array("name" => "cmid", "value" => $forumcm->id),
780                                                                         array("name" => "sectionnumber", "value" => 0)
781                                                                         ));
783         // We need to execute the return values cleaning process to simulate the web service server.
784         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
786         $this->assertCount(1, $sections);
787         $this->assertCount(1, $sections[0]['modules']);
788         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
789     }
791     /**
792      * Test get_course_contents filtering by modname
793      */
794     public function test_get_course_contents_modname() {
795         $this->resetAfterTest(true);
797         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
799         // Test exclude modules.
800         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
802         // We need to execute the return values cleaning process to simulate the web service server.
803         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
805         $this->assertCount(2, $sections);
806         $this->assertCount(1, $sections[0]['modules']);
807         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
808     }
810     /**
811      * Test get_course_contents filtering by modname
812      */
813     public function test_get_course_contents_modid() {
814         $this->resetAfterTest(true);
816         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
818         // Test exclude modules.
819         $sections = core_course_external::get_course_contents($course->id, array(
820                                                                             array("name" => "modname", "value" => "page"),
821                                                                             array("name" => "modid", "value" => $pagecm->instance),
822                                                                             ));
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         $this->assertCount(2, $sections);
828         $this->assertCount(1, $sections[0]['modules']);
829         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
830         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
831     }
833     /**
834      * Test duplicate_course
835      */
836     public function test_duplicate_course() {
837         $this->resetAfterTest(true);
839         // Create one course with three modules.
840         $course  = self::getDataGenerator()->create_course();
841         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
842         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
843         $forumcontext = context_module::instance($forum->cmid);
844         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
845         $datacontext = context_module::instance($data->cmid);
846         $datacm = get_coursemodule_from_instance('page', $data->id);
847         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
848         $pagecontext = context_module::instance($page->cmid);
849         $pagecm = get_coursemodule_from_instance('page', $page->id);
851         // Set the required capabilities by the external function.
852         $coursecontext = context_course::instance($course->id);
853         $categorycontext = context_coursecat::instance($course->category);
854         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
855         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
856         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
857         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
858         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
859         // Optional capabilities to copy user data.
860         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
861         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
863         $newcourse['fullname'] = 'Course duplicate';
864         $newcourse['shortname'] = 'courseduplicate';
865         $newcourse['categoryid'] = $course->category;
866         $newcourse['visible'] = true;
867         $newcourse['options'][] = array('name' => 'users', 'value' => true);
869         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
870                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
872         // We need to execute the return values cleaning process to simulate the web service server.
873         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
875         // Check that the course has been duplicated.
876         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
877     }
879     /**
880      * Test update_courses
881      */
882     public function test_update_courses() {
883         global $DB, $CFG, $USER, $COURSE;
885         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
886         // trick because we are both updating and getting (for testing) course information
887         // in the same request and core_course_external::update_courses()
888         // is overwriting $COURSE all over the time with OLD values, so later
889         // use of get_course() fetches those OLD values instead of the updated ones.
890         // See MDL-39723 for more info.
891         $origcourse = clone($COURSE);
893         $this->resetAfterTest(true);
895         // Set the required capabilities by the external function.
896         $contextid = context_system::instance()->id;
897         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
898         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
899         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
900         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
901         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
902         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
903         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
904         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
906         // Create category and course.
907         $category1  = self::getDataGenerator()->create_category();
908         $category2  = self::getDataGenerator()->create_category();
909         $originalcourse1 = self::getDataGenerator()->create_course();
910         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
911         $originalcourse2 = self::getDataGenerator()->create_course();
912         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
914         // Course values to be updated.
915         $course1['id'] = $originalcourse1->id;
916         $course1['fullname'] = 'Updated test course 1';
917         $course1['shortname'] = 'Udestedtestcourse1';
918         $course1['categoryid'] = $category1->id;
919         $course2['id'] = $originalcourse2->id;
920         $course2['fullname'] = 'Updated test course 2';
921         $course2['shortname'] = 'Updestedtestcourse2';
922         $course2['categoryid'] = $category2->id;
923         $course2['idnumber'] = 'Updatedidnumber2';
924         $course2['summary'] = 'Updaated description for course 2';
925         $course2['summaryformat'] = FORMAT_HTML;
926         $course2['format'] = 'topics';
927         $course2['showgrades'] = 1;
928         $course2['newsitems'] = 3;
929         $course2['startdate'] = 1420092000; // 01/01/2015.
930         $course2['numsections'] = 4;
931         $course2['maxbytes'] = 100000;
932         $course2['showreports'] = 1;
933         $course2['visible'] = 0;
934         $course2['hiddensections'] = 0;
935         $course2['groupmode'] = 0;
936         $course2['groupmodeforce'] = 0;
937         $course2['defaultgroupingid'] = 0;
938         $course2['enablecompletion'] = 1;
939         $course2['lang'] = 'en';
940         $course2['forcetheme'] = 'base';
941         $courses = array($course1, $course2);
943         $updatedcoursewarnings = core_course_external::update_courses($courses);
944         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
945                                                                     $updatedcoursewarnings);
946         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
948         // Check that right number of courses were created.
949         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
951         // Check that the courses were correctly created.
952         foreach ($courses as $course) {
953             $courseinfo = course_get_format($course['id'])->get_course();
954             if ($course['id'] == $course2['id']) {
955                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
956                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
957                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
958                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
959                 $this->assertEquals($course2['summary'], $courseinfo->summary);
960                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
961                 $this->assertEquals($course2['format'], $courseinfo->format);
962                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
963                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
964                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
965                 $this->assertEquals($course2['numsections'], $courseinfo->numsections);
966                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
967                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
968                 $this->assertEquals($course2['visible'], $courseinfo->visible);
969                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
970                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
971                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
972                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
973                 $this->assertEquals($course2['lang'], $courseinfo->lang);
975                 if (!empty($CFG->allowcoursethemes)) {
976                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
977                 }
979                 if (completion_info::is_enabled_for_site()) {
980                     $this->assertEquals($course2['enabledcompletion'], $courseinfo->enablecompletion);
981                 }
982             } else if ($course['id'] == $course1['id']) {
983                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
984                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
985                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
986                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
987                 $this->assertEquals('topics', $courseinfo->format);
988                 $this->assertEquals(5, $courseinfo->numsections);
989                 $this->assertEquals(0, $courseinfo->newsitems);
990                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
991             } else {
992                 throw moodle_exception('Unexpected shortname');
993             }
994         }
996         $courses = array($course1);
997         // Try update course without update capability.
998         $user = self::getDataGenerator()->create_user();
999         $this->setUser($user);
1000         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1001         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1002         $updatedcoursewarnings = core_course_external::update_courses($courses);
1003         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1004                                                                     $updatedcoursewarnings);
1005         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1007         // Try update course category without capability.
1008         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1009         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1010         $user = self::getDataGenerator()->create_user();
1011         $this->setUser($user);
1012         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1013         $course1['categoryid'] = $category2->id;
1014         $courses = array($course1);
1015         $updatedcoursewarnings = core_course_external::update_courses($courses);
1016         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1017                                                                     $updatedcoursewarnings);
1018         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1020         // Try update course fullname without capability.
1021         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1022         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1023         $user = self::getDataGenerator()->create_user();
1024         $this->setUser($user);
1025         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1026         $updatedcoursewarnings = core_course_external::update_courses($courses);
1027         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1028                                                                     $updatedcoursewarnings);
1029         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1030         $course1['fullname'] = 'Testing fullname without permission';
1031         $courses = array($course1);
1032         $updatedcoursewarnings = core_course_external::update_courses($courses);
1033         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1034                                                                     $updatedcoursewarnings);
1035         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1037         // Try update course shortname without capability.
1038         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1039         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1040         $user = self::getDataGenerator()->create_user();
1041         $this->setUser($user);
1042         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1043         $updatedcoursewarnings = core_course_external::update_courses($courses);
1044         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1045                                                                     $updatedcoursewarnings);
1046         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1047         $course1['shortname'] = 'Testing shortname without permission';
1048         $courses = array($course1);
1049         $updatedcoursewarnings = core_course_external::update_courses($courses);
1050         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1051                                                                     $updatedcoursewarnings);
1052         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1054         // Try update course idnumber without capability.
1055         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1056         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1057         $user = self::getDataGenerator()->create_user();
1058         $this->setUser($user);
1059         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1060         $updatedcoursewarnings = core_course_external::update_courses($courses);
1061         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1062                                                                     $updatedcoursewarnings);
1063         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1064         $course1['idnumber'] = 'NEWIDNUMBER';
1065         $courses = array($course1);
1066         $updatedcoursewarnings = core_course_external::update_courses($courses);
1067         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1068                                                                     $updatedcoursewarnings);
1069         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1071         // Try update course summary without capability.
1072         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1073         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1074         $user = self::getDataGenerator()->create_user();
1075         $this->setUser($user);
1076         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1077         $updatedcoursewarnings = core_course_external::update_courses($courses);
1078         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1079                                                                     $updatedcoursewarnings);
1080         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1081         $course1['summary'] = 'New summary';
1082         $courses = array($course1);
1083         $updatedcoursewarnings = core_course_external::update_courses($courses);
1084         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1085                                                                     $updatedcoursewarnings);
1086         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1088         // Try update course with invalid summary format.
1089         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1090         $user = self::getDataGenerator()->create_user();
1091         $this->setUser($user);
1092         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1093         $updatedcoursewarnings = core_course_external::update_courses($courses);
1094         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1095                                                                     $updatedcoursewarnings);
1096         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1097         $course1['summaryformat'] = 10;
1098         $courses = array($course1);
1099         $updatedcoursewarnings = core_course_external::update_courses($courses);
1100         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1101                                                                     $updatedcoursewarnings);
1102         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1104         // Try update course visibility without capability.
1105         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1106         $user = self::getDataGenerator()->create_user();
1107         $this->setUser($user);
1108         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1109         $course1['summaryformat'] = FORMAT_MOODLE;
1110         $courses = array($course1);
1111         $updatedcoursewarnings = core_course_external::update_courses($courses);
1112         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1113                                                                     $updatedcoursewarnings);
1114         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1115         $course1['visible'] = 0;
1116         $courses = array($course1);
1117         $updatedcoursewarnings = core_course_external::update_courses($courses);
1118         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1119                                                                     $updatedcoursewarnings);
1120         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1121     }
1123     /**
1124      * Test delete course_module.
1125      */
1126     public function test_delete_modules() {
1127         global $DB;
1129         // Ensure we reset the data after this test.
1130         $this->resetAfterTest(true);
1132         // Create a user.
1133         $user = self::getDataGenerator()->create_user();
1135         // Set the tests to run as the user.
1136         self::setUser($user);
1138         // Create a course to add the modules.
1139         $course = self::getDataGenerator()->create_course();
1141         // Create two test modules.
1142         $record = new stdClass();
1143         $record->course = $course->id;
1144         $module1 = self::getDataGenerator()->create_module('forum', $record);
1145         $module2 = self::getDataGenerator()->create_module('assign', $record);
1147         // Check the forum was correctly created.
1148         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1150         // Check the assignment was correctly created.
1151         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1153         // Check data exists in the course modules table.
1154         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1155                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1157         // Enrol the user in the course.
1158         $enrol = enrol_get_plugin('manual');
1159         $enrolinstances = enrol_get_instances($course->id, true);
1160         foreach ($enrolinstances as $courseenrolinstance) {
1161             if ($courseenrolinstance->enrol == "manual") {
1162                 $instance = $courseenrolinstance;
1163                 break;
1164             }
1165         }
1166         $enrol->enrol_user($instance, $user->id);
1168         // Assign capabilities to delete module 1.
1169         $modcontext = context_module::instance($module1->cmid);
1170         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1172         // Assign capabilities to delete module 2.
1173         $modcontext = context_module::instance($module2->cmid);
1174         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1175         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1177         // Deleting these module instances.
1178         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1180         // Check the forum was deleted.
1181         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1183         // Check the assignment was deleted.
1184         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1186         // Check we retrieve no data in the course modules table.
1187         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1188                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1190         // Call with non-existent course module id and ensure exception thrown.
1191         try {
1192             core_course_external::delete_modules(array('1337'));
1193             $this->fail('Exception expected due to missing course module.');
1194         } catch (dml_missing_record_exception $e) {
1195             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1196         }
1198         // Create two modules.
1199         $module1 = self::getDataGenerator()->create_module('forum', $record);
1200         $module2 = self::getDataGenerator()->create_module('assign', $record);
1202         // Since these modules were recreated the user will not have capabilities
1203         // to delete them, ensure exception is thrown if they try.
1204         try {
1205             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1206             $this->fail('Exception expected due to missing capability.');
1207         } catch (moodle_exception $e) {
1208             $this->assertEquals('nopermissions', $e->errorcode);
1209         }
1211         // Unenrol user from the course.
1212         $enrol->unenrol_user($instance, $user->id);
1214         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1215         try {
1216             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1217             $this->fail('Exception expected due to being unenrolled from the course.');
1218         } catch (moodle_exception $e) {
1219             $this->assertEquals('requireloginerror', $e->errorcode);
1220         }
1221     }
1223     /**
1224      * Test import_course into an empty course
1225      */
1226     public function test_import_course_empty() {
1227         global $USER;
1229         $this->resetAfterTest(true);
1231         $course1  = self::getDataGenerator()->create_course();
1232         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1233         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1235         $course2  = self::getDataGenerator()->create_course();
1237         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1238         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1240         // Verify the state of the courses before we do the import.
1241         $this->assertCount(2, $course1cms);
1242         $this->assertEmpty($course2cms);
1244         // Setup the user to run the operation (ugly hack because validate_context() will
1245         // fail as the email is not set by $this->setAdminUser()).
1246         $this->setAdminUser();
1247         $USER->email = 'emailtopass@example.com';
1249         // Import from course1 to course2.
1250         core_course_external::import_course($course1->id, $course2->id, 0);
1252         // Verify that now we have two modules in both courses.
1253         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1254         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1255         $this->assertCount(2, $course1cms);
1256         $this->assertCount(2, $course2cms);
1258         // Verify that the names transfered across correctly.
1259         foreach ($course2cms as $cm) {
1260             if ($cm->modname === 'page') {
1261                 $this->assertEquals($cm->name, $page->name);
1262             } else if ($cm->modname === 'forum') {
1263                 $this->assertEquals($cm->name, $forum->name);
1264             } else {
1265                 $this->fail('Unknown CM found.');
1266             }
1267         }
1268     }
1270     /**
1271      * Test import_course into an filled course
1272      */
1273     public function test_import_course_filled() {
1274         global $USER;
1276         $this->resetAfterTest(true);
1278         // Add forum and page to course1.
1279         $course1  = self::getDataGenerator()->create_course();
1280         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1281         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1283         // Add quiz to course 2.
1284         $course2  = self::getDataGenerator()->create_course();
1285         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1287         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1288         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1290         // Verify the state of the courses before we do the import.
1291         $this->assertCount(2, $course1cms);
1292         $this->assertCount(1, $course2cms);
1294         // Setup the user to run the operation (ugly hack because validate_context() will
1295         // fail as the email is not set by $this->setAdminUser()).
1296         $this->setAdminUser();
1297         $USER->email = 'emailtopass@example.com';
1299         // Import from course1 to course2 without deleting content.
1300         core_course_external::import_course($course1->id, $course2->id, 0);
1302         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1304         // Verify that now we have three modules in course2.
1305         $this->assertCount(3, $course2cms);
1307         // Verify that the names transfered across correctly.
1308         foreach ($course2cms as $cm) {
1309             if ($cm->modname === 'page') {
1310                 $this->assertEquals($cm->name, $page->name);
1311             } else if ($cm->modname === 'forum') {
1312                 $this->assertEquals($cm->name, $forum->name);
1313             } else if ($cm->modname === 'quiz') {
1314                 $this->assertEquals($cm->name, $quiz->name);
1315             } else {
1316                 $this->fail('Unknown CM found.');
1317             }
1318         }
1319     }
1321     /**
1322      * Test import_course with only blocks set to backup
1323      */
1324     public function test_import_course_blocksonly() {
1325         global $USER, $DB;
1327         $this->resetAfterTest(true);
1329         // Add forum and page to course1.
1330         $course1  = self::getDataGenerator()->create_course();
1331         $course1ctx = context_course::instance($course1->id);
1332         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1333         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1335         $course2  = self::getDataGenerator()->create_course();
1336         $course2ctx = context_course::instance($course2->id);
1337         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1338         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1340         // Setup the user to run the operation (ugly hack because validate_context() will
1341         // fail as the email is not set by $this->setAdminUser()).
1342         $this->setAdminUser();
1343         $USER->email = 'emailtopass@example.com';
1345         // Import from course1 to course2 without deleting content, but excluding
1346         // activities.
1347         $options = array(
1348             array('name' => 'activities', 'value' => 0),
1349             array('name' => 'blocks', 'value' => 1),
1350             array('name' => 'filters', 'value' => 0),
1351         );
1353         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1355         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1356         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1357         // Check that course modules haven't changed, but that blocks have.
1358         $this->assertEquals($initialcmcount, $newcmcount);
1359         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1360     }
1362     /**
1363      * Test import_course into an filled course, deleting content.
1364      */
1365     public function test_import_course_deletecontent() {
1366         global $USER;
1367         $this->resetAfterTest(true);
1369         // Add forum and page to course1.
1370         $course1  = self::getDataGenerator()->create_course();
1371         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1372         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1374         // Add quiz to course 2.
1375         $course2  = self::getDataGenerator()->create_course();
1376         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1378         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1379         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1381         // Verify the state of the courses before we do the import.
1382         $this->assertCount(2, $course1cms);
1383         $this->assertCount(1, $course2cms);
1385         // Setup the user to run the operation (ugly hack because validate_context() will
1386         // fail as the email is not set by $this->setAdminUser()).
1387         $this->setAdminUser();
1388         $USER->email = 'emailtopass@example.com';
1390         // Import from course1 to course2,  deleting content.
1391         core_course_external::import_course($course1->id, $course2->id, 1);
1393         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1395         // Verify that now we have two modules in course2.
1396         $this->assertCount(2, $course2cms);
1398         // Verify that the course only contains the imported modules.
1399         foreach ($course2cms as $cm) {
1400             if ($cm->modname === 'page') {
1401                 $this->assertEquals($cm->name, $page->name);
1402             } else if ($cm->modname === 'forum') {
1403                 $this->assertEquals($cm->name, $forum->name);
1404             } else {
1405                 $this->fail('Unknown CM found: '.$cm->name);
1406             }
1407         }
1408     }
1410     /**
1411      * Ensure import_course handles incorrect deletecontent option correctly.
1412      */
1413     public function test_import_course_invalid_deletecontent_option() {
1414         $this->resetAfterTest(true);
1416         $course1  = self::getDataGenerator()->create_course();
1417         $course2  = self::getDataGenerator()->create_course();
1419         $this->setExpectedException('moodle_exception', get_string('invalidextparam', 'webservice', -1));
1420         // Import from course1 to course2, with invalid option
1421         core_course_external::import_course($course1->id, $course2->id, -1);;
1422     }
1424     /**
1425      * Test view_course function
1426      */
1427     public function test_view_course() {
1429         $this->resetAfterTest();
1431         // Course without sections.
1432         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1433         $this->setAdminUser();
1435         // Redirect events to the sink, so we can recover them later.
1436         $sink = $this->redirectEvents();
1438         $result = core_course_external::view_course($course->id, 1);
1439         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1440         $events = $sink->get_events();
1441         $event = reset($events);
1443         // Check the event details are correct.
1444         $this->assertInstanceOf('\core\event\course_viewed', $event);
1445         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1446         $this->assertEquals(1, $event->other['coursesectionnumber']);
1448         $result = core_course_external::view_course($course->id);
1449         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1450         $events = $sink->get_events();
1451         $event = array_pop($events);
1452         $sink->close();
1454         // Check the event details are correct.
1455         $this->assertInstanceOf('\core\event\course_viewed', $event);
1456         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1457         $this->assertEmpty($event->other);
1459     }