on-demand release 4.0dev+
[moodle.git] / admin / tool / uploadcourse / tests / course_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  * File containing tests for the course class.
19  *
20  * @package    tool_uploadcourse
21  * @copyright  2013 Frédéric Massart
22  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 defined('MOODLE_INTERNAL') || die();
27 global $CFG;
29 /**
30  * Course test case.
31  *
32  * @package    tool_uploadcourse
33  * @copyright  2013 Frédéric Massart
34  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
35  */
36 class tool_uploadcourse_course_testcase extends advanced_testcase {
38     public function test_proceed_without_prepare() {
39         $this->resetAfterTest(true);
40         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
41         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
42         $data = array();
43         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
44         $this->expectException(coding_exception::class);
45         $co->proceed();
46     }
48     public function test_proceed_when_prepare_failed() {
49         $this->resetAfterTest(true);
50         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
51         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
52         $data = array();
53         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
54         $this->assertFalse($co->prepare());
55         $this->expectException(moodle_exception::class);
56         $co->proceed();
57     }
59     public function test_proceed_when_already_started() {
60         $this->resetAfterTest(true);
61         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
62         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
63         $data = array('shortname' => 'test', 'fullname' => 'New course', 'summary' => 'New', 'category' => 1);
64         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
65         $this->assertTrue($co->prepare());
66         $co->proceed();
67         $this->expectException('coding_exception');
68         $co->proceed();
69     }
71     public function test_invalid_shortname() {
72         $this->resetAfterTest(true);
73         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
74         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
75         $data = array('shortname' => '<invalid>', 'fullname' => 'New course', 'summary' => 'New', 'category' => 1);
76         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
77         $this->assertFalse($co->prepare());
78         $this->assertArrayHasKey('invalidshortname', $co->get_errors());
79     }
81     public function test_invalid_shortname_too_long() {
82         $this->resetAfterTest();
84         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
85         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
87         $upload = new tool_uploadcourse_course($mode, $updatemode, [
88             'category' => 1,
89             'fullname' => 'New course',
90             'shortname' => str_repeat('X', 2000),
91         ]);
93         $this->assertFalse($upload->prepare());
94         $this->assertArrayHasKey('invalidshortnametoolong', $upload->get_errors());
95     }
97     public function test_invalid_fullname_too_long() {
98         $this->resetAfterTest();
100         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
101         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
103         $upload = new tool_uploadcourse_course($mode, $updatemode, [
104             'category' => 1,
105             'fullname' => str_repeat('X', 2000),
106         ]);
108         $this->assertFalse($upload->prepare());
109         $this->assertArrayHasKey('invalidfullnametoolong', $upload->get_errors());
110     }
112     public function test_invalid_visibility() {
113         $this->resetAfterTest(true);
114         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
115         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
116         $data = array('shortname' => 'test', 'fullname' => 'New course', 'summary' => 'New', 'category' => 1, 'visible' => 2);
117         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
118         $this->assertFalse($co->prepare());
119         $this->assertArrayHasKey('invalidvisibilitymode', $co->get_errors());
120     }
122     /**
123      * Test setting 'downloadcontent' field when the feature is globally disabled
124      */
125     public function test_downloadcontent_disabled(): void {
126         $this->resetAfterTest();
127         $this->setAdminUser();
129         set_config('downloadcoursecontentallowed', 0);
131         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
132         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
134         $upload = new tool_uploadcourse_course($mode, $updatemode, [
135             'category' => 1,
136             'fullname' => 'Testing',
137             'shortname' => 'T101',
138             'downloadcontent' => DOWNLOAD_COURSE_CONTENT_ENABLED,
139         ]);
141         $this->assertFalse($upload->prepare());
142         $this->assertArrayHasKey('downloadcontentnotallowed', $upload->get_errors());
143     }
145     /**
146      * Test setting 'downloadcontent' field when user doesn't have required capability
147      */
148     public function test_downloadcontent_capability(): void {
149         global $DB;
151         $this->resetAfterTest();
153         set_config('downloadcoursecontentallowed', 1);
155         // Create category in which to create the new course.
156         $category = $this->getDataGenerator()->create_category();
157         $categorycontext = context_coursecat::instance($category->id);
159         $user = $this->getDataGenerator()->create_user();
160         $this->setUser($user);
162         // Assign the user as a manager of the category, disable ability to configure course content download.
163         $roleid = $DB->get_field('role', 'id', ['shortname' => 'manager']);
164         role_assign($roleid, $user->id, $categorycontext);
165         role_change_permission($roleid, $categorycontext, 'moodle/course:configuredownloadcontent', CAP_PROHIBIT);
167         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
168         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
170         $upload = new tool_uploadcourse_course($mode, $updatemode, [
171             'category' => $category->id,
172             'fullname' => 'Testing',
173             'shortname' => 'T101',
174             'downloadcontent' => DOWNLOAD_COURSE_CONTENT_ENABLED,
175         ]);
177         $this->assertFalse($upload->prepare());
178         $this->assertArrayHasKey('downloadcontentnotallowed', $upload->get_errors());
179     }
181     /**
182      * Test setting 'downloadcontent' field to an invalid value
183      */
184     public function test_downloadcontent_invalid(): void {
185         $this->resetAfterTest();
186         $this->setAdminUser();
188         set_config('downloadcoursecontentallowed', 1);
190         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
191         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
193         $upload = new tool_uploadcourse_course($mode, $updatemode, [
194             'category' => 1,
195             'fullname' => 'Testing',
196             'shortname' => 'T101',
197             'downloadcontent' => 42,
198         ]);
200         $this->assertFalse($upload->prepare());
201         $this->assertArrayHasKey('invaliddownloadcontent', $upload->get_errors());
202     }
204     public function test_create() {
205         global $DB;
206         $this->resetAfterTest(true);
208         // Existing course.
209         $c1 = $this->getDataGenerator()->create_course(array('shortname' => 'c1', 'summary' => 'Yay!'));
210         $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1')));
212         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
214         // Try to add a new course.
215         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
216         $data = array('shortname' => 'newcourse', 'fullname' => 'New course', 'summary' => 'New', 'category' => 1);
217         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
218         $this->assertTrue($co->prepare());
219         $this->assertFalse($DB->record_exists('course', array('shortname' => 'newcourse')));
220         $co->proceed();
221         $course = $DB->get_record('course', array('shortname' => 'newcourse'), '*', MUST_EXIST);
222         $this->assertEquals(0, course_get_format($course)->get_course()->coursedisplay);
224         // Try to add a new course, that already exists.
225         $coursecount = $DB->count_records('course', array());
226         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
227         $data = array('shortname' => 'c1', 'fullname' => 'C1FN', 'summary' => 'C1', 'category' => 1);
228         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
229         $this->assertFalse($co->prepare());
230         $this->assertArrayHasKey('courseexistsanduploadnotallowed', $co->get_errors());
231         $this->assertEquals($coursecount, $DB->count_records('course', array()));
232         $this->assertNotEquals('C1', $DB->get_field_select('course', 'summary', 'shortname = :s', array('s' => 'c1')));
234         // Try to add new with shortname incrementation.
235         $mode = tool_uploadcourse_processor::MODE_CREATE_ALL;
236         $data = array('shortname' => 'c1', 'fullname' => 'C1FN', 'summary' => 'C1', 'category' => 1);
237         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
238         $this->assertTrue($co->prepare());
239         $co->proceed();
240         $this->assertTrue($DB->record_exists('course', array('shortname' => 'c2')));
242         // Add a new course with non-default course format option.
243         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
244         $data = array('shortname' => 'c3', 'fullname' => 'C3', 'summary' => 'New c3', 'category' => 1,
245             'format' => 'weeks', 'coursedisplay' => 1);
246         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
247         $this->assertTrue($co->prepare());
248         $co->proceed();
249         $course = $DB->get_record('course', array('shortname' => 'c3'), '*', MUST_EXIST);
250         $this->assertEquals(1, course_get_format($course)->get_course()->coursedisplay);
251     }
253     public function test_create_with_sections() {
254         global $DB;
255         $this->resetAfterTest(true);
256         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
257         $defaultnumsections = get_config('moodlecourse', 'numsections');
259         // Add new course, make sure default number of sections is created.
260         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
261         $data = array('shortname' => 'newcourse1', 'fullname' => 'New course1', 'format' => 'topics', 'category' => 1);
262         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
263         $this->assertTrue($co->prepare());
264         $co->proceed();
265         $courseid = $DB->get_field('course', 'id', array('shortname' => 'newcourse1'));
266         $this->assertNotEmpty($courseid);
267         $this->assertEquals($defaultnumsections + 1,
268             $DB->count_records('course_sections', ['course' => $courseid]));
270         // Add new course specifying number of sections.
271         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
272         $data = array('shortname' => 'newcourse2', 'fullname' => 'New course2', 'format' => 'topics', 'category' => 1,
273             'numsections' => 15);
274         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
275         $this->assertTrue($co->prepare());
276         $co->proceed();
277         $courseid = $DB->get_field('course', 'id', array('shortname' => 'newcourse2'));
278         $this->assertNotEmpty($courseid);
279         $this->assertEquals(15 + 1,
280             $DB->count_records('course_sections', ['course' => $courseid]));
281     }
283     public function test_delete() {
284         global $DB;
285         $this->resetAfterTest(true);
287         $c1 = $this->getDataGenerator()->create_course();
288         $c2 = $this->getDataGenerator()->create_course();
290         $this->assertTrue($DB->record_exists('course', array('shortname' => $c1->shortname)));
291         $this->assertFalse($DB->record_exists('course', array('shortname' => 'DoesNotExist')));
293         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
294         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
296         // Try delete when option not available.
297         $importoptions = array('candelete' => false);
298         $data = array('shortname' => $c1->shortname, 'delete' => 1);
299         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
300         $this->assertFalse($co->prepare());
301         $this->assertArrayHasKey('coursedeletionnotallowed', $co->get_errors());
302         $this->assertTrue($DB->record_exists('course', array('shortname' => $c1->shortname)));
304         // Try delete when not requested.
305         $importoptions = array('candelete' => true);
306         $data = array('shortname' => $c1->shortname, 'delete' => 0);
307         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
308         $this->assertTrue($co->prepare());
309         $co->proceed();
310         $this->assertTrue($DB->record_exists('course', array('shortname' => $c1->shortname)));
312         // Try delete when requested.
313         $importoptions = array('candelete' => true);
314         $data = array('shortname' => $c1->shortname, 'delete' => 1);
315         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
316         $this->assertTrue($co->prepare());
317         $co->proceed();
318         $this->assertFalse($DB->record_exists('course', array('shortname' => $c1->shortname)));
319         $this->assertTrue($DB->record_exists('course', array('shortname' => $c2->shortname)));
321         // Try deleting non-existing record, this should not fail.
322         $data = array('shortname' => 'DoesNotExist', 'delete' => 1);
323         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
324         $this->assertFalse($co->prepare());
325         $this->assertArrayHasKey('cannotdeletecoursenotexist', $co->get_errors());
326     }
328     public function test_update() {
329         global $DB;
330         $this->resetAfterTest(true);
332         $c1 = $this->getDataGenerator()->create_course(array('shortname' => 'c1'));
334         // Try to update with existing shortnames, not allowing creation, and updating nothing.
335         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
336         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
337         $data = array('shortname' => 'c1', 'fullname' => 'New fullname');
338         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
339         $this->assertFalse($co->prepare());
340         $this->assertArrayHasKey('updatemodedoessettonothing', $co->get_errors());
342         // Try to update with non-existing shortnames.
343         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
344         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
345         $data = array('shortname' => 'DoesNotExist', 'fullname' => 'New fullname');
346         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
347         $this->assertFalse($co->prepare());
348         $this->assertArrayHasKey('coursedoesnotexistandcreatenotallowed', $co->get_errors());
350         // Try a proper update.
351         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
352         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
353         $data = array('shortname' => 'c1', 'fullname' => 'New fullname');
354         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
355         $this->assertTrue($co->prepare());
356         $co->proceed();
357         $this->assertEquals('New fullname', $DB->get_field_select('course', 'fullname', 'shortname = :s', array('s' => 'c1')));
359         // Try a proper update with defaults.
360         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
361         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_OR_DEFAUTLS;
362         $data = array('shortname' => 'c1', 'fullname' => 'Another fullname');
363         $defaults = array('fullname' => 'Not this one', 'summary' => 'Awesome summary');
364         $co = new tool_uploadcourse_course($mode, $updatemode, $data, $defaults);
365         $this->assertTrue($co->prepare());
366         $co->proceed();
367         $this->assertEquals('Another fullname', $DB->get_field_select('course', 'fullname', 'shortname = :s', array('s' => 'c1')));
368         $this->assertEquals('Awesome summary', $DB->get_field_select('course', 'summary', 'shortname = :s', array('s' => 'c1')));
370         // Try a proper update missing only.
371         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
372         $updatemode = tool_uploadcourse_processor::UPDATE_MISSING_WITH_DATA_OR_DEFAUTLS;
373         $DB->set_field('course', 'summary', '', array('shortname' => 'c1'));
374         $this->assertEquals('', $DB->get_field_select('course', 'summary', 'shortname = :s', array('s' => 'c1')));
375         $data = array('shortname' => 'c1', 'summary' => 'Fill in summary');
376         $defaults = array('summary' => 'Do not use this summary');
377         $co = new tool_uploadcourse_course($mode, $updatemode, $data, $defaults);
378         $this->assertTrue($co->prepare());
379         $co->proceed();
380         $this->assertEquals('Fill in summary', $DB->get_field_select('course', 'summary', 'shortname = :s', array('s' => 'c1')));
382         // Try a proper update missing only using defaults.
383         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
384         $updatemode = tool_uploadcourse_processor::UPDATE_MISSING_WITH_DATA_OR_DEFAUTLS;
385         $DB->set_field('course', 'summary', '', array('shortname' => 'c1'));
386         $this->assertEquals('', $DB->get_field_select('course', 'summary', 'shortname = :s', array('s' => 'c1')));
387         $data = array('shortname' => 'c1');
388         $defaults = array('summary' => 'Use this summary');
389         $co = new tool_uploadcourse_course($mode, $updatemode, $data, $defaults);
390         $this->assertTrue($co->prepare());
391         $co->proceed();
392         $this->assertEquals('Use this summary', $DB->get_field_select('course', 'summary', 'shortname = :s', array('s' => 'c1')));
394         // Update course format option.
395         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
396         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
397         $data = array('shortname' => 'c1', 'coursedisplay' => 1);
398         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
399         $this->assertTrue($co->prepare());
400         $co->proceed();
401         $course = $DB->get_record('course', array('shortname' => 'c1'), '*', MUST_EXIST);
402         $this->assertEquals(1, course_get_format($course)->get_course()->coursedisplay);
403     }
405     public function test_data_saved() {
406         global $DB;
408         $this->resetAfterTest(true);
409         $this->setAdminUser(); // To avoid warnings related to 'moodle/course:setforcedlanguage' capability check.
411         set_config('downloadcoursecontentallowed', 1);
413         // Create.
414         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
415         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
416         $data = array(
417             'shortname' => 'c1',
418             'fullname' => 'Fullname',
419             'category' => '1',
420             'visible' => '0',
421             'downloadcontent' => DOWNLOAD_COURSE_CONTENT_DISABLED,
422             'idnumber' => '123abc',
423             'summary' => 'Summary',
424             'format' => 'topics',
425             'theme' => 'afterburner',
426             'lang' => 'en',
427             'newsitems' => '7',
428             'showgrades' => '0',
429             'showreports' => '1',
430             'legacyfiles' => '1',
431             'maxbytes' => '1234',
432             'groupmode' => '2',
433             'groupmodeforce' => '1',
434             'enablecompletion' => '1',
435             'tags' => 'Cat, Dog',
437             'role_teacher' => 'Knight',
438             'role_manager' => 'Jedi',
440             'enrolment_1' => 'guest',
441             'enrolment_2' => 'self',
442             'enrolment_2_roleid' => '1',
443             'enrolment_3' => 'manual',
444             'enrolment_3_disable' => '1',
445         );
447         // There should be a start date if there is a end date.
448         $data['enddate'] = '7 June 1990';
449         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
450         $this->assertFalse($co->prepare());
451         $this->assertArrayHasKey('nostartdatenoenddate', $co->get_errors());
453         $data['startdate'] = '8 June 1990';
454         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
455         $this->assertFalse($co->prepare());
456         $this->assertArrayHasKey('enddatebeforestartdate', $co->get_errors());
458         // They are correct now.
459         $data['enddate'] = '18 June 1990';
461         $this->assertFalse($DB->record_exists('course', array('shortname' => 'c1')));
462         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
463         $this->assertTrue($co->prepare());
464         $co->proceed();
465         $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1')));
466         $course = $DB->get_record('course', array('shortname' => 'c1'));
467         $ctx = context_course::instance($course->id);
469         $this->assertEquals($data['fullname'], $course->fullname);
470         $this->assertEquals($data['category'], $course->category);
471         $this->assertEquals($data['visible'], $course->visible);
472         $this->assertEquals($data['downloadcontent'], $course->downloadcontent);
473         $this->assertEquals(mktime(0, 0, 0, 6, 8, 1990), $course->startdate);
474         $this->assertEquals(mktime(0, 0, 0, 6, 18, 1990), $course->enddate);
475         $this->assertEquals($data['idnumber'], $course->idnumber);
476         $this->assertEquals($data['summary'], $course->summary);
477         $this->assertEquals($data['format'], $course->format);
478         $this->assertEquals($data['theme'], $course->theme);
479         $this->assertEquals($data['lang'], $course->lang);
480         $this->assertEquals($data['newsitems'], $course->newsitems);
481         $this->assertEquals($data['showgrades'], $course->showgrades);
482         $this->assertEquals($data['showreports'], $course->showreports);
483         $this->assertEquals($data['legacyfiles'], $course->legacyfiles);
484         $this->assertEquals($data['maxbytes'], $course->maxbytes);
485         $this->assertEquals($data['groupmode'], $course->groupmode);
486         $this->assertEquals($data['groupmodeforce'], $course->groupmodeforce);
487         $this->assertEquals($data['enablecompletion'], $course->enablecompletion);
488         $this->assertEquals($data['tags'], join(', ', core_tag_tag::get_item_tags_array('core', 'course', $course->id)));
490         // Roles.
491         $roleids = array();
492         $roles = get_all_roles();
493         foreach ($roles as $role) {
494             $roleids[$role->shortname] = $role->id;
495         }
496         $this->assertEquals('Knight', $DB->get_field_select('role_names', 'name',
497             'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['teacher'])));
498         $this->assertEquals('Jedi', $DB->get_field_select('role_names', 'name',
499             'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['manager'])));
501         // Enrolment methods.
502         $enroldata = array();
503         $instances = enrol_get_instances($course->id, false);
504         $this->assertCount(3, $instances);
505         foreach ($instances as $instance) {
506             $enroldata[$instance->enrol] = $instance;
507         }
509         $this->assertNotEmpty($enroldata['guest']);
510         $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['guest']->status);
511         $this->assertNotEmpty($enroldata['self']);
512         $this->assertEquals($data['enrolment_2_roleid'], $enroldata['self']->roleid);
513         $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['self']->status);
514         $this->assertNotEmpty($enroldata['manual']);
515         $this->assertEquals(ENROL_INSTANCE_DISABLED, $enroldata['manual']->status);
517         // Update existing course.
518         $cat = $this->getDataGenerator()->create_category();
519         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
520         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
521         $data = array(
522             'shortname' => 'c1',
523             'fullname' => 'Fullname 2',
524             'category' => $cat->id,
525             'visible' => '1',
526             'downloadcontent' => DOWNLOAD_COURSE_CONTENT_ENABLED,
527             'idnumber' => 'changeidn',
528             'summary' => 'Summary 2',
529             'format' => 'topics',
530             'theme' => 'classic',
531             'lang' => '',
532             'newsitems' => '2',
533             'showgrades' => '1',
534             'showreports' => '0',
535             'legacyfiles' => '0',
536             'maxbytes' => '4321',
537             'groupmode' => '1',
538             'groupmodeforce' => '0',
539             'enablecompletion' => '0',
541             'role_teacher' => 'Teacher',
542             'role_manager' => 'Manager',
544             'enrolment_1' => 'guest',
545             'enrolment_1_disable' => '1',
546             'enrolment_2' => 'self',
547             'enrolment_2_roleid' => '2',
548             'enrolment_3' => 'manual',
549             'enrolment_3_delete' => '1',
550         );
552         $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1')));
554         $data['enddate'] = '31 June 1984';
555         // Previous start and end dates are 8 and 18 June 1990.
556         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
557         $this->assertFalse($co->prepare());
558         $this->assertArrayHasKey('enddatebeforestartdate', $co->get_errors());
560         $data['startdate'] = '19 June 1990';
561         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
562         $this->assertFalse($co->prepare());
563         $this->assertArrayHasKey('enddatebeforestartdate', $co->get_errors());
565         // They are correct now.
566         $data['startdate'] = '11 June 1984';
568         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
569         $this->assertTrue($co->prepare());
570         $co->proceed();
571         $course = $DB->get_record('course', array('shortname' => 'c1'));
572         $ctx = context_course::instance($course->id);
574         $this->assertEquals($data['fullname'], $course->fullname);
575         $this->assertEquals($data['category'], $course->category);
576         $this->assertEquals($data['visible'], $course->visible);
577         $this->assertEquals($data['downloadcontent'], $course->downloadcontent);
578         $this->assertEquals(mktime(0, 0, 0, 6, 11, 1984), $course->startdate);
579         $this->assertEquals(mktime(0, 0, 0, 6, 31, 1984), $course->enddate);
580         $this->assertEquals($data['idnumber'], $course->idnumber);
581         $this->assertEquals($data['summary'], $course->summary);
582         $this->assertEquals($data['format'], $course->format);
583         $this->assertEquals($data['theme'], $course->theme);
584         $this->assertEquals($data['lang'], $course->lang);
585         $this->assertEquals($data['newsitems'], $course->newsitems);
586         $this->assertEquals($data['showgrades'], $course->showgrades);
587         $this->assertEquals($data['showreports'], $course->showreports);
588         $this->assertEquals($data['legacyfiles'], $course->legacyfiles);
589         $this->assertEquals($data['maxbytes'], $course->maxbytes);
590         $this->assertEquals($data['groupmode'], $course->groupmode);
591         $this->assertEquals($data['groupmodeforce'], $course->groupmodeforce);
592         $this->assertEquals($data['enablecompletion'], $course->enablecompletion);
594         // Roles.
595         $roleids = array();
596         $roles = get_all_roles();
597         foreach ($roles as $role) {
598             $roleids[$role->shortname] = $role->id;
599         }
600         $this->assertEquals('Teacher', $DB->get_field_select('role_names', 'name',
601             'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['teacher'])));
602         $this->assertEquals('Manager', $DB->get_field_select('role_names', 'name',
603             'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['manager'])));
605         // Enrolment methods.
606         $enroldata = array();
607         $instances = enrol_get_instances($course->id, false);
608         $this->assertCount(2, $instances);
609         foreach ($instances as $instance) {
610             $enroldata[$instance->enrol] = $instance;
611         }
613         $this->assertNotEmpty($enroldata['guest']);
614         $this->assertEquals(ENROL_INSTANCE_DISABLED, $enroldata['guest']->status);
615         $this->assertNotEmpty($enroldata['self']);
616         $this->assertEquals($data['enrolment_2_roleid'], $enroldata['self']->roleid);
617         $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['self']->status);
618     }
620     public function test_default_data_saved() {
621         global $DB;
623         $this->resetAfterTest(true);
624         $this->setAdminUser();
626         set_config('downloadcoursecontentallowed', 1);
628         // Create.
629         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
630         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
631         $data = array(
632             'shortname' => 'c1',
633         );
634         $defaultdata = array(
635             'fullname' => 'Fullname',
636             'category' => '1',
637             'visible' => '0',
638             'downloadcontent' => DOWNLOAD_COURSE_CONTENT_DISABLED,
639             'startdate' => 644803200,
640             'enddate' => 645667200,
641             'idnumber' => '123abc',
642             'summary' => 'Summary',
643             'format' => 'topics',
644             'theme' => 'afterburner',
645             'lang' => 'en',
646             'newsitems' => '7',
647             'showgrades' => '0',
648             'showreports' => '1',
649             'legacyfiles' => '1',
650             'maxbytes' => '1234',
651             'groupmode' => '2',
652             'groupmodeforce' => '1',
653             'enablecompletion' => '1',
654         );
656         $this->assertFalse($DB->record_exists('course', array('shortname' => 'c1')));
657         $co = new tool_uploadcourse_course($mode, $updatemode, $data, $defaultdata);
658         $this->assertTrue($co->prepare());
659         $co->proceed();
660         $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1')));
661         $course = $DB->get_record('course', array('shortname' => 'c1'));
662         $ctx = context_course::instance($course->id);
664         $this->assertEquals($defaultdata['fullname'], $course->fullname);
665         $this->assertEquals($defaultdata['category'], $course->category);
666         $this->assertEquals($defaultdata['visible'], $course->visible);
667         $this->assertEquals($defaultdata['downloadcontent'], $course->downloadcontent);
668         $this->assertEquals($defaultdata['startdate'], $course->startdate);
669         $this->assertEquals($defaultdata['enddate'], $course->enddate);
670         $this->assertEquals($defaultdata['idnumber'], $course->idnumber);
671         $this->assertEquals($defaultdata['summary'], $course->summary);
672         $this->assertEquals($defaultdata['format'], $course->format);
673         $this->assertEquals($defaultdata['theme'], $course->theme);
674         $this->assertEquals($defaultdata['lang'], $course->lang);
675         $this->assertEquals($defaultdata['newsitems'], $course->newsitems);
676         $this->assertEquals($defaultdata['showgrades'], $course->showgrades);
677         $this->assertEquals($defaultdata['showreports'], $course->showreports);
678         $this->assertEquals($defaultdata['legacyfiles'], $course->legacyfiles);
679         $this->assertEquals($defaultdata['maxbytes'], $course->maxbytes);
680         $this->assertEquals($defaultdata['groupmode'], $course->groupmode);
681         $this->assertEquals($defaultdata['groupmodeforce'], $course->groupmodeforce);
682         $this->assertEquals($defaultdata['enablecompletion'], $course->enablecompletion);
684         // Update.
685         $cat = $this->getDataGenerator()->create_category();
686         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
687         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_OR_DEFAUTLS;
688         $data = array(
689             'shortname' => 'c1',
690         );
691         $defaultdata = array(
692             'fullname' => 'Fullname 2',
693             'category' => $cat->id,
694             'visible' => '1',
695             'downloadcontent' => DOWNLOAD_COURSE_CONTENT_ENABLED,
696             'startdate' => 455760000,
697             'enddate' => 457488000,
698             'idnumber' => 'changedid',
699             'summary' => 'Summary 2',
700             'format' => 'topics',
701             'theme' => 'classic',
702             'lang' => '',
703             'newsitems' => '2',
704             'showgrades' => '1',
705             'showreports' => '0',
706             'legacyfiles' => '0',
707             'maxbytes' => '1111',
708             'groupmode' => '1',
709             'groupmodeforce' => '0',
710             'enablecompletion' => '0',
711         );
713         $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1')));
714         $co = new tool_uploadcourse_course($mode, $updatemode, $data, $defaultdata);
715         $this->assertTrue($co->prepare());
716         $co->proceed();
717         $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1')));
718         $course = $DB->get_record('course', array('shortname' => 'c1'));
719         $ctx = context_course::instance($course->id);
721         $this->assertEquals($defaultdata['fullname'], $course->fullname);
722         $this->assertEquals($defaultdata['category'], $course->category);
723         $this->assertEquals($defaultdata['visible'], $course->visible);
724         $this->assertEquals($defaultdata['downloadcontent'], $course->downloadcontent);
725         $this->assertEquals($defaultdata['startdate'], $course->startdate);
726         $this->assertEquals($defaultdata['enddate'], $course->enddate);
727         $this->assertEquals($defaultdata['idnumber'], $course->idnumber);
728         $this->assertEquals($defaultdata['summary'], $course->summary);
729         $this->assertEquals($defaultdata['format'], $course->format);
730         $this->assertEquals($defaultdata['theme'], $course->theme);
731         $this->assertEquals($defaultdata['lang'], $course->lang);
732         $this->assertEquals($defaultdata['newsitems'], $course->newsitems);
733         $this->assertEquals($defaultdata['showgrades'], $course->showgrades);
734         $this->assertEquals($defaultdata['showreports'], $course->showreports);
735         $this->assertEquals($defaultdata['legacyfiles'], $course->legacyfiles);
736         $this->assertEquals($defaultdata['maxbytes'], $course->maxbytes);
737         $this->assertEquals($defaultdata['groupmode'], $course->groupmode);
738         $this->assertEquals($defaultdata['groupmodeforce'], $course->groupmodeforce);
739         $this->assertEquals($defaultdata['enablecompletion'], $course->enablecompletion);
740     }
742     public function test_rename() {
743         global $DB;
744         $this->resetAfterTest(true);
746         $c1 = $this->getDataGenerator()->create_course(array('shortname' => 'c1'));
747         $c2 = $this->getDataGenerator()->create_course(array('shortname' => 'c2'));
749         // Cannot rename when creating.
750         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
751         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
752         $importoptions = array('canrename' => true);
753         $data = array('shortname' => 'c1', 'rename' => 'newshortname');
754         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
755         $this->assertFalse($co->prepare());
756         $this->assertArrayHasKey('courseexistsanduploadnotallowed', $co->get_errors());
758         // Cannot rename when creating.
759         $mode = tool_uploadcourse_processor::MODE_CREATE_ALL;
760         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
761         $importoptions = array('canrename' => true);
762         $data = array('shortname' => 'c1', 'rename' => 'newshortname', 'category' => 1, 'summary' => 'S', 'fullname' => 'F');
763         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
764         $this->assertFalse($co->prepare());
765         $this->assertArrayHasKey('canonlyrenameinupdatemode', $co->get_errors());
767         // Error when not allowed to rename the course.
768         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
769         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
770         $importoptions = array('canrename' => false);
771         $data = array('shortname' => 'c1', 'rename' => 'newshortname');
772         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
773         $this->assertFalse($co->prepare());
774         $this->assertArrayHasKey('courserenamingnotallowed', $co->get_errors());
776         // Can rename when updating.
777         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
778         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
779         $importoptions = array('canrename' => true);
780         $data = array('shortname' => 'c1', 'rename' => 'newshortname');
781         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
782         $this->assertTrue($co->prepare());
783         $co->proceed();
784         $this->assertEquals('newshortname', $DB->get_field_select('course', 'shortname', 'id = :id', array('id' => $c1->id)));
786         // Can rename when updating.
787         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
788         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
789         $importoptions = array('canrename' => true);
790         $data = array('shortname' => 'newshortname', 'rename' => 'newshortname2');
791         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
792         $this->assertTrue($co->prepare());
793         $co->proceed();
794         $this->assertEquals('newshortname2', $DB->get_field_select('course', 'shortname', 'id = :id', array('id' => $c1->id)));
796         // Error when course does not exist.
797         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
798         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
799         $importoptions = array('canrename' => true);
800         $data = array('shortname' => 'DoesNotExist', 'rename' => 'c1', 'category' => 1, 'summary' => 'S', 'fullname' => 'F');
801         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
802         $this->assertFalse($co->prepare());
803         $this->assertArrayHasKey('cannotrenamecoursenotexist', $co->get_errors());
805         // Renaming still updates the other values.
806         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
807         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_OR_DEFAUTLS;
808         $importoptions = array('canrename' => true);
809         $data = array('shortname' => 'newshortname2', 'rename' => 'c1', 'fullname' => 'Another fullname!');
810         $defaultdata = array('summary' => 'New summary!');
811         $co = new tool_uploadcourse_course($mode, $updatemode, $data, $defaultdata, $importoptions);
812         $this->assertTrue($co->prepare());
813         $co->proceed();
814         $this->assertEquals('c1', $DB->get_field_select('course', 'shortname', 'id = :id', array('id' => $c1->id)));
815         $this->assertEquals('New summary!', $DB->get_field_select('course', 'summary', 'id = :id', array('id' => $c1->id)));
816         $this->assertEquals('Another fullname!', $DB->get_field_select('course', 'fullname', 'id = :id', array('id' => $c1->id)));
818         // Renaming with invalid shortname.
819         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
820         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
821         $importoptions = array('canrename' => true);
822         $data = array('shortname' => 'c1', 'rename' => '<span>invalid</span>');
823         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
824         $this->assertFalse($co->prepare());
825         $this->assertArrayHasKey('invalidshortname', $co->get_errors());
827         // Renaming with invalid shortname.
828         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
829         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
830         $importoptions = array('canrename' => true);
831         $data = array('shortname' => 'c1', 'rename' => 'c2');
832         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
833         $this->assertFalse($co->prepare());
834         $this->assertArrayHasKey('cannotrenameshortnamealreadyinuse', $co->get_errors());
835     }
837     public function test_restore_course() {
838         global $DB;
839         $this->resetAfterTest(true);
840         $this->setAdminUser();
842         $c1 = $this->getDataGenerator()->create_course();
843         $c1f1 = $this->getDataGenerator()->create_module('forum', array('course' => $c1->id));
845         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
846         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
847         $data = array('shortname' => 'A1', 'templatecourse' => $c1->shortname, 'summary' => 'A', 'category' => 1,
848             'fullname' => 'A1');
849         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
850         $this->assertTrue($co->prepare());
851         $co->proceed();
852         $course = $DB->get_record('course', array('shortname' => 'A1'));
853         $modinfo = get_fast_modinfo($course);
854         $found = false;
855         foreach ($modinfo->get_cms() as $cmid => $cm) {
856             if ($cm->modname == 'forum' && $cm->name == $c1f1->name) {
857                 $found = true;
858                 break;
859             }
860         }
861         $this->assertTrue($found);
863         // Restoring twice from the same course should work.
864         $data = array('shortname' => 'B1', 'templatecourse' => $c1->shortname, 'summary' => 'B', 'category' => 1,
865             'fullname' => 'B1');
866         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
867         $this->assertTrue($co->prepare());
868         $co->proceed();
869         $course = $DB->get_record('course', array('shortname' => 'B1'));
870         $modinfo = get_fast_modinfo($course);
871         $found = false;
872         foreach ($modinfo->get_cms() as $cmid => $cm) {
873             if ($cm->modname == 'forum' && $cm->name == $c1f1->name) {
874                 $found = true;
875                 break;
876             }
877         }
878         $this->assertTrue($found);
879     }
881     public function test_restore_file() {
882         global $DB;
883         $this->resetAfterTest(true);
884         $this->setAdminUser();
886         $c1 = $this->getDataGenerator()->create_course();
887         $c1f1 = $this->getDataGenerator()->create_module('forum', array('course' => $c1->id));
889         // Restore from a file, checking that the file takes priority over the templatecourse.
890         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
891         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
892         $data = array('shortname' => 'A1', 'backupfile' => __DIR__ . '/fixtures/backup.mbz',
893             'summary' => 'A', 'category' => 1, 'fullname' => 'A1', 'templatecourse' => $c1->shortname);
894         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
895         $this->assertTrue($co->prepare());
896         $co->proceed();
897         $course = $DB->get_record('course', array('shortname' => 'A1'));
898         $modinfo = get_fast_modinfo($course);
899         $found = false;
900         foreach ($modinfo->get_cms() as $cmid => $cm) {
901             if ($cm->modname == 'glossary' && $cm->name == 'Imported Glossary') {
902                 $found = true;
903             } else if ($cm->modname == 'forum' && $cm->name == $c1f1->name) {
904                 // We should not find this!
905                 $this->assertTrue(false);
906             }
907         }
908         $this->assertTrue($found);
910         // Restoring twice from the same file should work.
911         $data = array('shortname' => 'B1', 'backupfile' => __DIR__ . '/fixtures/backup.mbz',
912             'summary' => 'B', 'category' => 1, 'fullname' => 'B1');
913         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
914         $this->assertTrue($co->prepare());
915         $co->proceed();
916         $course = $DB->get_record('course', array('shortname' => 'B1'));
917         $modinfo = get_fast_modinfo($course);
918         $found = false;
919         foreach ($modinfo->get_cms() as $cmid => $cm) {
920             if ($cm->modname == 'glossary' && $cm->name == 'Imported Glossary') {
921                 $found = true;
922             } else if ($cm->modname == 'forum' && $cm->name == $c1f1->name) {
923                 // We should not find this!
924                 $this->assertTrue(false);
925             }
926         }
927         $this->assertTrue($found);
928     }
930     /**
931      * Test that specifying course template respects default restore settings
932      */
933     public function test_restore_file_settings() {
934         global $DB;
935         $this->resetAfterTest(true);
936         $this->setAdminUser();
938         // Set admin config setting so that activities are not restored by default.
939         set_config('restore_general_activities', 0, 'restore');
941         $c1 = $this->getDataGenerator()->create_course();
943         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
944         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
945         $data = array('shortname' => 'A1', 'backupfile' => __DIR__ . '/fixtures/backup.mbz',
946             'summary' => 'A', 'category' => 1, 'fullname' => 'A1', 'templatecourse' => $c1->shortname);
947         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
948         $this->assertTrue($co->prepare());
949         $co->proceed();
950         $course = $DB->get_record('course', array('shortname' => 'A1'));
952         // Make sure the glossary is not restored.
953         $modinfo = get_fast_modinfo($course);
954         $this->assertEmpty($modinfo->get_instances_of('glossary'));
955     }
957     public function test_restore_invalid_file() {
958         $this->resetAfterTest();
960         // Restore from a non-existing file should not be allowed.
961         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
962         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
963         $data = array('shortname' => 'A1', 'backupfile' => '/lead/no/where',
964             'category' => 1, 'fullname' => 'A1');
965         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
966         $this->assertFalse($co->prepare());
967         $this->assertArrayHasKey('cannotreadbackupfile', $co->get_errors());
969         // Restore from an invalid file should not be allowed.
970         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
971         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
972         $data = array('shortname' => 'A1', 'backupfile' => __FILE__,
973             'category' => 1, 'fullname' => 'A1');
974         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
976         $this->assertFalse($co->prepare());
977         $this->assertArrayHasKey('invalidbackupfile', $co->get_errors());
979         // Zip packer throws a debugging message, this assertion is only here to prevent
980         // the message from being displayed.
981         $this->assertDebuggingCalled();
982     }
984     public function test_restore_invalid_course() {
985         $this->resetAfterTest();
987         // Restore from an invalid file should not be allowed.
988         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
989         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
990         $data = array('shortname' => 'A1', 'templatecourse' => 'iamnotavalidcourse',
991             'category' => 1, 'fullname' => 'A1');
992         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
993         $this->assertFalse($co->prepare());
994         $this->assertArrayHasKey('coursetorestorefromdoesnotexist', $co->get_errors());
995     }
997     /**
998      * Testing the reset on groups, group members and enrolments.
999      */
1000     public function test_reset() {
1001         global $DB;
1002         $this->resetAfterTest(true);
1004         $c1 = $this->getDataGenerator()->create_course();
1005         $c1ctx = context_course::instance($c1->id);
1006         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1007         $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
1009         $u1 = $this->getDataGenerator()->create_user();
1010         $this->getDataGenerator()->enrol_user($u1->id, $c1->id, $studentrole->id);
1011         $this->assertCount(1, get_enrolled_users($c1ctx));
1013         $g1 = $this->getDataGenerator()->create_group(array('courseid' => $c1->id));
1014         $this->getDataGenerator()->create_group_member(array('groupid' => $g1->id, 'userid' => $u1->id));
1015         $this->assertEquals(1, $DB->count_records('groups', array('courseid' => $c1->id)));
1016         $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $g1->id, 'userid' => $u1->id)));
1018         // Wrong mode.
1019         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1020         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1021         $data = array('shortname' => 'DoesNotExist', 'reset' => '1', 'summary' => 'summary', 'fullname' => 'FN', 'category' => 1);
1022         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
1023         $this->assertFalse($co->prepare());
1024         $this->assertArrayHasKey('canonlyresetcourseinupdatemode', $co->get_errors());
1025         $this->assertTrue($DB->record_exists('groups', array('id' => $g1->id)));
1026         $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $g1->id, 'userid' => $u1->id)));
1027         $this->assertCount(1, get_enrolled_users($c1ctx));
1029         // Reset not allowed.
1030         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1031         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1032         $data = array('shortname' => $c1->shortname, 'reset' => '1');
1033         $importoptions = array('canreset' => false);
1034         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1035         $this->assertFalse($co->prepare());
1036         $this->assertArrayHasKey('courseresetnotallowed', $co->get_errors());
1037         $this->assertTrue($DB->record_exists('groups', array('id' => $g1->id)));
1038         $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $g1->id, 'userid' => $u1->id)));
1039         $this->assertCount(1, get_enrolled_users($c1ctx));
1041         // Reset allowed but not requested.
1042         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1043         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1044         $data = array('shortname' => $c1->shortname, 'reset' => '0');
1045         $importoptions = array('canreset' => true);
1046         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1047         $this->assertTrue($co->prepare());
1048         $co->proceed();
1049         $this->assertTrue($DB->record_exists('groups', array('id' => $g1->id)));
1050         $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $g1->id, 'userid' => $u1->id)));
1051         $this->assertCount(1, get_enrolled_users($c1ctx));
1053         // Reset passed as a default parameter, should not be taken in account.
1054         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1055         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1056         $data = array('shortname' => $c1->shortname);
1057         $importoptions = array('canreset' => true);
1058         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array('reset' => 1), $importoptions);
1059         $this->assertTrue($co->prepare());
1060         $co->proceed();
1061         $this->assertTrue($DB->record_exists('groups', array('id' => $g1->id)));
1062         $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $g1->id, 'userid' => $u1->id)));
1063         $this->assertCount(1, get_enrolled_users($c1ctx));
1065         // Reset executed from data.
1066         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1067         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1068         $data = array('shortname' => $c1->shortname, 'reset' => 1);
1069         $importoptions = array('canreset' => true);
1070         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1071         $this->assertTrue($co->prepare());
1072         $co->proceed();
1073         $this->assertFalse($DB->record_exists('groups', array('id' => $g1->id)));
1074         $this->assertFalse($DB->record_exists('groups_members', array('groupid' => $g1->id, 'userid' => $u1->id)));
1075         $this->assertCount(0, get_enrolled_users($c1ctx));
1077         // Reset executed from import option.
1078         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1079         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1080         $data = array('shortname' => $c1->shortname, 'reset' => 0);
1081         $importoptions = array('reset' => 1, 'canreset' => true);
1082         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1084         $g1 = $this->getDataGenerator()->create_group(array('courseid' => $c1->id));
1085         $this->getDataGenerator()->create_group_member(array('groupid' => $g1->id, 'userid' => $u1->id));
1086         $this->assertEquals(1, $DB->count_records('groups', array('courseid' => $c1->id)));
1087         $this->assertTrue($co->prepare());
1088         $co->proceed();
1089         $this->assertFalse($DB->record_exists('groups', array('id' => $g1->id)));
1090     }
1092     public function test_create_bad_category() {
1093         global $DB;
1094         $this->resetAfterTest(true);
1096         // Ensure fails when category cannot be resolved upon creation.
1097         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1098         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1099         $data = array('shortname' => 'c1', 'summary' => 'summary', 'fullname' => 'FN', 'category' => 'Wrong cat');
1100         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
1101         $this->assertFalse($co->prepare());
1102         $this->assertArrayHasKey('couldnotresolvecatgorybyid', $co->get_errors());
1104         // Ensure fails when category is 0 on create.
1105         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1106         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1107         $data = array('shortname' => 'c1', 'summary' => 'summary', 'fullname' => 'FN', 'category' => '0');
1108         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
1109         $this->assertFalse($co->prepare());
1110         $this->assertArrayHasKey('missingmandatoryfields', $co->get_errors());
1112         // Ensure fails when category cannot be resolved upon update.
1113         $c1 = $this->getDataGenerator()->create_course();
1114         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1115         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1116         $data = array('shortname' => $c1->shortname, 'category' => 'Wrong cat');
1117         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
1118         $this->assertFalse($co->prepare());
1119         $this->assertArrayHasKey('couldnotresolvecatgorybyid', $co->get_errors());
1121         // Ensure does not update the category when it is 0.
1122         $c1 = $this->getDataGenerator()->create_course();
1123         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1124         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1125         $data = array('shortname' => $c1->shortname, 'category' => '0');
1126         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
1127         $this->assertTrue($co->prepare());
1128         $this->assertEmpty($co->get_errors());
1129         $this->assertEmpty($co->get_statuses());
1130         $co->proceed();
1131         $this->assertEquals($c1->category, $DB->get_field('course', 'category', array('id' => $c1->id)));
1133         // Ensure does not update the category when it is set to 0 in the defaults.
1134         $c1 = $this->getDataGenerator()->create_course();
1135         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1136         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_OR_DEFAUTLS;
1137         $data = array('shortname' => $c1->shortname);
1138         $defaults = array('category' => '0');
1139         $co = new tool_uploadcourse_course($mode, $updatemode, $data, $defaults);
1140         $this->assertTrue($co->prepare());
1141         $this->assertEmpty($co->get_errors());
1142         $this->assertEmpty($co->get_statuses());
1143         $co->proceed();
1144         $this->assertEquals($c1->category, $DB->get_field('course', 'category', array('id' => $c1->id)));
1145     }
1147     public function test_enrolment_data() {
1148         $this->resetAfterTest(true);
1150         // We need to set the current user as one with the capability to edit manual enrolment instances in the new course.
1151         $this->setAdminUser();
1153         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1154         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1155         $data = array('shortname' => 'c1', 'summary' => 'S', 'fullname' => 'FN', 'category' => '1');
1156         $data['enrolment_1'] = 'manual';
1157         $data['enrolment_1_role'] = 'teacher';
1158         $data['enrolment_1_startdate'] = '2nd July 2013';
1159         $data['enrolment_1_enddate'] = '2nd August 2013';
1160         $data['enrolment_1_enrolperiod'] = '10 days';
1161         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
1162         $this->assertTrue($co->prepare());
1163         $co->proceed();
1165         // Enrolment methods.
1166         $enroldata = array();
1167         $instances = enrol_get_instances($co->get_id(), false);
1168         foreach ($instances as $instance) {
1169             $enroldata[$instance->enrol] = $instance;
1170         }
1172         $this->assertNotEmpty($enroldata['manual']);
1173         $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['manual']->status);
1174         $this->assertEquals(strtotime($data['enrolment_1_startdate']), $enroldata['manual']->enrolstartdate);
1175         $this->assertEquals(strtotime('1970-01-01 GMT + ' . $data['enrolment_1_enrolperiod']), $enroldata['manual']->enrolperiod);
1176         $this->assertEquals(strtotime('12th July 2013'), $enroldata['manual']->enrolenddate);
1177     }
1179     /**
1180      * Data provider for testing enrolment errors
1181      *
1182      * @return array
1183      */
1184     public function enrolment_uploaddata_error_provider(): array {
1185         return [
1186             ['errorcannotcreateorupdateenrolment', [
1187                 'shortname' => 'C1',
1188                 'enrolment_1' => 'manual',
1189             ]],
1190             ['errorcannotdeleteenrolment', [
1191                 'shortname' => 'C1',
1192                 'enrolment_1' => 'manual',
1193                 'enrolment_1_delete' => '1',
1194             ]],
1195             ['errorcannotdisableenrolment', [
1196                 'shortname' => 'C1',
1197                 'enrolment_1' => 'manual',
1198                 'enrolment_1_disable' => '1',
1199             ]],
1200         ];
1201     }
1203     /**
1204      * Test that user without permission, cannot modify enrolment instances when creating courses
1205      *
1206      * @param string $expectederror
1207      * @param array $uploaddata
1208      *
1209      * @dataProvider enrolment_uploaddata_error_provider
1210      */
1211     public function test_enrolment_error_create_course(string $expectederror, array $uploaddata): void {
1212         global $DB;
1214         $this->resetAfterTest();
1216         // Create category in which to create the new course.
1217         $category = $this->getDataGenerator()->create_category();
1218         $categorycontext = context_coursecat::instance($category->id);
1220         $user = $this->getDataGenerator()->create_user();
1221         $this->setUser($user);
1223         // Assign the user as a manager of the category, disable ability to configure manual enrolment instances.
1224         $roleid = $DB->get_field('role', 'id', ['shortname' => 'manager']);
1225         role_assign($roleid, $user->id, $categorycontext);
1226         role_change_permission($roleid, $categorycontext, 'enrol/manual:config', CAP_PROHIBIT);
1228         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1229         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1231         $upload = new tool_uploadcourse_course($mode, $updatemode, array_merge($uploaddata, [
1232             'category' => $category->id,
1233             'fullname' => 'My course',
1234         ]));
1236         // Enrolment validation isn't performed during 'prepare' for new courses.
1237         $this->assertTrue($upload->prepare());
1238         $upload->proceed();
1240         $errors = $upload->get_errors();
1241         $this->assertArrayHasKey($expectederror, $errors);
1243         $this->assertEquals(get_string($expectederror, 'tool_uploadcourse', 'Manual enrolments'),
1244             (string) $errors[$expectederror]);
1245     }
1247     /**
1248      * Test that user without permission, cannot modify enrolment instances when updating courses
1249      *
1250      * @param string $expectederror
1251      * @param array $uploaddata
1252      *
1253      * @dataProvider enrolment_uploaddata_error_provider
1254      */
1255     public function test_enrolment_error_update_course(string $expectederror, array $uploaddata): void {
1256         global $DB;
1258         $this->resetAfterTest();
1260         // Create category in which to create the new course.
1261         $category = $this->getDataGenerator()->create_category();
1262         $categorycontext = context_coursecat::instance($category->id);
1264         $course = $this->getDataGenerator()->create_course([
1265             'category' => $category->id,
1266             'shortname' => $uploaddata['shortname'],
1267         ]);
1269         $user = $this->getDataGenerator()->create_user();
1270         $this->setUser($user);
1272         // Assign the user as a manager of the category, disable ability to configure manual enrolment instances.
1273         $roleid = $DB->get_field('role', 'id', ['shortname' => 'manager']);
1274         role_assign($roleid, $user->id, $categorycontext);
1275         role_change_permission($roleid, $categorycontext, 'enrol/manual:config', CAP_PROHIBIT);
1277         // Sanity check.
1278         $instances = enrol_get_instances($course->id, true);
1279         $this->assertCount(1, $instances);
1280         $this->assertEquals('manual', reset($instances)->enrol);
1282         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1283         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1285         $upload = new tool_uploadcourse_course($mode, $updatemode, $uploaddata);
1287         $this->assertFalse($upload->prepare());
1289         $errors = $upload->get_errors();
1290         $this->assertArrayHasKey($expectederror, $errors);
1292         $this->assertEquals(get_string($expectederror, 'tool_uploadcourse', 'Manual enrolments'),
1293             (string) $errors[$expectederror]);
1294     }
1296     /**
1297      * Test upload processing of course custom fields
1298      */
1299     public function test_custom_fields_data() {
1300         $this->resetAfterTest();
1301         $this->setAdminUser();
1303         $course = $this->getDataGenerator()->create_course(['shortname' => 'C1']);
1305         // Create our custom fields.
1306         $category = $this->get_customfield_generator()->create_category();
1307         $this->create_custom_field($category, 'date', 'mydatefield');
1308         $this->create_custom_field($category, 'text', 'mytextfield');
1309         $this->create_custom_field($category, 'textarea', 'mytextareafield');
1311         // Perform upload.
1312         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1313         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1314         $dataupload = [
1315             'shortname' => $course->shortname,
1316             'customfield_mydatefield' => '2020-04-01 16:00',
1317             'customfield_mytextfield' => 'Hello',
1318             'customfield_mytextareafield' => 'Is it me you\'re looking for?',
1319         ];
1321         $uploader = new tool_uploadcourse_course($mode, $updatemode, $dataupload);
1322         $this->assertTrue($uploader->prepare());
1323         $uploader->proceed();
1325         // Confirm presence of course custom fields.
1326         $data = \core_course\customfield\course_handler::create()->export_instance_data_object($course->id);
1327         $this->assertEqualsIgnoringCase('Wednesday, 1 April 2020, 4:00 PM', $data->mydatefield);
1328         $this->assertEquals($dataupload['customfield_mytextfield'], $data->mytextfield);
1329         $this->assertStringContainsString($dataupload['customfield_mytextareafield'], $data->mytextareafield);
1330     }
1332     /**
1333      * Test upload processing of course custom field that is required but empty
1334      */
1335     public function test_custom_fields_data_required() {
1336         $this->resetAfterTest();
1337         $this->setAdminUser();
1339         $course = $this->getDataGenerator()->create_course(['shortname' => 'C1']);
1341         // Create our custom field.
1342         $category = $this->get_customfield_generator()->create_category();
1343         $this->create_custom_field($category, 'select', 'myselect', ['required' => true, 'options' => "Cat\nDog"]);
1345         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1346         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1347         $dataupload = [
1348             'shortname' => $course->shortname,
1349             'customfield_myselect' => null,
1350         ];
1352         $uploader = new tool_uploadcourse_course($mode, $updatemode, $dataupload);
1353         $this->assertFalse($uploader->prepare());
1354         $this->assertArrayHasKey('customfieldinvalid', $uploader->get_errors());
1356         // Try again with a default value.
1357         $defaults = [
1358             'customfield_myselect' => 2, // Our second option: Dog.
1359         ];
1361         $uploader = new tool_uploadcourse_course($mode, $updatemode, $dataupload, $defaults);
1362         $this->assertTrue($uploader->prepare());
1363         $uploader->proceed();
1365         // Confirm presence of course custom fields.
1366         $data = \core_course\customfield\course_handler::create()->export_instance_data_object($course->id);
1367         $this->assertEquals('Dog', $data->myselect);
1368     }
1370     /**
1371      * Test upload processing of course custom field with an invalid select option
1372      */
1373     public function test_custom_fields_data_invalid_select_option() {
1374         $this->resetAfterTest();
1375         $this->setAdminUser();
1377         $course = $this->getDataGenerator()->create_course(['shortname' => 'C1']);
1379         // Create our custom field.
1380         $category = $this->get_customfield_generator()->create_category();
1381         $this->create_custom_field($category, 'select', 'myselect',
1382             ['required' => true, 'options' => "Cat\nDog", 'defaultvalue' => 'Cat']);
1384         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1385         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1386         $dataupload = [
1387             'shortname' => $course->shortname,
1388             'customfield_myselect' => 'Fish', // No, invalid.
1389         ];
1391         $uploader = new tool_uploadcourse_course($mode, $updatemode, $dataupload);
1392         $this->assertTrue($uploader->prepare());
1393         $uploader->proceed();
1395         // Confirm presence of course custom fields.
1396         $data = \core_course\customfield\course_handler::create()->export_instance_data_object($course->id);
1397         $this->assertEquals('Cat', $data->myselect);
1398     }
1400     /**
1401      * Test upload processing of course custom field with an out of range date
1402      */
1403     public function test_custom_fields_data_invalid_date() {
1404         $this->resetAfterTest();
1405         $this->setAdminUser();
1407         $course = $this->getDataGenerator()->create_course(['shortname' => 'C1']);
1409         // Create our custom field.
1410         $category = $this->get_customfield_generator()->create_category();
1411         $this->create_custom_field($category, 'date', 'mydate',
1412             ['mindate' => strtotime('2020-04-01'), 'maxdate' => '2020-04-30']);
1414         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1415         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1416         $dataupload = [
1417             'shortname' => $course->shortname,
1418             'customfield_mydate' => '2020-05-06', // Out of range.
1419         ];
1421         $uploader = new tool_uploadcourse_course($mode, $updatemode, $dataupload);
1422         $this->assertFalse($uploader->prepare());
1423         $this->assertArrayHasKey('customfieldinvalid', $uploader->get_errors());
1424     }
1426     public function test_idnumber_problems() {
1427         $this->resetAfterTest(true);
1429         $c1 = $this->getDataGenerator()->create_course(array('shortname' => 'sntaken', 'idnumber' => 'taken'));
1430         $c2 = $this->getDataGenerator()->create_course();
1432         // Create with existing ID number.
1433         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1434         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1435         $data = array('shortname' => 'c2', 'summary' => 'summary', 'fullname' => 'FN', 'category' => '1',
1436             'idnumber' => $c1->idnumber);
1437         $co = new tool_uploadcourse_course($mode, $updatemode, $data);
1438         $this->assertFalse($co->prepare());
1439         $this->assertArrayHasKey('idnumberalreadyinuse', $co->get_errors());
1441         // Rename to existing ID number.
1442         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1443         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1444         $data = array('shortname' => $c2->shortname, 'rename' => 'SN', 'idnumber' => $c1->idnumber);
1445         $importoptions = array('canrename' => true);
1446         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1447         $this->assertFalse($co->prepare());
1448         $this->assertArrayHasKey('cannotrenameidnumberconflict', $co->get_errors());
1450         // Incrementing shortname increments idnumber.
1451         $mode = tool_uploadcourse_processor::MODE_CREATE_ALL;
1452         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
1453         $data = array('shortname' => $c1->shortname, 'idnumber' => $c1->idnumber, 'summary' => 'S', 'fullname' => 'F',
1454             'category' => 1);
1455         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), array());
1456         $this->assertTrue($co->prepare());
1457         $this->assertArrayHasKey('courseshortnameincremented', $co->get_statuses());
1458         $this->assertArrayHasKey('courseidnumberincremented', $co->get_statuses());
1459         $data = $co->get_data();
1460         $this->assertEquals('sntaken_2', $data['shortname']);
1461         $this->assertEquals('taken_2', $data['idnumber']);
1463         // Incrementing shortname increments idnumber unless available.
1464         $mode = tool_uploadcourse_processor::MODE_CREATE_ALL;
1465         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
1466         $data = array('shortname' => $c1->shortname, 'idnumber' => 'nottaken', 'summary' => 'S', 'fullname' => 'F',
1467             'category' => 1);
1468         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), array());
1469         $this->assertTrue($co->prepare());
1470         $this->assertArrayHasKey('courseshortnameincremented', $co->get_statuses());
1471         $this->assertArrayNotHasKey('courseidnumberincremented', $co->get_statuses());
1472         $data = $co->get_data();
1473         $this->assertEquals('sntaken_2', $data['shortname']);
1474         $this->assertEquals('nottaken', $data['idnumber']);
1475     }
1477     public function test_generate_shortname() {
1478         $this->resetAfterTest(true);
1480         $c1 = $this->getDataGenerator()->create_course(array('shortname' => 'taken'));
1482         // Generate a shortname.
1483         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1484         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
1485         $data = array('summary' => 'summary', 'fullname' => 'FN', 'category' => '1', 'idnumber' => 'IDN');
1486         $importoptions = array('shortnametemplate' => '%i');
1487         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1488         $this->assertTrue($co->prepare());
1489         $this->assertArrayHasKey('courseshortnamegenerated', $co->get_statuses());
1491         // Generate a shortname without a template.
1492         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1493         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
1494         $data = array('summary' => 'summary', 'fullname' => 'FN', 'category' => '1');
1495         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), array());
1496         $this->assertFalse($co->prepare());
1497         $this->assertArrayHasKey('missingshortnamenotemplate', $co->get_errors());
1499         // Generate a shortname in update mode.
1500         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1501         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1502         $data = array('summary' => 'summary', 'fullname' => 'FN', 'category' => '1');
1503         $importoptions = array('shortnametemplate' => '%f');
1504         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1505         $this->assertFalse($co->prepare());
1506         // Commented because we never get here as the course without shortname does not exist.
1507         // $this->assertArrayHasKey('cannotgenerateshortnameupdatemode', $co->get_errors());
1509         // Generate a shortname to a course that already exists.
1510         $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
1511         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
1512         $data = array('summary' => 'summary', 'fullname' => 'taken', 'category' => '1');
1513         $importoptions = array('shortnametemplate' => '%f');
1514         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1515         $this->assertFalse($co->prepare());
1516         $this->assertArrayHasKey('generatedshortnamealreadyinuse', $co->get_errors());
1518         // Generate a shortname to a course that already exists will be incremented.
1519         $mode = tool_uploadcourse_processor::MODE_CREATE_ALL;
1520         $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
1521         $data = array('summary' => 'summary', 'fullname' => 'taken', 'category' => '1');
1522         $importoptions = array('shortnametemplate' => '%f');
1523         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1524         $this->assertTrue($co->prepare());
1525         $this->assertArrayHasKey('courseshortnamegenerated', $co->get_statuses());
1526         $this->assertArrayHasKey('courseshortnameincremented', $co->get_statuses());
1527     }
1529     public function test_mess_with_frontpage() {
1530         global $SITE;
1531         $this->resetAfterTest(true);
1533         // Updating the front page.
1534         $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
1535         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1536         $data = array('shortname' => $SITE->shortname, 'idnumber' => 'NewIDN');
1537         $importoptions = array();
1538         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1539         $this->assertFalse($co->prepare());
1540         $this->assertArrayHasKey('cannotupdatefrontpage', $co->get_errors());
1542         // Updating the front page.
1543         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
1544         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1545         $data = array('shortname' => $SITE->shortname, 'idnumber' => 'NewIDN');
1546         $importoptions = array();
1547         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1548         $this->assertFalse($co->prepare());
1549         $this->assertArrayHasKey('cannotupdatefrontpage', $co->get_errors());
1551         // Generating a shortname should not be allowed in update mode, and so we cannot update the front page.
1552         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
1553         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1554         $data = array('idnumber' => 'NewIDN', 'fullname' => 'FN', 'category' => 1);
1555         $importoptions = array('shortnametemplate' => $SITE->shortname);
1556         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1557         $this->assertFalse($co->prepare());
1558         $this->assertArrayHasKey('cannotgenerateshortnameupdatemode', $co->get_errors());
1560         // Renaming to the front page should not be allowed.
1561         $c1 = $this->getDataGenerator()->create_course();
1562         $mode = tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE;
1563         $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
1564         $data = array('shortname' => $c1->shortname, 'fullname' => 'FN', 'idnumber' => 'NewIDN', 'rename' => $SITE->shortname);
1565         $importoptions = array('canrename' => true);
1566         $co = new tool_uploadcourse_course($mode, $updatemode, $data, array(), $importoptions);
1567         $this->assertFalse($co->prepare());
1568         $this->assertArrayHasKey('cannotrenameshortnamealreadyinuse', $co->get_errors());
1569     }
1571     /**
1572      * Get custom field plugin generator
1573      *
1574      * @return core_customfield_generator
1575      */
1576     protected function get_customfield_generator() : core_customfield_generator {
1577         return $this->getDataGenerator()->get_plugin_generator('core_customfield');
1578     }
1580     /**
1581      * Helper method to create custom course field
1582      *
1583      * @param \core_customfield\category_controller $category
1584      * @param string $type
1585      * @param string $shortname
1586      * @param array $configdata
1587      * @return \core_customfield\field_controller
1588      */
1589     protected function create_custom_field(\core_customfield\category_controller $category, string $type, string $shortname,
1590             array $configdata = []) : \core_customfield\field_controller {
1592         return $this->get_customfield_generator()->create_field([
1593             'categoryid' => $category->get('id'),
1594             'type' => $type,
1595             'shortname' => $shortname,
1596             'configdata' => $configdata,
1597         ]);
1598     }