MDL-43648 course: Allow start /end dates to have times
[moodle.git] / course / edit_form.php
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. '/coursecatlib.php');
9 /**
10  * The form for handling editing a course.
11  */
12 class course_edit_form extends moodleform {
13     protected $course;
14     protected $context;
16     /**
17      * Form definition.
18      */
19     function definition() {
20         global $CFG, $PAGE;
22         $mform    = $this->_form;
23         $PAGE->requires->yui_module('moodle-course-formatchooser', 'M.course.init_formatchooser',
24                 array(array('formid' => $mform->getAttribute('id'))));
26         $course        = $this->_customdata['course']; // this contains the data of this form
27         $category      = $this->_customdata['category'];
28         $editoroptions = $this->_customdata['editoroptions'];
29         $returnto = $this->_customdata['returnto'];
30         $returnurl = $this->_customdata['returnurl'];
32         $systemcontext   = context_system::instance();
33         $categorycontext = context_coursecat::instance($category->id);
35         if (!empty($course->id)) {
36             $coursecontext = context_course::instance($course->id);
37             $context = $coursecontext;
38         } else {
39             $coursecontext = null;
40             $context = $categorycontext;
41         }
43         $courseconfig = get_config('moodlecourse');
45         $this->course  = $course;
46         $this->context = $context;
48         // Form definition with new course defaults.
49         $mform->addElement('header','general', get_string('general', 'form'));
51         $mform->addElement('hidden', 'returnto', null);
52         $mform->setType('returnto', PARAM_ALPHANUM);
53         $mform->setConstant('returnto', $returnto);
55         $mform->addElement('hidden', 'returnurl', null);
56         $mform->setType('returnurl', PARAM_LOCALURL);
57         $mform->setConstant('returnurl', $returnurl);
59         $mform->addElement('text','fullname', get_string('fullnamecourse'),'maxlength="254" size="50"');
60         $mform->addHelpButton('fullname', 'fullnamecourse');
61         $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
62         $mform->setType('fullname', PARAM_TEXT);
63         if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) {
64             $mform->hardFreeze('fullname');
65             $mform->setConstant('fullname', $course->fullname);
66         }
68         $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
69         $mform->addHelpButton('shortname', 'shortnamecourse');
70         $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
71         $mform->setType('shortname', PARAM_TEXT);
72         if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) {
73             $mform->hardFreeze('shortname');
74             $mform->setConstant('shortname', $course->shortname);
75         }
77         // Verify permissions to change course category or keep current.
78         if (empty($course->id)) {
79             if (has_capability('moodle/course:create', $categorycontext)) {
80                 $displaylist = coursecat::make_categories_list('moodle/course:create');
81                 $mform->addElement('select', 'category', get_string('coursecategory'), $displaylist);
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);
88             }
89         } else {
90             if (has_capability('moodle/course:changecategory', $coursecontext)) {
91                 $displaylist = coursecat::make_categories_list('moodle/course:create');
92                 if (!isset($displaylist[$course->category])) {
93                     //always keep current
94                     $displaylist[$course->category] = coursecat::get($course->category, MUST_EXIST, true)->get_formatted_name();
95                 }
96                 $mform->addElement('select', 'category', get_string('coursecategory'), $displaylist);
97                 $mform->addHelpButton('category', 'coursecategory');
98             } else {
99                 //keep current
100                 $mform->addElement('hidden', 'category', null);
101                 $mform->setType('category', PARAM_INT);
102                 $mform->setConstant('category', $course->category);
103             }
104         }
106         $choices = array();
107         $choices['0'] = get_string('hide');
108         $choices['1'] = get_string('show');
109         $mform->addElement('select', 'visible', get_string('coursevisibility'), $choices);
110         $mform->addHelpButton('visible', 'coursevisibility');
111         $mform->setDefault('visible', $courseconfig->visible);
112         if (!empty($course->id)) {
113             if (!has_capability('moodle/course:visibility', $coursecontext)) {
114                 $mform->hardFreeze('visible');
115                 $mform->setConstant('visible', $course->visible);
116             }
117         } else {
118             if (!guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext)) {
119                 $mform->hardFreeze('visible');
120                 $mform->setConstant('visible', $courseconfig->visible);
121             }
122         }
123         $mform->addElement('date_time_selector', 'startdate', get_string('startdate'));
124         $mform->addHelpButton('startdate', 'startdate');
125         $date = (new DateTime())->setTimestamp(usergetmidnight(time()));
126         $date->modify('+1 day');
127         $mform->setDefault('startdate', $date->getTimestamp());
129         $mform->addElement('date_time_selector', 'enddate', get_string('enddate'), array('optional' => true));
130         $mform->addHelpButton('enddate', 'enddate');
132         $mform->addElement('text','idnumber', get_string('idnumbercourse'),'maxlength="100"  size="10"');
133         $mform->addHelpButton('idnumber', 'idnumbercourse');
134         $mform->setType('idnumber', PARAM_RAW);
135         if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
136             $mform->hardFreeze('idnumber');
137             $mform->setConstants('idnumber', $course->idnumber);
138         }
140         // Description.
141         $mform->addElement('header', 'descriptionhdr', get_string('description'));
142         $mform->setExpanded('descriptionhdr');
144         $mform->addElement('editor','summary_editor', get_string('coursesummary'), null, $editoroptions);
145         $mform->addHelpButton('summary_editor', 'coursesummary');
146         $mform->setType('summary_editor', PARAM_RAW);
147         $summaryfields = 'summary_editor';
149         if ($overviewfilesoptions = course_overviewfiles_options($course)) {
150             $mform->addElement('filemanager', 'overviewfiles_filemanager', get_string('courseoverviewfiles'), null, $overviewfilesoptions);
151             $mform->addHelpButton('overviewfiles_filemanager', 'courseoverviewfiles');
152             $summaryfields .= ',overviewfiles_filemanager';
153         }
155         if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) {
156             // Remove the description header it does not contain anything any more.
157             $mform->removeElement('descriptionhdr');
158             $mform->hardFreeze($summaryfields);
159         }
161         // Course format.
162         $mform->addElement('header', 'courseformathdr', get_string('type_format', 'plugin'));
164         $courseformats = get_sorted_course_formats(true);
165         $formcourseformats = array();
166         foreach ($courseformats as $courseformat) {
167             $formcourseformats[$courseformat] = get_string('pluginname', "format_$courseformat");
168         }
169         if (isset($course->format)) {
170             $course->format = course_get_format($course)->get_format(); // replace with default if not found
171             if (!in_array($course->format, $courseformats)) {
172                 // this format is disabled. Still display it in the dropdown
173                 $formcourseformats[$course->format] = get_string('withdisablednote', 'moodle',
174                         get_string('pluginname', 'format_'.$course->format));
175             }
176         }
178         $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
179         $mform->addHelpButton('format', 'format');
180         $mform->setDefault('format', $courseconfig->format);
182         // Button to update format-specific options on format change (will be hidden by JavaScript).
183         $mform->registerNoSubmitButton('updatecourseformat');
184         $mform->addElement('submit', 'updatecourseformat', get_string('courseformatudpate'));
186         // Just a placeholder for the course format options.
187         $mform->addElement('hidden', 'addcourseformatoptionshere');
188         $mform->setType('addcourseformatoptionshere', PARAM_BOOL);
190         // Appearance.
191         $mform->addElement('header', 'appearancehdr', get_string('appearance'));
193         if (!empty($CFG->allowcoursethemes)) {
194             $themeobjects = get_list_of_themes();
195             $themes=array();
196             $themes[''] = get_string('forceno');
197             foreach ($themeobjects as $key=>$theme) {
198                 if (empty($theme->hidefromselector)) {
199                     $themes[$key] = get_string('pluginname', 'theme_'.$theme->name);
200                 }
201             }
202             $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
203         }
205         $languages=array();
206         $languages[''] = get_string('forceno');
207         $languages += get_string_manager()->get_list_of_translations();
208         $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
209         $mform->setDefault('lang', $courseconfig->lang);
211         // Multi-Calendar Support - see MDL-18375.
212         $calendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
213         // We do not want to show this option unless there is more than one calendar type to display.
214         if (count($calendartypes) > 1) {
215             $calendars = array();
216             $calendars[''] = get_string('forceno');
217             $calendars += $calendartypes;
218             $mform->addElement('select', 'calendartype', get_string('forcecalendartype', 'calendar'), $calendars);
219         }
221         $options = range(0, 10);
222         $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
223         $courseconfig = get_config('moodlecourse');
224         $mform->setDefault('newsitems', $courseconfig->newsitems);
225         $mform->addHelpButton('newsitems', 'newsitemsnumber');
227         $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
228         $mform->addHelpButton('showgrades', 'showgrades');
229         $mform->setDefault('showgrades', $courseconfig->showgrades);
231         $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
232         $mform->addHelpButton('showreports', 'showreports');
233         $mform->setDefault('showreports', $courseconfig->showreports);
235         // Files and uploads.
236         $mform->addElement('header', 'filehdr', get_string('filesanduploads'));
238         if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) {
239             if (empty($course->legacyfiles)) {
240                 //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet
241                 $choices = array('0'=>get_string('no'), '2'=>get_string('yes'));
242             } else {
243                 $choices = array('1'=>get_string('no'), '2'=>get_string('yes'));
244             }
245             $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices);
246             $mform->addHelpButton('legacyfiles', 'courselegacyfiles');
247             if (!isset($courseconfig->legacyfiles)) {
248                 // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses
249                 $courseconfig->legacyfiles = 0;
250             }
251             $mform->setDefault('legacyfiles', $courseconfig->legacyfiles);
252         }
254         // Handle non-existing $course->maxbytes on course creation.
255         $coursemaxbytes = !isset($course->maxbytes) ? null : $course->maxbytes;
257         // Let's prepare the maxbytes popup.
258         $choices = get_max_upload_sizes($CFG->maxbytes, 0, 0, $coursemaxbytes);
259         $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
260         $mform->addHelpButton('maxbytes', 'maximumupload');
261         $mform->setDefault('maxbytes', $courseconfig->maxbytes);
263         // Completion tracking.
264         if (completion_info::is_enabled_for_site()) {
265             $mform->addElement('header', 'completionhdr', get_string('completion', 'completion'));
266             $mform->addElement('selectyesno', 'enablecompletion', get_string('enablecompletion', 'completion'));
267             $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
268             $mform->addHelpButton('enablecompletion', 'enablecompletion', 'completion');
269         } else {
270             $mform->addElement('hidden', 'enablecompletion');
271             $mform->setType('enablecompletion', PARAM_INT);
272             $mform->setDefault('enablecompletion', 0);
273         }
275         enrol_course_edit_form($mform, $course, $context);
277         $mform->addElement('header','groups', get_string('groupsettingsheader', 'group'));
279         $choices = array();
280         $choices[NOGROUPS] = get_string('groupsnone', 'group');
281         $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
282         $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
283         $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices);
284         $mform->addHelpButton('groupmode', 'groupmode', 'group');
285         $mform->setDefault('groupmode', $courseconfig->groupmode);
287         $mform->addElement('selectyesno', 'groupmodeforce', get_string('groupmodeforce', 'group'));
288         $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group');
289         $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
291         //default groupings selector
292         $options = array();
293         $options[0] = get_string('none');
294         $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
296         if ((empty($course->id) && guess_if_creator_will_have_course_capability('moodle/course:renameroles', $categorycontext))
297                 || (!empty($course->id) && has_capability('moodle/course:renameroles', $coursecontext))) {
298             // Customizable role names in this course.
299             $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
300             $mform->addHelpButton('rolerenaming', 'rolerenaming');
302             if ($roles = get_all_roles()) {
303                 $roles = role_fix_names($roles, null, ROLENAME_ORIGINAL);
304                 $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
305                 foreach ($roles as $role) {
306                     $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->localname));
307                     $mform->setType('role_' . $role->id, PARAM_TEXT);
308                 }
309             }
310         }
312         if (core_tag_tag::is_enabled('core', 'course') &&
313                 ((empty($course->id) && guess_if_creator_will_have_course_capability('moodle/course:tag', $categorycontext))
314                 || (!empty($course->id) && has_capability('moodle/course:tag', $coursecontext)))) {
315             $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
316             $mform->addElement('tags', 'tags', get_string('tags'),
317                     array('itemtype' => 'course', 'component' => 'core'));
318         }
320         // When two elements we need a group.
321         $buttonarray = array();
322         $classarray = array('class' => 'form-submit');
323         if ($returnto !== 0) {
324             $buttonarray[] = &$mform->createElement('submit', 'saveandreturn', get_string('savechangesandreturn'), $classarray);
325         }
326         $buttonarray[] = &$mform->createElement('submit', 'saveanddisplay', get_string('savechangesanddisplay'), $classarray);
327         $buttonarray[] = &$mform->createElement('cancel');
328         $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
329         $mform->closeHeaderBefore('buttonar');
331         $mform->addElement('hidden', 'id', null);
332         $mform->setType('id', PARAM_INT);
334         // Finally set the current form data
335         $this->set_data($course);
336     }
338     /**
339      * Fill in the current page data for this course.
340      */
341     function definition_after_data() {
342         global $DB;
344         $mform = $this->_form;
346         // add available groupings
347         $courseid = $mform->getElementValue('id');
348         if ($courseid and $mform->elementExists('defaultgroupingid')) {
349             $options = array();
350             if ($groupings = $DB->get_records('groupings', array('courseid'=>$courseid))) {
351                 foreach ($groupings as $grouping) {
352                     $options[$grouping->id] = format_string($grouping->name);
353                 }
354             }
355             core_collator::asort($options);
356             $gr_el =& $mform->getElement('defaultgroupingid');
357             $gr_el->load($options);
358         }
360         // add course format options
361         $formatvalue = $mform->getElementValue('format');
362         if (is_array($formatvalue) && !empty($formatvalue)) {
364             $params = array('format' => $formatvalue[0]);
365             // Load the course as well if it is available, course formats may need it to work out
366             // they preferred course end date.
367             if ($courseid) {
368                 $params['id'] = $courseid;
369             }
370             $courseformat = course_get_format((object)$params);
372             $elements = $courseformat->create_edit_form_elements($mform);
373             for ($i = 0; $i < count($elements); $i++) {
374                 $mform->insertElementBefore($mform->removeElement($elements[$i]->getName(), false),
375                         'addcourseformatoptionshere');
376             }
378             // Remove newsitems element if format does not support news.
379             if (!$courseformat->supports_news()) {
380                 $mform->removeElement('newsitems');
381             }
382         }
383     }
385     /**
386      * Validation.
387      *
388      * @param array $data
389      * @param array $files
390      * @return array the errors that were found
391      */
392     function validation($data, $files) {
393         global $DB;
395         $errors = parent::validation($data, $files);
397         // Add field validation check for duplicate shortname.
398         if ($course = $DB->get_record('course', array('shortname' => $data['shortname']), '*', IGNORE_MULTIPLE)) {
399             if (empty($data['id']) || $course->id != $data['id']) {
400                 $errors['shortname'] = get_string('shortnametaken', '', $course->fullname);
401             }
402         }
404         // Add field validation check for duplicate idnumber.
405         if (!empty($data['idnumber']) && (empty($data['id']) || $this->course->idnumber != $data['idnumber'])) {
406             if ($course = $DB->get_record('course', array('idnumber' => $data['idnumber']), '*', IGNORE_MULTIPLE)) {
407                 if (empty($data['id']) || $course->id != $data['id']) {
408                     $errors['idnumber'] = get_string('courseidnumbertaken', 'error', $course->fullname);
409                 }
410             }
411         }
413         if ($errorcode = course_validate_dates($data)) {
414             $errors['enddate'] = get_string($errorcode, 'error');
415         }
417         $errors = array_merge($errors, enrol_course_edit_validation($data, $this->context));
419         $courseformat = course_get_format((object)array('format' => $data['format']));
420         $formaterrors = $courseformat->edit_form_validation($data, $files, $errors);
421         if (!empty($formaterrors) && is_array($formaterrors)) {
422             $errors = array_merge($errors, $formaterrors);
423         }
425         return $errors;
426     }