MDL-80949 mod_data: Remove unused Allow autolink param for text field
[moodle.git] / course / edit_form.php
blob0c1879ad9bb53c96aaa8065dbadefaa1ffbdf9db
1 <?php
3 defined('MOODLE_INTERNAL') || die;
5 require_once($CFG->libdir.'/formslib.php');
6 require_once($CFG->libdir.'/completionlib.php');
7 require_once($CFG->libdir . '/pdflib.php');
9 /**
10 * The form for handling editing a course.
12 class course_edit_form extends moodleform {
13 protected $course;
14 protected $context;
16 /**
17 * Form definition.
19 function definition() {
20 global $CFG, $PAGE;
22 $mform = $this->_form;
23 $PAGE->requires->js_call_amd('core_course/formatchooser', 'init');
25 $course = $this->_customdata['course']; // this contains the data of this form
26 $category = $this->_customdata['category'];
27 $editoroptions = $this->_customdata['editoroptions'];
28 $returnto = $this->_customdata['returnto'];
29 $returnurl = $this->_customdata['returnurl'];
31 $systemcontext = context_system::instance();
32 $categorycontext = context_coursecat::instance($category->id);
34 if (!empty($course->id)) {
35 $coursecontext = context_course::instance($course->id);
36 $context = $coursecontext;
37 } else {
38 $coursecontext = null;
39 $context = $categorycontext;
42 $courseconfig = get_config('moodlecourse');
44 $this->course = $course;
45 $this->context = $context;
47 // Form definition with new course defaults.
48 $mform->addElement('header','general', get_string('general', 'form'));
50 $mform->addElement('hidden', 'returnto', null);
51 $mform->setType('returnto', PARAM_ALPHANUM);
52 $mform->setConstant('returnto', $returnto);
54 $mform->addElement('hidden', 'returnurl', null);
55 $mform->setType('returnurl', PARAM_LOCALURL);
56 $mform->setConstant('returnurl', $returnurl);
58 $mform->addElement('text','fullname', get_string('fullnamecourse'),'maxlength="254" size="50"');
59 $mform->addHelpButton('fullname', 'fullnamecourse');
60 $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
61 $mform->setType('fullname', PARAM_TEXT);
62 if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) {
63 $mform->hardFreeze('fullname');
64 $mform->setConstant('fullname', $course->fullname);
67 $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
68 $mform->addHelpButton('shortname', 'shortnamecourse');
69 $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
70 $mform->setType('shortname', PARAM_TEXT);
71 if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) {
72 $mform->hardFreeze('shortname');
73 $mform->setConstant('shortname', $course->shortname);
76 // Verify permissions to change course category or keep current.
77 if (empty($course->id)) {
78 if (has_capability('moodle/course:create', $categorycontext)) {
79 $displaylist = core_course_category::make_categories_list('moodle/course:create');
80 $mform->addElement('autocomplete', 'category', get_string('coursecategory'), $displaylist);
81 $mform->addRule('category', null, 'required', null, 'client');
82 $mform->addHelpButton('category', 'coursecategory');
83 $mform->setDefault('category', $category->id);
84 } else {
85 $mform->addElement('hidden', 'category', null);
86 $mform->setType('category', PARAM_INT);
87 $mform->setConstant('category', $category->id);
89 } else {
90 if (has_capability('moodle/course:changecategory', $coursecontext)) {
91 $displaylist = core_course_category::make_categories_list('moodle/course:changecategory');
92 if (!isset($displaylist[$course->category])) {
93 //always keep current
94 $displaylist[$course->category] = core_course_category::get($course->category, MUST_EXIST, true)
95 ->get_formatted_name();
97 $mform->addElement('autocomplete', 'category', get_string('coursecategory'), $displaylist);
98 $mform->addRule('category', null, 'required', null, 'client');
99 $mform->addHelpButton('category', 'coursecategory');
100 } else {
101 //keep current
102 $mform->addElement('hidden', 'category', null);
103 $mform->setType('category', PARAM_INT);
104 $mform->setConstant('category', $course->category);
108 $choices = array();
109 $choices['0'] = get_string('hide');
110 $choices['1'] = get_string('show');
111 $mform->addElement('select', 'visible', get_string('coursevisibility'), $choices);
112 $mform->addHelpButton('visible', 'coursevisibility');
113 $mform->setDefault('visible', $courseconfig->visible);
114 if (!empty($course->id)) {
115 if (!has_capability('moodle/course:visibility', $coursecontext)) {
116 $mform->hardFreeze('visible');
117 $mform->setConstant('visible', $course->visible);
119 } else {
120 if (!guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext)) {
121 $mform->hardFreeze('visible');
122 $mform->setConstant('visible', $courseconfig->visible);
126 // Download course content.
127 if ($CFG->downloadcoursecontentallowed) {
128 $downloadchoices = [
129 DOWNLOAD_COURSE_CONTENT_DISABLED => get_string('no'),
130 DOWNLOAD_COURSE_CONTENT_ENABLED => get_string('yes'),
132 $sitedefaultstring = $downloadchoices[$courseconfig->downloadcontentsitedefault];
133 $downloadchoices[DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT] = get_string('sitedefaultspecified', '', $sitedefaultstring);
134 $downloadselectdefault = $courseconfig->downloadcontent ?? DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT;
136 $mform->addElement('select', 'downloadcontent', get_string('enabledownloadcoursecontent', 'course'), $downloadchoices);
137 $mform->addHelpButton('downloadcontent', 'downloadcoursecontent', 'course');
138 $mform->setDefault('downloadcontent', $downloadselectdefault);
140 if ((!empty($course->id) && !has_capability('moodle/course:configuredownloadcontent', $coursecontext)) ||
141 (empty($course->id) &&
142 !guess_if_creator_will_have_course_capability('moodle/course:configuredownloadcontent', $categorycontext))) {
143 $mform->hardFreeze('downloadcontent');
144 $mform->setConstant('downloadcontent', $downloadselectdefault);
148 // Get the task to change automatically the course visibility when the current day matches the course start date.
149 $task = \core\task\manager::get_scheduled_task('\core\task\show_started_courses_task');
150 $startdatestring = 'startdate';
151 if (!empty($task) && !$task->get_disabled()) {
152 // When the task is enabled, display a different help message.
153 $startdatestring = 'startdatewithtaskenabled';
155 $mform->addElement('date_time_selector', 'startdate', get_string('startdate'));
156 $mform->addHelpButton('startdate', $startdatestring);
157 $date = (new DateTime())->setTimestamp(usergetmidnight(time()));
158 $date->modify('+1 day');
159 $mform->setDefault('startdate', $date->getTimestamp());
161 // Get the task to change automatically the course visibility when the current day matches the course end date.
162 $task = \core\task\manager::get_scheduled_task('\core\task\hide_ended_courses_task');
163 $enddatestring = 'enddate';
164 if (!empty($task) && !$task->get_disabled()) {
165 // When the task is enabled, display a different help message.
166 $enddatestring = 'enddatewithtaskenabled';
168 $mform->addElement('date_time_selector', 'enddate', get_string('enddate'), array('optional' => true));
169 $mform->addHelpButton('enddate', $enddatestring);
171 if (!empty($CFG->enablecourserelativedates)) {
172 $attributes = [
173 'aria-describedby' => 'relativedatesmode_warning'
175 if (!empty($course->id)) {
176 $attributes['disabled'] = true;
178 $relativeoptions = [
179 0 => get_string('no'),
180 1 => get_string('yes'),
182 $relativedatesmodegroup = [];
183 $relativedatesmodegroup[] = $mform->createElement('select', 'relativedatesmode', get_string('relativedatesmode'),
184 $relativeoptions, $attributes);
185 $relativedatesmodegroup[] = $mform->createElement('html', html_writer::span(get_string('relativedatesmode_warning'),
186 '', ['id' => 'relativedatesmode_warning']));
187 $mform->addGroup($relativedatesmodegroup, 'relativedatesmodegroup', get_string('relativedatesmode'), null, false);
188 $mform->addHelpButton('relativedatesmodegroup', 'relativedatesmode');
191 $mform->addElement('text','idnumber', get_string('idnumbercourse'),'maxlength="100" size="10"');
192 $mform->addHelpButton('idnumber', 'idnumbercourse');
193 $mform->setType('idnumber', PARAM_RAW);
194 if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
195 $mform->hardFreeze('idnumber');
196 $mform->setConstants('idnumber', $course->idnumber);
199 // Description.
200 $mform->addElement('header', 'descriptionhdr', get_string('description'));
201 $mform->setExpanded('descriptionhdr');
203 $mform->addElement('editor','summary_editor', get_string('coursesummary'), null, $editoroptions);
204 $mform->addHelpButton('summary_editor', 'coursesummary');
205 $mform->setType('summary_editor', PARAM_RAW);
206 $summaryfields = 'summary_editor';
208 if ($overviewfilesoptions = course_overviewfiles_options($course)) {
209 $mform->addElement('filemanager', 'overviewfiles_filemanager', get_string('courseoverviewfiles'), null, $overviewfilesoptions);
210 $mform->addHelpButton('overviewfiles_filemanager', 'courseoverviewfiles');
211 $summaryfields .= ',overviewfiles_filemanager';
214 if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) {
215 // Remove the description header it does not contain anything any more.
216 $mform->removeElement('descriptionhdr');
217 $mform->hardFreeze($summaryfields);
220 // Course format.
221 $mform->addElement('header', 'courseformathdr', get_string('type_format', 'plugin'));
223 $courseformats = get_sorted_course_formats(true);
224 $formcourseformats = new core\output\choicelist();
225 $formcourseformats->set_allow_empty(false);
226 foreach ($courseformats as $courseformat) {
227 $definition = [];
228 $component = "format_$courseformat";
229 if (get_string_manager()->string_exists('plugin_description', $component)) {
230 $definition['description'] = get_string('plugin_description', $component);
232 $formcourseformats->add_option(
233 $courseformat,
234 get_string('pluginname', "format_$courseformat"),
236 'description' => $definition,
240 if (isset($course->format)) {
241 $course->format = course_get_format($course)->get_format(); // Replace with default if not found.
242 if (!in_array($course->format, $courseformats)) {
243 // This format is disabled. Still display it in the dropdown.
244 $formcourseformats->add_option(
245 $course->format,
246 get_string('withdisablednote', 'moodle', get_string('pluginname', 'format_'.$course->format)),
251 $mform->addElement(
252 'choicedropdown',
253 'format',
254 get_string('format'),
255 $formcourseformats,
256 ['data-formatchooser-field' => 'selector'],
258 $mform->setDefault('format', $courseconfig->format);
260 // Button to update format-specific options on format change (will be hidden by JavaScript).
261 $mform->registerNoSubmitButton('updatecourseformat');
262 $mform->addElement('submit', 'updatecourseformat', get_string('courseformatudpate'), [
263 'data-formatchooser-field' => 'updateButton',
264 'class' => 'd-none',
267 // Just a placeholder for the course format options.
268 $mform->addElement('hidden', 'addcourseformatoptionshere');
269 $mform->setType('addcourseformatoptionshere', PARAM_BOOL);
271 // Appearance.
272 $mform->addElement('header', 'appearancehdr', get_string('appearance'));
274 if (!empty($CFG->allowcoursethemes)) {
275 $themeobjects = get_list_of_themes();
276 $themes=array();
277 $themes[''] = get_string('forceno');
278 foreach ($themeobjects as $key=>$theme) {
279 if (empty($theme->hidefromselector)) {
280 $themes[$key] = get_string('pluginname', 'theme_'.$theme->name);
283 $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
286 if ((empty($course->id) && guess_if_creator_will_have_course_capability('moodle/course:setforcedlanguage', $categorycontext))
287 || (!empty($course->id) && has_capability('moodle/course:setforcedlanguage', $coursecontext))) {
289 $languages = ['' => get_string('forceno')];
290 $languages += get_string_manager()->get_list_of_translations();
292 $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
293 $mform->setDefault('lang', $courseconfig->lang);
296 // Multi-Calendar Support - see MDL-18375.
297 $calendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
298 // We do not want to show this option unless there is more than one calendar type to display.
299 if (count($calendartypes) > 1) {
300 $calendars = array();
301 $calendars[''] = get_string('forceno');
302 $calendars += $calendartypes;
303 $mform->addElement('select', 'calendartype', get_string('forcecalendartype', 'calendar'), $calendars);
306 $options = range(0, 10);
307 $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
308 $courseconfig = get_config('moodlecourse');
309 $mform->setDefault('newsitems', $courseconfig->newsitems);
310 $mform->addHelpButton('newsitems', 'newsitemsnumber');
312 $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
313 $mform->addHelpButton('showgrades', 'showgrades');
314 $mform->setDefault('showgrades', $courseconfig->showgrades);
316 $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
317 $mform->addHelpButton('showreports', 'showreports');
318 $mform->setDefault('showreports', $courseconfig->showreports);
320 // Show activity dates.
321 $mform->addElement('selectyesno', 'showactivitydates', get_string('showactivitydates'));
322 $mform->addHelpButton('showactivitydates', 'showactivitydates');
323 $mform->setDefault('showactivitydates', $courseconfig->showactivitydates);
325 // Files and uploads.
326 $mform->addElement('header', 'filehdr', get_string('filesanduploads'));
328 if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) {
329 if (empty($course->legacyfiles)) {
330 //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet
331 $choices = array('0'=>get_string('no'), '2'=>get_string('yes'));
332 } else {
333 $choices = array('1'=>get_string('no'), '2'=>get_string('yes'));
335 $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices);
336 $mform->addHelpButton('legacyfiles', 'courselegacyfiles');
337 if (!isset($courseconfig->legacyfiles)) {
338 // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses
339 $courseconfig->legacyfiles = 0;
341 $mform->setDefault('legacyfiles', $courseconfig->legacyfiles);
344 // Handle non-existing $course->maxbytes on course creation.
345 $coursemaxbytes = !isset($course->maxbytes) ? null : $course->maxbytes;
347 // Let's prepare the maxbytes popup.
348 $choices = get_max_upload_sizes($CFG->maxbytes, 0, 0, $coursemaxbytes);
349 $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
350 $mform->addHelpButton('maxbytes', 'maximumupload');
351 $mform->setDefault('maxbytes', $courseconfig->maxbytes);
353 // PDF font.
354 if (!empty($CFG->enablepdfexportfont)) {
355 $pdf = new \pdf;
356 $fontlist = $pdf->get_export_fontlist();
357 // Show the option if the font is defined more than one.
358 if (count($fontlist) > 1) {
359 $defaultfont = $courseconfig->pdfexportfont ?? 'freesans';
360 if (empty($fontlist[$defaultfont])) {
361 $defaultfont = current($fontlist);
363 $mform->addElement('select', 'pdfexportfont', get_string('pdfexportfont', 'course'), $fontlist);
364 $mform->addHelpButton('pdfexportfont', 'pdfexportfont', 'course');
365 $mform->setDefault('pdfexportfont', $defaultfont);
369 // Completion tracking.
370 if (completion_info::is_enabled_for_site()) {
371 $mform->addElement('header', 'completionhdr', get_string('completion', 'completion'));
372 $mform->addElement('selectyesno', 'enablecompletion', get_string('enablecompletion', 'completion'));
373 $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
374 $mform->addHelpButton('enablecompletion', 'enablecompletion', 'completion');
376 $showcompletionconditions = $courseconfig->showcompletionconditions ?? COMPLETION_SHOW_CONDITIONS;
377 $mform->addElement('selectyesno', 'showcompletionconditions', get_string('showcompletionconditions', 'completion'));
378 $mform->addHelpButton('showcompletionconditions', 'showcompletionconditions', 'completion');
379 $mform->setDefault('showcompletionconditions', $showcompletionconditions);
380 $mform->hideIf('showcompletionconditions', 'enablecompletion', 'eq', COMPLETION_DISABLED);
381 } else {
382 $mform->addElement('hidden', 'enablecompletion');
383 $mform->setType('enablecompletion', PARAM_INT);
384 $mform->setDefault('enablecompletion', 0);
387 enrol_course_edit_form($mform, $course, $context);
389 $mform->addElement('header','groups', get_string('groupsettingsheader', 'group'));
391 $choices = array();
392 $choices[NOGROUPS] = get_string('groupsnone', 'group');
393 $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
394 $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
395 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices);
396 $mform->addHelpButton('groupmode', 'groupmode', 'group');
397 $mform->setDefault('groupmode', $courseconfig->groupmode);
399 $mform->addElement('selectyesno', 'groupmodeforce', get_string('groupmodeforce', 'group'));
400 $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group');
401 $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
403 //default groupings selector
404 $options = array();
405 $options[0] = get_string('none');
406 $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
408 if (core_tag_tag::is_enabled('core', 'course') &&
409 ((empty($course->id) && guess_if_creator_will_have_course_capability('moodle/course:tag', $categorycontext))
410 || (!empty($course->id) && has_capability('moodle/course:tag', $coursecontext)))) {
411 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
412 $mform->addElement('tags', 'tags', get_string('tags'),
413 array('itemtype' => 'course', 'component' => 'core'));
416 // Add custom fields to the form.
417 $handler = core_course\customfield\course_handler::create();
418 $handler->set_parent_context($categorycontext); // For course handler only.
419 $handler->instance_form_definition($mform, empty($course->id) ? 0 : $course->id);
421 $hook = new \core_course\hook\after_form_definition($this, $mform);
422 \core\hook\manager::get_instance()->dispatch($hook);
424 // When two elements we need a group.
425 $buttonarray = array();
426 $classarray = array('class' => 'form-submit');
427 if ($returnto !== 0) {
428 $buttonarray[] = &$mform->createElement('submit', 'saveandreturn', get_string('savechangesandreturn'), $classarray);
430 $buttonarray[] = &$mform->createElement('submit', 'saveanddisplay', get_string('savechangesanddisplay'), $classarray);
431 $buttonarray[] = &$mform->createElement('cancel');
432 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
433 $mform->closeHeaderBefore('buttonar');
435 $mform->addElement('hidden', 'id', null);
436 $mform->setType('id', PARAM_INT);
438 // Prepare custom fields data.
439 $handler->instance_form_before_set_data($course);
440 // Finally set the current form data
441 $this->set_data($course);
445 * Fill in the current page data for this course.
447 function definition_after_data() {
448 global $DB;
450 $mform = $this->_form;
452 // add available groupings
453 $courseid = $mform->getElementValue('id');
454 if ($courseid and $mform->elementExists('defaultgroupingid')) {
455 $options = array();
456 if ($groupings = $DB->get_records('groupings', array('courseid'=>$courseid))) {
457 foreach ($groupings as $grouping) {
458 $options[$grouping->id] = format_string($grouping->name);
461 core_collator::asort($options);
462 $gr_el =& $mform->getElement('defaultgroupingid');
463 $gr_el->load($options);
466 // add course format options
467 $formatvalue = $mform->getElementValue('format');
468 if (is_array($formatvalue) && !empty($formatvalue)) {
470 $params = array('format' => $formatvalue[0]);
471 // Load the course as well if it is available, course formats may need it to work out
472 // they preferred course end date.
473 if ($courseid) {
474 $params['id'] = $courseid;
476 $courseformat = course_get_format((object)$params);
478 $elements = $courseformat->create_edit_form_elements($mform);
479 for ($i = 0; $i < count($elements); $i++) {
480 $mform->insertElementBefore($mform->removeElement($elements[$i]->getName(), false),
481 'addcourseformatoptionshere');
484 // Remove newsitems element if format does not support news.
485 if (!$courseformat->supports_news()) {
486 $mform->removeElement('newsitems');
490 // Tweak the form with values provided by custom fields in use.
491 $handler = core_course\customfield\course_handler::create();
492 $handler->instance_form_definition_after_data($mform, empty($courseid) ? 0 : $courseid);
494 $hook = new \core_course\hook\after_form_definition_after_data($this, $mform);
495 \core\hook\manager::get_instance()->dispatch($hook);
499 * Validation.
501 * @param array $data
502 * @param array $files
503 * @return array the errors that were found
505 function validation($data, $files) {
506 global $DB;
508 $errors = parent::validation($data, $files);
510 // Add field validation check for duplicate shortname.
511 if ($course = $DB->get_record('course', array('shortname' => $data['shortname']), '*', IGNORE_MULTIPLE)) {
512 if (empty($data['id']) || $course->id != $data['id']) {
513 $errors['shortname'] = get_string('shortnametaken', '', $course->fullname);
517 // Add field validation check for duplicate idnumber.
518 if (!empty($data['idnumber']) && (empty($data['id']) || $this->course->idnumber != $data['idnumber'])) {
519 if ($course = $DB->get_record('course', array('idnumber' => $data['idnumber']), '*', IGNORE_MULTIPLE)) {
520 if (empty($data['id']) || $course->id != $data['id']) {
521 $errors['idnumber'] = get_string('courseidnumbertaken', 'error', $course->fullname);
526 if ($errorcode = course_validate_dates($data)) {
527 $errors['enddate'] = get_string($errorcode, 'error');
530 $errors = array_merge($errors, enrol_course_edit_validation($data, $this->context));
532 $courseformat = course_get_format((object)array('format' => $data['format']));
533 $formaterrors = $courseformat->edit_form_validation($data, $files, $errors);
534 if (!empty($formaterrors) && is_array($formaterrors)) {
535 $errors = array_merge($errors, $formaterrors);
538 // Add the custom fields validation.
539 $handler = core_course\customfield\course_handler::create();
540 $errors = array_merge($errors, $handler->instance_form_validation($data, $files));
542 $hook = new \core_course\hook\after_form_validation($this, $data, $files);
543 \core\hook\manager::get_instance()->dispatch($hook);
544 $pluginerrors = $hook->get_errors();
545 if (!empty($pluginerrors)) {
546 $errors = array_merge($errors, $pluginerrors);
549 return $errors;
553 * Returns course object.
555 * @return \stdClass
557 public function get_course(): stdClass {
558 return $this->course;
562 * Returns context.
564 * @return \core\context
566 public function get_context(): \core\context {
567 return $this->context;