MDL-66079 core_grades: Add support for multiple grade items in an activity
[moodle.git] / course / moodleform_mod.php
CommitLineData
aa6c1ced 1<?php
fcc88fdd
AN
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/>.
16
17/**
18 * Moodleform.
19 *
20 * @package core_course
21 * @copyright Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25require_once($CFG->libdir.'/formslib.php');
516c5eca 26require_once($CFG->libdir.'/completionlib.php');
06cdda46 27require_once($CFG->libdir.'/gradelib.php');
7f53e8aa 28require_once($CFG->libdir.'/plagiarismlib.php');
61fceb86 29
fcc88fdd
AN
30use core_grades\component_gradeitems;
31
e24b7f85 32/**
fcc88fdd
AN
33 * This class adds extra methods to form wrapper specific to be used for module add / update forms
34 * mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html Moodleform.
35 *
36 * @package core_course
37 * @copyright Andrew Nicols <andrew@nicols.co.uk>
e24b7f85 38 */
7b5bd060 39abstract class moodleform_mod extends moodleform {
9a105989 40 /** Current data */
41 protected $current;
e24b7f85 42 /**
43 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
44 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
45 * update one.
46 *
47 * @var mixed
48 */
42f103be 49 protected $_instance;
e24b7f85 50 /**
51 * Section of course that module instance will be put in or is in.
24f41672 52 * This is always the section number itself (column 'section' from 'course_sections' table).
e24b7f85 53 *
8341055e 54 * @var int
e24b7f85 55 */
42f103be 56 protected $_section;
e24b7f85 57 /**
7e85563d 58 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
e24b7f85 59 * update one.
60 *
61 * @var mixed
62 */
42f103be 63 protected $_cm;
8995c270
DW
64
65 /**
66 * Current course.
07fc0ec3 67 *
8995c270
DW
68 * @var mixed
69 */
70 protected $_course;
71
4b86bb08 72 /**
73 * List of modform features
74 */
42f103be 75 protected $_features;
4e781c7b 76 /**
77 * @var array Custom completion-rule elements, if enabled
78 */
42f103be 79 protected $_customcompletionelements;
80 /**
f9a7a98a 81 * @var string name of module.
42f103be 82 */
83 protected $_modname;
09f8d75e 84 /** current context, course or module depends if already exists*/
85 protected $context;
e24b7f85 86
1d50dd13
AD
87 /** a flag indicating whether outcomes are being used*/
88 protected $_outcomesused;
89
fa358a83 90 /**
c3037116
DW
91 * @var bool A flag used to indicate that this module should lock settings
92 * based on admin settings flags in definition_after_data.
fa358a83 93 */
c3037116 94 protected $applyadminlockedflags = false;
fa358a83 95
d9203fb7
FM
96 /** @var object The course format of the current course. */
97 protected $courseformat;
98
fcc88fdd
AN
99 /** @var string Whether this is graded or rated. */
100 private $gradedorrated = null;
101
1a0df553 102 public function __construct($current, $section, $cm, $course) {
d9203fb7
FM
103 global $CFG;
104
9a105989 105 $this->current = $current;
106 $this->_instance = $current->instance;
107 $this->_section = $section;
108 $this->_cm = $cm;
8995c270 109 $this->_course = $course;
09f8d75e 110 if ($this->_cm) {
9a5e297b 111 $this->context = context_module::instance($this->_cm->id);
09f8d75e 112 } else {
9a5e297b 113 $this->context = context_course::instance($course->id);
09f8d75e 114 }
aa6c1ced 115
d9203fb7
FM
116 // Set the course format.
117 require_once($CFG->dirroot . '/course/format/lib.php');
118 $this->courseformat = course_get_format($course);
119
f9a7a98a
TW
120 // Guess module name if not set.
121 if (is_null($this->_modname)) {
122 $matches = array();
123 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
124 debugging('Rename form to mod_xx_mod_form, where xx is name of your module');
125 print_error('unknownmodulename');
126 }
127 $this->_modname = $matches[1];
42f103be 128 }
42f103be 129 $this->init_features();
1a0df553
MG
130 parent::__construct('modedit.php');
131 }
132
133 /**
134 * Old syntax of class constructor. Deprecated in PHP7.
135 *
136 * @deprecated since Moodle 3.1
137 */
138 public function moodleform_mod($current, $section, $cm, $course) {
139 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
140 self::__construct($current, $section, $cm, $course);
e24b7f85 141 }
71ee4471 142
8995c270
DW
143 /**
144 * Get the current data for the form.
145 * @return stdClass|null
146 */
91e54642 147 public function get_current() {
8995c270
DW
148 return $this->current;
149 }
150
151 /**
152 * Get the DB record for the current instance.
153 * @return stdClass|null
154 */
91e54642 155 public function get_instance() {
8995c270
DW
156 return $this->_instance;
157 }
158
159 /**
160 * Get the course section number (relative).
161 * @return int
162 */
91e54642 163 public function get_section() {
8995c270
DW
164 return $this->_section;
165 }
166
167 /**
168 * Get the course id.
169 * @return int
170 */
91e54642 171 public function get_course() {
8995c270
DW
172 return $this->_course;
173 }
174
175 /**
176 * Get the course module object.
177 * @return stdClass|null
178 */
91e54642 179 public function get_coursemodule() {
8995c270
DW
180 return $this->_cm;
181 }
182
183 /**
184 * Return the course context for new modules, or the module context for existing modules.
185 * @return context
186 */
91e54642 187 public function get_context() {
8995c270
DW
188 return $this->context;
189 }
190
191 /**
192 * Return the features this module supports.
193 * @return stdClass
194 */
91e54642 195 public function get_features() {
8995c270
DW
196 return $this->_features;
197 }
198
199
42f103be 200 protected function init_features() {
201 global $CFG;
202
fbaea88f 203 $this->_features = new stdClass();
ea191cf1 204 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, false);
42f103be 205 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
42f103be 206 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
207 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
208 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
dc5c2bd9 209 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
42f103be 210 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
16306628 211 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
8c40662e 212 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
42f103be 213 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
b11f9da6 214 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
d629c601 215 $this->_features->canrescale = (component_callback_exists('mod_' . $this->_modname, 'rescale_activity_grades') !== false);
42f103be 216 }
217
e24b7f85 218 /**
06cdda46
MG
219 * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
220 * This method is also called in the bulk activity completion form.
221 *
a7f7e52f 222 * Only available on moodleform_mod.
e24b7f85 223 *
224 * @param array $default_values passed by reference
225 */
a7f7e52f 226 function data_preprocessing(&$default_values){
a09aeee4
AD
227 if (empty($default_values['scale'])) {
228 $default_values['assessed'] = 0;
229 }
230
231 if (empty($default_values['assessed'])){
a09aeee4
AD
232 $default_values['ratingtime'] = 0;
233 } else {
a09aeee4
AD
234 $default_values['ratingtime']=
235 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
236 }
e24b7f85 237 }
71ee4471 238
4b86bb08 239 /**
240 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
241 */
71ee4471 242 function definition_after_data() {
4b86bb08 243 global $CFG, $COURSE;
71ee4471 244 $mform =& $this->_form;
245
246 if ($id = $mform->getElementValue('update')) {
247 $modulename = $mform->getElementValue('modulename');
248 $instance = $mform->getElementValue('instance');
fcc88fdd 249 $component = "mod_{$modulename}";
71ee4471 250
4b86bb08 251 if ($this->_features->gradecat) {
fc55273e 252 $hasgradeitems = false;
fcc88fdd
AN
253 $items = grade_item::fetch_all([
254 'itemtype' => 'mod',
255 'itemmodule' => $modulename,
256 'iteminstance' => $instance,
257 'courseid' => $COURSE->id,
258 ]);
259
260 $gradecategories = [];
261 $removecategories = [];
16306628
AD
262 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
263 if (!empty($items)) {
4b86bb08 264 foreach ($items as $item) {
265 if (!empty($item->outcomeid)) {
266 $elname = 'outcome_'.$item->outcomeid;
267 if ($mform->elementExists($elname)) {
268 $mform->hardFreeze($elname); // prevent removing of existing outcomes
269 }
fc55273e
MG
270 } else {
271 $hasgradeitems = true;
4b86bb08 272 }
273 }
16306628 274
4b86bb08 275 foreach ($items as $item) {
fcc88fdd
AN
276 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber(
277 $component,
278 $item->itemnumber,
279 'gradecat'
280 );
281
282 if (!isset($gradecategories[$gradecatfieldname])) {
283 $gradecategories[$gradecatfieldname] = $item->categoryid;
284 } else if ($gradecategories[$gradecatfieldname] != $item->categoryid) {
285 $removecategories[$gradecatfieldname] = true;
4b86bb08 286 }
287 }
288 }
289
fcc88fdd
AN
290 foreach ($removecategories as $toremove) {
291 if ($mform->elementExists($toremove)) {
292 $mform->removeElement($toremove);
71ee4471 293 }
294 }
295 }
296 }
24f41672 297
a78890d5 298 if ($COURSE->groupmodeforce) {
299 if ($mform->elementExists('groupmode')) {
fcc88fdd
AN
300 // The groupmode can not be changed if forced from course settings.
301 //
302 $mform->hardFreeze('groupmode');
24f41672 303 }
304 }
a104debf 305
fcc88fdd
AN
306 // Don't disable/remove groupingid if it is currently set to something, otherwise you cannot turn it off at same
307 // time as turning off other option (MDL-30764).
6d02b265 308 if (empty($this->_cm) || !$this->_cm->groupingid) {
4717a5fc 309 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
87c7fb6e 310 $mform->hideIf('groupingid', 'groupmode', 'eq', NOGROUPS);
6d02b265 311
4717a5fc 312 } else if (!$mform->elementExists('groupmode')) {
313 // Groupings have no use without groupmode.
6d02b265 314 if ($mform->elementExists('groupingid')) {
315 $mform->removeElement('groupingid');
316 }
de60737d
JD
317 // Nor does the group restrictions button.
318 if ($mform->elementExists('restrictgroupbutton')) {
319 $mform->removeElement('restrictgroupbutton');
320 }
a104debf 321 }
322 }
4e781c7b 323
324 // Completion: If necessary, freeze fields
61fceb86 325 $completion = new completion_info($COURSE);
326 if ($completion->is_enabled()) {
4e781c7b 327 // If anybody has completed the activity, these options will be 'locked'
328 $completedcount = empty($this->_cm)
329 ? 0
330 : $completion->count_user_data($this->_cm);
331
61fceb86 332 $freeze = false;
333 if (!$completedcount) {
334 if ($mform->elementExists('unlockcompletion')) {
4e781c7b 335 $mform->removeElement('unlockcompletion');
336 }
91d0bb0a
SM
337 // Automatically set to unlocked (note: this is necessary
338 // in order to make it recalculate completion once the option
339 // is changed, maybe someone has completed it now)
340 $mform->getElement('completionunlocked')->setValue(1);
4e781c7b 341 } else {
17109731 342 // Has the element been unlocked, either by the button being pressed
343 // in this request, or the field already being set from a previous one?
344 if ($mform->exportValue('unlockcompletion') ||
345 $mform->exportValue('completionunlocked')) {
4e781c7b 346 // Yes, add in warning text and set the hidden variable
347 $mform->insertElementBefore(
61fceb86 348 $mform->createElement('static', 'completedunlocked',
349 get_string('completedunlocked', 'completion'),
350 get_string('completedunlockedtext', 'completion')),
4e781c7b 351 'unlockcompletion');
352 $mform->removeElement('unlockcompletion');
353 $mform->getElement('completionunlocked')->setValue(1);
354 } else {
355 // No, add in the warning text with the count (now we know
356 // it) before the unlock button
357 $mform->insertElementBefore(
61fceb86 358 $mform->createElement('static', 'completedwarning',
359 get_string('completedwarning', 'completion'),
360 get_string('completedwarningtext', 'completion', $completedcount)),
4e781c7b 361 'unlockcompletion');
61fceb86 362 $freeze = true;
4e781c7b 363 }
aa6c1ced 364 }
4e781c7b 365
61fceb86 366 if ($freeze) {
4e781c7b 367 $mform->freeze('completion');
61fceb86 368 if ($mform->elementExists('completionview')) {
4e781c7b 369 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
370 }
61fceb86 371 if ($mform->elementExists('completionusegrade')) {
4e781c7b 372 $mform->freeze('completionusegrade');
373 }
374 $mform->freeze($this->_customcompletionelements);
aa6c1ced 375 }
4e781c7b 376 }
82bd6a5e 377
fa358a83 378 // Freeze admin defaults if required (and not different from default)
c3037116 379 $this->apply_admin_locked_flags();
71ee4471 380 }
381
60243313 382 // form verification
a78890d5 383 function validation($data, $files) {
400c0fd2 384 global $COURSE, $DB, $CFG;
a78890d5 385 $errors = parent::validation($data, $files);
60243313 386
273eb2f5 387 $mform =& $this->_form;
388
60243313 389 $errors = array();
390
273eb2f5 391 if ($mform->elementExists('name')) {
392 $name = trim($data['name']);
393 if ($name == '') {
394 $errors['name'] = get_string('required');
395 }
e04ff2d5 396 }
397
60243313 398 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
399 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
400 if ($data['coursemodule']) {
32648682 401 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
60243313 402 } else {
403 $cm = null;
404 }
405
273eb2f5 406 if ($mform->elementExists('cmidnumber')) {
407 // verify the idnumber
204175c5 408 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
273eb2f5 409 $errors['cmidnumber'] = get_string('idnumbertaken');
410 }
60243313 411 }
aa6c1ced 412
fcc88fdd
AN
413 $component = "mod_{$this->_modname}";
414 $itemnames = component_gradeitems::get_itemname_mapping_for_component($component);
415 foreach ($itemnames as $itemnumber => $itemname) {
416 $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
417 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
418 $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
419 $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
420
421 // Ratings: Don't let them select an aggregate type without selecting a scale.
422 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
423 // invalid. If ratings have been selected then the user must select either a scale or max points.
424 // This matches (horrible) logic in data_preprocessing.
425 if (isset($data[$assessedfieldname]) && $data[$assessedfieldname] > 0 && empty($data[$scalefieldname])) {
426 $errors[$assessedfieldname] = get_string('scaleselectionrequired', 'rating');
9758da6e 427 }
9758da6e 428
fcc88fdd
AN
429 // Check that the grade pass is a valid number.
430 $gradepassvalid = false;
431 if (isset($data[$gradepassfieldname])) {
432 if (unformat_float($data[$gradepassfieldname], true) === false) {
433 $errors[$gradepassfieldname] = get_string('err_numeric', 'form');
434 } else {
435 $gradepassvalid = true;
436 }
8164fad4 437 }
fcc88fdd
AN
438
439 // Grade to pass: ensure that the grade to pass is valid for points and scales.
440 // If we are working with a scale, convert into a positive number for validation.
441 if ($gradepassvalid && isset($data[$gradepassfieldname]) && (!empty($data[$gradefieldname]) || !empty($data[$scalefieldname]))) {
442 $scale = !empty($data[$gradefieldname]) ? $data[$gradefieldname] : $data[$scalefieldname];
443 if ($scale < 0) {
444 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
445 $grade = count(explode(',', $scalevalues->scale));
446 } else {
447 $grade = $scale;
448 }
449 if (unformat_float($data[$gradepassfieldname]) > $grade) {
450 $errors[$gradepassfieldname] = get_string('gradepassgreaterthangrade', 'grades', $grade);
451 }
8164fad4
GF
452 }
453 }
454
4e781c7b 455 // Completion: Don't let them choose automatic completion without turning
a9f5fc15 456 // on some conditions. Ignore this check when completion settings are
457 // locked, as the options are then disabled.
458 if (array_key_exists('completion', $data) &&
459 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
460 !empty($data['completionunlocked'])) {
61fceb86 461 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
4e781c7b 462 !$this->completion_rule_enabled($data)) {
61fceb86 463 $errors['completion'] = get_string('badautocompletion', 'completion');
4e781c7b 464 }
465 }
60243313 466
400c0fd2 467 // Availability: Check availability field does not have errors.
468 if (!empty($CFG->enableavailability)) {
469 \core_availability\frontend::report_validation_errors($data, $errors);
a6b538a8
MN
470 }
471
8995c270
DW
472 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
473 if (!empty($pluginerrors)) {
474 $errors = array_merge($errors, $pluginerrors);
475 }
476
477 return $errors;
478 }
479
480 /**
481 * Extend the validation function from any other plugin.
482 *
483 * @param stdClass $data The form data.
484 * @return array $errors The list of errors keyed by element name.
485 */
91e54642 486 protected function plugin_extend_coursemodule_validation($data) {
8995c270
DW
487 $errors = array();
488
489 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
490 foreach ($callbacks as $type => $plugins) {
491 foreach ($plugins as $plugin => $pluginfunction) {
492 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
493 $pluginerrors = $pluginfunction($this, $data);
494 if (!empty($pluginerrors)) {
495 $errors = array_merge($errors, $pluginerrors);
496 }
497 }
498 }
a78890d5 499 return $errors;
60243313 500 }
501
e24b7f85 502 /**
503 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
504 * form definition (new entry form); this function is used to load in data where values
505 * already exist and data is being edited (edit entry form).
506 *
507 * @param mixed $default_values object or array of default values
508 */
32db0d42 509 function set_data($default_values) {
e24b7f85 510 if (is_object($default_values)) {
511 $default_values = (array)$default_values;
512 }
82bd6a5e 513
aa6c1ced 514 $this->data_preprocessing($default_values);
82bd6a5e 515 parent::set_data($default_values);
e24b7f85 516 }
71ee4471 517
e24b7f85 518 /**
519 * Adds all the standard elements to a form to edit the settings for an activity module.
e24b7f85 520 */
fcc88fdd 521 protected function standard_coursemodule_elements() {
c18269c7 522 global $COURSE, $CFG, $DB;
e24b7f85 523 $mform =& $this->_form;
f3b783f4 524
1d50dd13 525 $this->_outcomesused = false;
42f103be 526 if ($this->_features->outcomes) {
f3b783f4 527 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
1d50dd13 528 $this->_outcomesused = true;
f3b783f4 529 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
530 foreach($outcomes as $outcome) {
531 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
532 }
533 }
534 }
535
16306628 536 if ($this->_features->rating) {
fcc88fdd 537 $this->add_rating_settings($mform, 0);
a09aeee4
AD
538 }
539
24e25bc1 540 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
207c737d 541
8341055e
MG
542 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section);
543 $allowstealth = !empty($CFG->allowstealth) && $this->courseformat->allow_stealth_module_visibility($this->_cm, $section);
125c4c4c
MG
544 if ($allowstealth && $section->visible) {
545 $modvisiblelabel = 'modvisiblewithstealth';
546 } else if ($section->visible) {
547 $modvisiblelabel = 'modvisible';
548 } else {
549 $modvisiblelabel = 'modvisiblehiddensection';
550 }
551 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
8341055e 552 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible, 'cm' => $this->_cm));
125c4c4c 553 $mform->addHelpButton('visible', $modvisiblelabel);
207c737d
FM
554 if (!empty($this->_cm)) {
555 $context = context_module::instance($this->_cm->id);
556 if (!has_capability('moodle/course:activityvisibility', $context)) {
557 $mform->hardFreeze('visible');
558 }
559 }
560
561 if ($this->_features->idnumber) {
562 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
8af0dffb 563 $mform->setType('cmidnumber', PARAM_RAW);
207c737d
FM
564 $mform->addHelpButton('cmidnumber', 'idnumbermod');
565 }
566
4b86bb08 567 if ($this->_features->groups) {
a78890d5 568 $options = array(NOGROUPS => get_string('groupsnone'),
569 SEPARATEGROUPS => get_string('groupsseparate'),
570 VISIBLEGROUPS => get_string('groupsvisible'));
ddd9f926
DM
571 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
572 $mform->addHelpButton('groupmode', 'groupmode', 'group');
e24b7f85 573 }
24f41672 574
4717a5fc 575 if ($this->_features->groupings) {
576 // Groupings selector - used to select grouping for groups in activity.
98da6021 577 $options = array();
98da6021
PS
578 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
579 foreach ($groupings as $grouping) {
580 $options[$grouping->id] = format_string($grouping->name);
24f41672 581 }
582 }
3ba63534
MG
583 core_collator::asort($options);
584 $options = array(0 => get_string('none')) + $options;
98da6021 585 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
ddd9f926 586 $mform->addHelpButton('groupingid', 'grouping', 'group');
98da6021 587 }
e04ff2d5 588
82bd6a5e 589 if (!empty($CFG->enableavailability)) {
a4c31832 590 // Add special button to end of previous section if groups/groupings
591 // are enabled.
592 if ($this->_features->groups || $this->_features->groupings) {
593 $mform->addElement('static', 'restrictgroupbutton', '',
594 html_writer::tag('button', get_string('restrictbygroup', 'availability'),
29df1cad 595 array('id' => 'restrictbygroup', 'disabled' => 'disabled', 'class' => 'btn btn-secondary')));
a4c31832 596 }
597
400c0fd2 598 // Availability field. This is just a textarea; the user interface
599 // interaction is all implemented in JavaScript.
6282381d 600 $mform->addElement('header', 'availabilityconditionsheader',
400c0fd2 601 get_string('restrictaccess', 'availability'));
602 // Note: This field cannot be named 'availability' because that
603 // conflicts with fields in existing modules (such as assign).
604 // So it uses a long name that will not conflict.
605 $mform->addElement('textarea', 'availabilityconditionsjson',
606 get_string('accessrestrictions', 'availability'));
607 // The _cm variable may not be a proper cm_info, so get one from modinfo.
608 if ($this->_cm) {
42f103be 609 $modinfo = get_fast_modinfo($COURSE);
400c0fd2 610 $cm = $modinfo->get_cm($this->_cm->id);
611 } else {
612 $cm = null;
82bd6a5e 613 }
400c0fd2 614 \core_availability\frontend::include_all_javascript($COURSE, $cm);
82bd6a5e 615 }
616
aa6c1ced 617 // Conditional activities: completion tracking section
82bd6a5e 618 if(!isset($completion)) {
619 $completion = new completion_info($COURSE);
620 }
61fceb86 621 if ($completion->is_enabled()) {
3fbe0e8a 622 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
4e781c7b 623 // Unlock button for if people have completed it (will
624 // be removed in definition_after_data if they haven't)
61fceb86 625 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
4e781c7b 626 $mform->registerNoSubmitButton('unlockcompletion');
61fceb86 627 $mform->addElement('hidden', 'completionunlocked', 0);
d18e0fe6 628 $mform->setType('completionunlocked', PARAM_INT);
82bd6a5e 629
4ed60499
EM
630 $trackingdefault = COMPLETION_TRACKING_NONE;
631 // If system and activity default is on, set it.
632 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
a0a6762e
JP
633 $hasrules = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_HAS_RULES, true);
634 $tracksviews = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, true);
635 if ($hasrules || $tracksviews) {
636 $trackingdefault = COMPLETION_TRACKING_AUTOMATIC;
637 } else {
638 $trackingdefault = COMPLETION_TRACKING_MANUAL;
639 }
4ed60499
EM
640 }
641
aa6c1ced
PS
642 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
643 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
61fceb86 644 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
4ed60499 645 $mform->setDefault('completion', $trackingdefault);
c8dcb793 646 $mform->addHelpButton('completion', 'completion', 'completion');
4e781c7b 647
648 // Automatic completion once you view it
61fceb86 649 $gotcompletionoptions = false;
9593d8b8 650 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
61fceb86 651 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
ddd9f926 652 get_string('completionview_desc', 'completion'));
87c7fb6e 653 $mform->hideIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
a0a6762e
JP
654 // Check by default if automatic completion tracking is set.
655 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC) {
656 $mform->setDefault('completionview', 1);
657 }
61fceb86 658 $gotcompletionoptions = true;
4e781c7b 659 }
660
661 // Automatic completion once it's graded
9593d8b8 662 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
61fceb86 663 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
ddd9f926 664 get_string('completionusegrade_desc', 'completion'));
87c7fb6e 665 $mform->hideIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
af455aa0 666 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
61fceb86 667 $gotcompletionoptions = true;
97c3c2c2 668
669 // If using the rating system, there is no grade unless ratings are enabled.
670 if ($this->_features->rating) {
671 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
672 }
4e781c7b 673 }
674
675 // Automatic completion according to module-specific rules
676 $this->_customcompletionelements = $this->add_completion_rules();
61fceb86 677 foreach ($this->_customcompletionelements as $element) {
87c7fb6e 678 $mform->hideIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
4e781c7b 679 }
680
681 $gotcompletionoptions = $gotcompletionoptions ||
682 count($this->_customcompletionelements)>0;
683
684 // Automatic option only appears if possible
61fceb86 685 if ($gotcompletionoptions) {
4e781c7b 686 $mform->getElement('completion')->addOption(
61fceb86 687 get_string('completion_automatic', 'completion'),
4e781c7b 688 COMPLETION_TRACKING_AUTOMATIC);
aa6c1ced 689 }
4e781c7b 690
691 // Completion expected at particular date? (For progress tracking)
dccd9540
SB
692 $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
693 array('optional' => true));
ddd9f926 694 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
87c7fb6e 695 $mform->hideIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
4e781c7b 696 }
697
dffcf46f 698 // Populate module tags.
dffcf46f
NK
699 if (core_tag_tag::is_enabled('core', 'course_modules')) {
700 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
701 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
702 if ($this->_cm) {
1ea2f7d6 703 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
dffcf46f
NK
704 $mform->setDefault('tags', $tags);
705 }
706 }
707
e24b7f85 708 $this->standard_hidden_coursemodule_elements();
8995c270
DW
709
710 $this->plugin_extend_coursemodule_standard_elements();
711 }
712
fcc88fdd
AN
713 /**
714 * Add rating settings.
715 *
716 * @param moodleform_mod $mform
717 * @param int $itemnumber
718 */
719 protected function add_rating_settings($mform, int $itemnumber) {
720 global $CFG, $COURSE;
721
722 if ($this->gradedorrated && $this->gradedorrated !== 'rated') {
723 return;
724 }
725 $this->gradedorrated = 'rated';
726
727 require_once("{$CFG->dirroot}/rating/lib.php");
728 $rm = new rating_manager();
729
730 $component = "mod_{$this->_modname}";
731 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
732 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
733 $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
734 $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
735
736 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
737
738 $isupdate = !empty($this->_cm);
739
740 $rolenamestring = null;
741 if ($isupdate) {
742 $context = context_module::instance($this->_cm->id);
743 $capabilities = ['moodle/rating:rate', "mod/{$this->_cm->modname}:rate"];
744 $rolenames = get_role_names_with_caps_in_context($context, $capabilities);
745 $rolenamestring = implode(', ', $rolenames);
746 } else {
747 $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
748 }
749
750 $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
751 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
752
753 $mform->addElement('select', $assessedfieldname, get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
754 $mform->setDefault($assessedfieldname, 0);
755 $mform->addHelpButton($assessedfieldname, 'aggregatetype', 'rating');
756
757 $gradeoptions = [
758 'isupdate' => $isupdate,
759 'currentgrade' => false,
760 'hasgrades' => false,
761 'canrescale' => false,
762 'useratings' => true,
763 ];
764 if ($isupdate) {
765 $gradeitem = grade_item::fetch([
766 'itemtype' => 'mod',
767 'itemmodule' => $this->_cm->modname,
768 'iteminstance' => $this->_cm->instance,
769 'itemnumber' => $itemnumber,
770 'courseid' => $COURSE->id,
771 ]);
772 if ($gradeitem) {
773 $gradeoptions['currentgrade'] = $gradeitem->grademax;
774 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
775 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
776 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
777 }
778 }
779
780 $mform->addElement('modgrade', $scalefieldname, get_string('scale'), $gradeoptions);
781 $mform->hideIf($scalefieldname, $assessedfieldname, 'eq', 0);
782 $mform->addHelpButton($scalefieldname, 'modgrade', 'grades');
783 $mform->setDefault($scalefieldname, $CFG->gradepointdefault);
784
785 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
786 $mform->hideIf('ratingtime', $assessedfieldname, 'eq', 0);
787
788 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
789 $mform->hideIf('assesstimestart', $assessedfieldname, 'eq', 0);
790 $mform->hideIf('assesstimestart', 'ratingtime');
791
792 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
793 $mform->hideIf('assesstimefinish', $assessedfieldname, 'eq', 0);
794 $mform->hideIf('assesstimefinish', 'ratingtime');
795
796 if ($this->_features->gradecat) {
797 $mform->addElement(
798 'select',
799 $gradecatfieldname,
800 get_string('gradecategoryonmodform', 'grades'),
801 grade_get_categories_menu($COURSE->id, $this->_outcomesused)
802 );
803 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
804 $mform->hideIf($gradecatfieldname, $assessedfieldname, 'eq', 0);
805 $mform->hideIf($gradecatfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
806 }
807
808 // Grade to pass.
809 $mform->addElement('text', $gradepassfieldname, get_string('gradepass', 'grades'));
810 $mform->addHelpButton($gradepassfieldname, 'gradepass', 'grades');
811 $mform->setDefault($gradepassfieldname, '');
812 $mform->setType($gradepassfieldname, PARAM_RAW);
813 $mform->hideIf($gradepassfieldname, $assessedfieldname, 'eq', '0');
814 $mform->hideIf($gradepassfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
815 }
816
8995c270
DW
817 /**
818 * Plugins can extend the coursemodule settings form.
819 */
91e54642 820 protected function plugin_extend_coursemodule_standard_elements() {
8995c270
DW
821 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
822 foreach ($callbacks as $type => $plugins) {
823 foreach ($plugins as $plugin => $pluginfunction) {
824 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
825 // directly.
826 $pluginfunction($this, $this->_form);
827 }
828 }
e24b7f85 829 }
aa6c1ced 830
4e781c7b 831 /**
832 * Can be overridden to add custom completion rules if the module wishes
833 * them. If overriding this, you should also override completion_rule_enabled.
834 * <p>
835 * Just add elements to the form as needed and return the list of IDs. The
836 * system will call disabledIf and handle other behaviour for each returned
837 * ID.
838 * @return array Array of string IDs of added items, empty array if none
839 */
840 function add_completion_rules() {
841 return array();
842 }
843
844 /**
845 * Called during validation. Override to indicate, based on the data, whether
846 * a custom completion rule is enabled (selected).
847 *
848 * @param array $data Input data (not yet validated)
849 * @return bool True if one or more rules is enabled, false if none are;
850 * default returns false
851 */
54352ac9 852 function completion_rule_enabled($data) {
4e781c7b 853 return false;
854 }
e24b7f85 855
856 function standard_hidden_coursemodule_elements(){
857 $mform =& $this->_form;
858 $mform->addElement('hidden', 'course', 0);
859 $mform->setType('course', PARAM_INT);
860
861 $mform->addElement('hidden', 'coursemodule', 0);
862 $mform->setType('coursemodule', PARAM_INT);
863
864 $mform->addElement('hidden', 'section', 0);
865 $mform->setType('section', PARAM_INT);
866
867 $mform->addElement('hidden', 'module', 0);
868 $mform->setType('module', PARAM_INT);
869
870 $mform->addElement('hidden', 'modulename', '');
aff24313 871 $mform->setType('modulename', PARAM_PLUGIN);
e24b7f85 872
873 $mform->addElement('hidden', 'instance', 0);
874 $mform->setType('instance', PARAM_INT);
875
876 $mform->addElement('hidden', 'add', 0);
877 $mform->setType('add', PARAM_ALPHA);
878
879 $mform->addElement('hidden', 'update', 0);
880 $mform->setType('update', PARAM_INT);
19110c57 881
882 $mform->addElement('hidden', 'return', 0);
883 $mform->setType('return', PARAM_BOOL);
a41b1d96
FM
884
885 $mform->addElement('hidden', 'sr', 0);
886 $mform->setType('sr', PARAM_INT);
e24b7f85 887 }
888
60d5a2e4 889 public function standard_grading_coursemodule_elements() {
16306628 890 global $COURSE, $CFG;
fcc88fdd
AN
891
892 if ($this->gradedorrated && $this->gradedorrated !== 'graded') {
893 return;
894 }
895 if ($this->_features->rating) {
896 return;
897 }
898 $this->gradedorrated = 'graded';
899
900 $itemnumber = 0;
901 $component = "mod_{$this->_modname}";
902 $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
903 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
904 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
905
1d50dd13 906 $mform =& $this->_form;
d629c601
DW
907 $isupdate = !empty($this->_cm);
908 $gradeoptions = array('isupdate' => $isupdate,
909 'currentgrade' => false,
910 'hasgrades' => false,
664d8be7
MN
911 'canrescale' => $this->_features->canrescale,
912 'useratings' => $this->_features->rating);
1d50dd13 913
16306628 914 if ($this->_features->hasgrades) {
fcc88fdd 915 if ($this->_features->gradecat) {
16306628
AD
916 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
917 }
918
919 //if supports grades and grades arent being handled via ratings
fcc88fdd
AN
920 if ($isupdate) {
921 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
922 'itemmodule' => $this->_cm->modname,
923 'iteminstance' => $this->_cm->instance,
924 'itemnumber' => 0,
925 'courseid' => $COURSE->id));
926 if ($gradeitem) {
927 $gradeoptions['currentgrade'] = $gradeitem->grademax;
928 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
929 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
930 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
d629c601 931 }
16306628 932 }
fcc88fdd
AN
933 $mform->addElement('modgrade', $gradefieldname, get_string('grade'), $gradeoptions);
934 $mform->addHelpButton($gradefieldname, 'modgrade', 'grades');
935 $mform->setDefault($gradefieldname, $CFG->gradepointdefault);
1d50dd13 936
b11f9da6
DM
937 if ($this->_features->advancedgrading
938 and !empty($this->current->_advancedgradingdata['methods'])
939 and !empty($this->current->_advancedgradingdata['areas'])) {
940
941 if (count($this->current->_advancedgradingdata['areas']) == 1) {
942 // if there is just one gradable area (most cases), display just the selector
943 // without its name to make UI simplier
944 $areadata = reset($this->current->_advancedgradingdata['areas']);
945 $areaname = key($this->current->_advancedgradingdata['areas']);
946 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
947 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
6832a102 948 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
fcc88fdd 949 $mform->hideIf('advancedgradingmethod_'.$areaname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
b11f9da6
DM
950
951 } else {
952 // the module defines multiple gradable areas, display a selector
953 // for each of them together with a name of the area
954 $areasgroup = array();
955 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
956 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
957 $areadata['title'], $this->current->_advancedgradingdata['methods']);
958 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
959 }
960 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
961 array(' ', '<br />'), false);
962 }
963 }
964
1d50dd13 965 if ($this->_features->gradecat) {
fcc88fdd 966 $mform->addElement('select', $gradecatfieldname,
71c4154a
TH
967 get_string('gradecategoryonmodform', 'grades'),
968 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
fcc88fdd
AN
969 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
970 $mform->hideIf($gradecatfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1d50dd13 971 }
c977b350
MG
972
973 // Grade to pass.
fcc88fdd
AN
974 $mform->addElement('text', $gradepassfieldname, get_string($gradepassfieldname, 'grades'));
975 $mform->addHelpButton($gradepassfieldname, $gradepassfieldname, 'grades');
976 $mform->setDefault($gradepassfieldname, '');
977 $mform->setType($gradepassfieldname, PARAM_RAW);
978 $mform->hideIf($gradepassfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1d50dd13
AD
979 }
980 }
981
6398ff53
AH
982 /**
983 * Add an editor for an activity's introduction field.
984 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
985 * @param null $required Override system default for requiremodintro
986 * @param null $customlabel Override default label for editor
987 * @throws coding_exception
988 */
989 protected function add_intro_editor($required=null, $customlabel=null) {
990 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
991 debugging($str, DEBUG_DEVELOPER);
992
993 $this->standard_intro_elements($customlabel);
994 }
995
996
997 /**
998 * Add an editor for an activity's introduction field.
999 *
1000 * @param null $customlabel Override default label for editor
1001 * @throws coding_exception
1002 */
bc577c54 1003 protected function standard_intro_elements($customlabel=null) {
6398ff53
AH
1004 global $CFG;
1005
1006 $required = $CFG->requiremodintro;
dc5c2bd9 1007
1008 $mform = $this->_form;
1009 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
1010
bc577c54 1011 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
f9beaf44 1012 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
dc5c2bd9 1013 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
1014 if ($required) {
1015 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
1016 }
8c40662e 1017
d9203fb7
FM
1018 // If the 'show description' feature is enabled, this checkbox appears below the intro.
1019 // We want to hide that when using the singleactivity course format because it is confusing.
1020 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
7f53e8aa 1021 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
8c40662e 1022 $mform->addHelpButton('showdescription', 'showdescription');
1023 }
dc5c2bd9 1024 }
1025
6b467109 1026 /**
1027 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
b5ab55dd 1028 *
1029 * @param bool $cancel show cancel button
1030 * @param string $submitlabel null means default, false means none, string is label text
1031 * @param string $submit2label null means default, false means none, string is label text
6b467109 1032 * @return void
b5ab55dd 1033 */
6b467109 1034 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
1035 if (is_null($submitlabel)) {
1036 $submitlabel = get_string('savechangesanddisplay');
1037 }
b5ab55dd 1038
6b467109 1039 if (is_null($submit2label)) {
1040 $submit2label = get_string('savechangesandreturntocourse');
1041 }
b5ab55dd 1042
dc5c2bd9 1043 $mform = $this->_form;
b5ab55dd 1044
1045 // elements in a row need a group
1046 $buttonarray = array();
1047
d9203fb7
FM
1048 // Label for the submit button to return to the course.
1049 // Ignore this button in single activity format because it is confusing.
1050 if ($submit2label !== false && $this->courseformat->has_view_page()) {
b5ab55dd 1051 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
1052 }
1053
1054 if ($submitlabel !== false) {
1055 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1056 }
1057
6b467109 1058 if ($cancel) {
1059 $buttonarray[] = &$mform->createElement('cancel');
1060 }
1061
1062 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
de6f158f 1063 $mform->setType('buttonar', PARAM_RAW);
6b467109 1064 $mform->closeHeaderBefore('buttonar');
1065 }
3c88a678
DW
1066
1067 /**
fa358a83
DW
1068 * Get the list of admin settings for this module and apply any locked settings.
1069 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
1070 * in that function because set_data has not been called yet.
3c88a678 1071 *
3c88a678
DW
1072 * @return void
1073 */
c3037116 1074 protected function apply_admin_locked_flags() {
3c88a678
DW
1075 global $OUTPUT;
1076
c3037116 1077 if (!$this->applyadminlockedflags) {
fa358a83
DW
1078 return;
1079 }
fa358a83 1080
3c88a678
DW
1081 $settings = get_config($this->_modname);
1082 $mform = $this->_form;
1083 $lockedicon = html_writer::tag('span',
1084 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1085 array('class' => 'action-icon'));
54106942 1086 $isupdate = !empty($this->_cm);
3c88a678
DW
1087
1088 foreach ($settings as $name => $value) {
1089 if (strpos('_', $name) !== false) {
1090 continue;
1091 }
1092 if ($mform->elementExists($name)) {
1093 $element = $mform->getElement($name);
3c88a678
DW
1094 $lockedsetting = $name . '_locked';
1095 if (!empty($settings->$lockedsetting)) {
54106942
DW
1096 // Always lock locked settings for new modules,
1097 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1098 $value = $settings->$name;
1099 if ($isupdate && isset($this->current->$name)) {
1100 $value = $this->current->$name;
1101 }
fa358a83
DW
1102 if ($value == $settings->$name) {
1103 $mform->setConstant($name, $settings->$name);
1104 $element->setLabel($element->getLabel() . $lockedicon);
1105 // Do not use hardfreeze because we need the hidden input to check dependencies.
1106 $element->freeze();
1107 }
3c88a678
DW
1108 }
1109 }
1110 }
1111 }
fa358a83
DW
1112
1113 /**
1114 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
1115 *
1116 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1117 * default date/time value should be relative to. If not passed, all
1118 * date/time fields are set relative to the users current midnight.
1119 * @return void
1120 */
1121 public function apply_admin_defaults($datetimeoffsets = array()) {
c3037116
DW
1122 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1123 $this->applyadminlockedflags = true;
1124
1125 $settings = get_config($this->_modname);
1126 $mform = $this->_form;
1127 $usermidnight = usergetmidnight(time());
1128 $isupdate = !empty($this->_cm);
1129
1130 foreach ($settings as $name => $value) {
1131 if (strpos('_', $name) !== false) {
1132 continue;
1133 }
1134 if ($mform->elementExists($name)) {
1135 $element = $mform->getElement($name);
1136 if (!$isupdate) {
1137 if ($element->getType() == 'date_time_selector') {
1138 $enabledsetting = $name . '_enabled';
1139 if (empty($settings->$enabledsetting)) {
1140 $mform->setDefault($name, 0);
1141 } else {
1142 $relativetime = $usermidnight;
1143 if (isset($datetimeoffsets[$name])) {
1144 $relativetime = $datetimeoffsets[$name];
1145 }
1146 $mform->setDefault($name, $relativetime + $settings->$name);
1147 }
1148 } else {
1149 $mform->setDefault($name, $settings->$name);
1150 }
1151 }
1152 $advancedsetting = $name . '_adv';
1153 if (!empty($settings->$advancedsetting)) {
1154 $mform->setAdvanced($name);
1155 }
1156 }
1157 }
fa358a83 1158 }
06cdda46
MG
1159
1160 /**
1161 * Allows modules to modify the data returned by form get_data().
1162 * This method is also called in the bulk activity completion form.
1163 *
1164 * Only available on moodleform_mod.
1165 *
1166 * @param stdClass $data passed by reference
1167 */
273d3106 1168 public function data_postprocessing($data) {
06cdda46
MG
1169 }
1170
1171 /**
1172 * Return submitted data if properly submitted or returns NULL if validation fails or
1173 * if there is no submitted data.
1174 *
1175 * Do not override this method, override data_postprocessing() instead.
1176 *
1177 * @return object submitted data; NULL if not valid or not submitted or cancelled
1178 */
1179 public function get_data() {
1180 $data = parent::get_data();
1181 if ($data) {
1182 // Convert the grade pass value - we may be using a language which uses commas,
1183 // rather than decimal points, in numbers. These need to be converted so that
1184 // they can be added to the DB.
1185 if (isset($data->gradepass)) {
1186 $data->gradepass = unformat_float($data->gradepass);
1187 }
1188
1189 $this->data_postprocessing($data);
1190 }
1191 return $data;
1192 }
e24b7f85 1193}