Merge branch 'MDL-40920_master' of https://github.com/markn86/moodle
[moodle.git] / course / editsection_form.php
blob7663e930ab9fc90feff259e180df4b86c9202317
1 <?php
3 if (!defined('MOODLE_INTERNAL')) {
4 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
7 require_once($CFG->libdir.'/formslib.php');
8 require_once($CFG->libdir.'/filelib.php');
9 require_once($CFG->libdir.'/completionlib.php');
10 require_once($CFG->libdir.'/gradelib.php');
12 /**
13 * Default form for editing course section
15 * Course format plugins may specify different editing form to use
17 class editsection_form extends moodleform {
19 function definition() {
21 $mform = $this->_form;
22 $course = $this->_customdata['course'];
24 $mform->addElement('header', 'generalhdr', get_string('general'));
26 $elementgroup = array();
27 $elementgroup[] = $mform->createElement('text', 'name', '', array('size' => '30', 'maxlength' => '255'));
28 $elementgroup[] = $mform->createElement('checkbox', 'usedefaultname', '', get_string('sectionusedefaultname'));
29 $mform->addGroup($elementgroup, 'name_group', get_string('sectionname'), ' ', false);
30 $mform->addGroupRule('name_group', array('name' => array(array(get_string('maximumchars', '', 255), 'maxlength', 255))));
32 $mform->setDefault('usedefaultname', true);
33 $mform->setType('name', PARAM_TEXT);
34 $mform->disabledIf('name','usedefaultname','checked');
36 /// Prepare course and the editor
38 $mform->addElement('editor', 'summary_editor', get_string('summary'), null, $this->_customdata['editoroptions']);
39 $mform->addHelpButton('summary_editor', 'summary');
40 $mform->setType('summary_editor', PARAM_RAW);
42 $mform->addElement('hidden', 'id');
43 $mform->setType('id', PARAM_INT);
45 // additional fields that course format has defined
46 $courseformat = course_get_format($course);
47 $formatoptions = $courseformat->section_format_options(true);
48 if (!empty($formatoptions)) {
49 $elements = $courseformat->create_edit_form_elements($mform, true);
52 $mform->_registerCancelButton('cancel');
55 public function definition_after_data() {
56 global $CFG, $DB;
58 $mform = $this->_form;
59 $course = $this->_customdata['course'];
60 $context = context_course::instance($course->id);
62 if (!empty($CFG->enableavailability)) {
63 $mform->addElement('header', 'availabilityconditions', get_string('availabilityconditions', 'condition'));
64 $mform->setExpanded('availabilityconditions', false);
65 // String used by conditions more than once
66 $strcondnone = get_string('none', 'condition');
67 // Grouping conditions - only if grouping is enabled at site level
68 if (!empty($CFG->enablegroupmembersonly)) {
69 $options = array();
70 $options[0] = get_string('none');
71 if ($groupings = $DB->get_records('groupings', array('courseid' => $course->id))) {
72 foreach ($groupings as $grouping) {
73 $options[$grouping->id] = format_string(
74 $grouping->name, true, array('context' => $context));
77 $mform->addElement('select', 'groupingid', get_string('groupingsection', 'group'), $options);
78 $mform->addHelpButton('groupingid', 'groupingsection', 'group');
81 // Available from/to defaults to midnight because then the display
82 // will be nicer where it tells users when they can access it (it
83 // shows only the date and not time).
84 $date = usergetdate(time());
85 $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
87 // Date and time conditions.
88 $mform->addElement('date_time_selector', 'availablefrom',
89 get_string('availablefrom', 'condition'),
90 array('optional' => true, 'defaulttime' => $midnight));
91 $mform->addElement('date_time_selector', 'availableuntil',
92 get_string('availableuntil', 'condition'),
93 array('optional' => true, 'defaulttime' => $midnight));
95 // Conditions based on grades
96 $gradeoptions = array();
97 $items = grade_item::fetch_all(array('courseid' => $course->id));
98 $items = $items ? $items : array();
99 foreach ($items as $id => $item) {
100 $gradeoptions[$id] = $item->get_name();
102 asort($gradeoptions);
103 $gradeoptions = array(0 => $strcondnone) + $gradeoptions;
105 $grouparray = array();
106 $grouparray[] = $mform->createElement('select', 'conditiongradeitemid', '', $gradeoptions);
107 $grouparray[] = $mform->createElement('static', '', '',
108 ' ' . get_string('grade_atleast', 'condition').' ');
109 $grouparray[] = $mform->createElement('text', 'conditiongrademin', '', array('size' => 3));
110 $grouparray[] = $mform->createElement('static', '', '',
111 '% ' . get_string('grade_upto', 'condition') . ' ');
112 $grouparray[] = $mform->createElement('text', 'conditiongrademax', '', array('size' => 3));
113 $grouparray[] = $mform->createElement('static', '', '', '%');
114 $group = $mform->createElement('group', 'conditiongradegroup',
115 get_string('gradecondition', 'condition'), $grouparray);
117 // Get full version (including condition info) of section object
118 $ci = new condition_info_section($this->_customdata['cs']);
119 $fullcs = $ci->get_full_section();
120 $count = count($fullcs->conditionsgrade) + 1;
122 // Grade conditions
123 $this->repeat_elements(array($group), $count, array(
124 'conditiongradegroup[conditiongrademin]' => array('type' => PARAM_RAW),
125 'conditiongradegroup[conditiongrademax]' => array('type' => PARAM_RAW)
126 ), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true);
127 $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
129 // Conditions based on user fields
130 $operators = condition_info::get_condition_user_field_operators();
131 $useroptions = condition_info::get_condition_user_fields(array('context' => $context));
132 asort($useroptions);
134 $useroptions = array(0 => $strcondnone) + $useroptions;
135 $grouparray = array();
136 $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions);
137 $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators);
138 $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue');
139 $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray);
141 $fieldcount = count($fullcs->conditionsfield) + 1;
143 $this->repeat_elements(array($group), $fieldcount, array(
144 'conditionfieldgroup[conditionfieldvalue]' => array('type' => PARAM_RAW)),
145 'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true);
146 $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition');
148 // Conditions based on completion
149 $completion = new completion_info($course);
150 if ($completion->is_enabled()) {
151 $completionoptions = array();
152 $modinfo = get_fast_modinfo($course);
153 foreach ($modinfo->cms as $id => $cm) {
154 // Add each course-module if it:
155 // (a) has completion turned on
156 // (b) does not belong to current course-section
157 if ($cm->completion && ($fullcs->id != $cm->section)) {
158 $completionoptions[$id] = $cm->name;
161 asort($completionoptions);
162 $completionoptions = array(0 => $strcondnone) +
163 $completionoptions;
165 $completionvalues = array(
166 COMPLETION_COMPLETE => get_string('completion_complete', 'condition'),
167 COMPLETION_INCOMPLETE => get_string('completion_incomplete', 'condition'),
168 COMPLETION_COMPLETE_PASS => get_string('completion_pass', 'condition'),
169 COMPLETION_COMPLETE_FAIL => get_string('completion_fail', 'condition'));
171 $grouparray = array();
172 $grouparray[] = $mform->createElement('select', 'conditionsourcecmid', '',
173 $completionoptions);
174 $grouparray[] = $mform->createElement('select', 'conditionrequiredcompletion', '',
175 $completionvalues);
176 $group = $mform->createElement('group', 'conditioncompletiongroup',
177 get_string('completioncondition', 'condition'), $grouparray);
179 $count = count($fullcs->conditionscompletion) + 1;
180 $this->repeat_elements(array($group), $count, array(),
181 'conditioncompletionrepeats', 'conditioncompletionadds', 2,
182 get_string('addcompletions', 'condition'), true);
183 $mform->addHelpButton('conditioncompletiongroup[0]',
184 'completionconditionsection', 'condition');
187 // Availability conditions - set up form values
188 if (!empty($CFG->enableavailability)) {
189 $num = 0;
190 foreach ($fullcs->conditionsgrade as $gradeitemid => $minmax) {
191 $groupelements = $mform->getElement(
192 'conditiongradegroup[' . $num . ']')->getElements();
193 $groupelements[0]->setValue($gradeitemid);
194 $groupelements[2]->setValue(is_null($minmax->min) ? '' :
195 format_float($minmax->min, 5, true, true));
196 $groupelements[4]->setValue(is_null($minmax->max) ? '' :
197 format_float($minmax->max, 5, true, true));
198 $num++;
201 $num = 0;
202 foreach ($fullcs->conditionsfield as $fieldid => $data) {
203 $groupelements = $mform->getElement(
204 'conditionfieldgroup[' . $num . ']')->getElements();
205 $groupelements[0]->setValue($fieldid);
206 $groupelements[1]->setValue(is_null($data->operator) ? '' :
207 $data->operator);
208 $groupelements[2]->setValue(is_null($data->value) ? '' :
209 $data->value);
210 $num++;
213 if ($completion->is_enabled()) {
214 $num = 0;
215 foreach ($fullcs->conditionscompletion as $othercmid => $state) {
216 $groupelements = $mform->getElement('conditioncompletiongroup[' . $num . ']')->getElements();
217 $groupelements[0]->setValue($othercmid);
218 $groupelements[1]->setValue($state);
219 $num++;
224 // Do we display availability info to students?
225 $showhide = array(
226 CONDITION_STUDENTVIEW_SHOW => get_string('showavailabilitysection_show', 'condition'),
227 CONDITION_STUDENTVIEW_HIDE => get_string('showavailabilitysection_hide', 'condition'));
228 $mform->addElement('select', 'showavailability',
229 get_string('showavailabilitysection', 'condition'), $showhide);
232 $this->add_action_buttons();
235 public function validation($data, $files) {
236 $errors = parent::validation($data, $files);
237 // Conditions: Don't let them set dates which make no sense
238 if (array_key_exists('availablefrom', $data) &&
239 $data['availablefrom'] && $data['availableuntil'] &&
240 $data['availablefrom'] >= $data['availableuntil']) {
241 $errors['availablefrom'] = get_string('badavailabledates', 'condition');
244 // Conditions: Verify that the grade conditions are numbers, and make sense.
245 if (array_key_exists('conditiongradegroup', $data)) {
246 foreach ($data['conditiongradegroup'] as $i => $gradedata) {
247 if ($gradedata['conditiongrademin'] !== '' &&
248 !is_numeric(unformat_float($gradedata['conditiongrademin']))) {
249 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
250 continue;
252 if ($gradedata['conditiongrademax'] !== '' &&
253 !is_numeric(unformat_float($gradedata['conditiongrademax']))) {
254 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
255 continue;
257 if ($gradedata['conditiongrademin'] !== '' && $gradedata['conditiongrademax'] !== '' &&
258 unformat_float($gradedata['conditiongrademax']) <= unformat_float($gradedata['conditiongrademin'])) {
259 $errors["conditiongradegroup[{$i}]"] = get_string('badgradelimits', 'condition');
260 continue;
262 if ($gradedata['conditiongrademin'] === '' && $gradedata['conditiongrademax'] === '' &&
263 $gradedata['conditiongradeitemid']) {
264 $errors["conditiongradegroup[{$i}]"] = get_string('gradeitembutnolimits', 'condition');
265 continue;
267 if (($gradedata['conditiongrademin'] !== '' || $gradedata['conditiongrademax'] !== '') &&
268 !$gradedata['conditiongradeitemid']) {
269 $errors["conditiongradegroup[{$i}]"] = get_string('gradelimitsbutnoitem', 'condition');
270 continue;
275 // Conditions: Verify that the user profile field has not been declared more than once
276 if (array_key_exists('conditionfieldgroup', $data)) {
277 // Array to store the existing fields
278 $arrcurrentfields = array();
279 // Error message displayed if any condition is declared more than once. We use lang string because
280 // this way we don't actually generate the string unless there is an error.
281 $stralreadydeclaredwarning = new lang_string('fielddeclaredmultipletimes', 'condition');
282 foreach ($data['conditionfieldgroup'] as $i => $fielddata) {
283 if ($fielddata['conditionfield'] == 0) { // Don't need to bother if none is selected
284 continue;
286 if (in_array($fielddata['conditionfield'], $arrcurrentfields)) {
287 $errors["conditionfieldgroup[{$i}]"] = $stralreadydeclaredwarning->out();
289 // Add the field to the array
290 $arrcurrentfields[] = $fielddata['conditionfield'];
294 return $errors;
298 * Load in existing data as form defaults
300 * @param stdClass|array $default_values object or array of default values
302 function set_data($default_values) {
303 if (!is_object($default_values)) {
304 // we need object for file_prepare_standard_editor
305 $default_values = (object)$default_values;
307 $editoroptions = $this->_customdata['editoroptions'];
308 $default_values = file_prepare_standard_editor($default_values, 'summary', $editoroptions,
309 $editoroptions['context'], 'course', 'section', $default_values->id);
310 $default_values->usedefaultname = (is_null($default_values->name));
311 parent::set_data($default_values);
315 * Return submitted data if properly submitted or returns NULL if validation fails or
316 * if there is no submitted data.
318 * @return object submitted data; NULL if not valid or not submitted or cancelled
320 function get_data() {
321 $data = parent::get_data();
322 if ($data !== null) {
323 $editoroptions = $this->_customdata['editoroptions'];
324 if (!empty($data->usedefaultname)) {
325 $data->name = null;
327 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions,
328 $editoroptions['context'], 'course', 'section', $data->id);
329 $course = $this->_customdata['course'];
330 foreach (course_get_format($course)->section_format_options() as $option => $unused) {
331 // fix issue with unset checkboxes not being returned at all
332 if (!isset($data->$option)) {
333 $data->$option = null;
337 return $data;