Merge branch 'MDL-74718-400' of https://github.com/sharidas/moodle into MOODLE_400_STABLE
[moodle.git] / course / moodleform_mod.php
blobcad2bf879e5f368d98e5eebcfe02ff125c59cb31
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Moodleform.
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
25 require_once($CFG->libdir.'/formslib.php');
26 require_once($CFG->libdir.'/completionlib.php');
27 require_once($CFG->libdir.'/gradelib.php');
28 require_once($CFG->libdir.'/plagiarismlib.php');
30 use core\content\export\exporters\component_exporter;
31 use core_grades\component_gradeitems;
33 /**
34 * This class adds extra methods to form wrapper specific to be used for module add / update forms
35 * mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html Moodleform.
37 * @package core_course
38 * @copyright Andrew Nicols <andrew@nicols.co.uk>
40 abstract class moodleform_mod extends moodleform {
41 /** Current data */
42 protected $current;
43 /**
44 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
45 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
46 * update one.
48 * @var mixed
50 protected $_instance;
51 /**
52 * Section of course that module instance will be put in or is in.
53 * This is always the section number itself (column 'section' from 'course_sections' table).
55 * @var int
57 protected $_section;
58 /**
59 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
60 * update one.
62 * @var mixed
64 protected $_cm;
66 /**
67 * Current course.
69 * @var mixed
71 protected $_course;
73 /**
74 * List of modform features
76 protected $_features;
77 /**
78 * @var array Custom completion-rule elements, if enabled
80 protected $_customcompletionelements;
81 /**
82 * @var string name of module.
84 protected $_modname;
85 /** current context, course or module depends if already exists*/
86 protected $context;
88 /** a flag indicating whether outcomes are being used*/
89 protected $_outcomesused;
91 /**
92 * @var bool A flag used to indicate that this module should lock settings
93 * based on admin settings flags in definition_after_data.
95 protected $applyadminlockedflags = false;
97 /** @var object The course format of the current course. */
98 protected $courseformat;
100 /** @var string Whether this is graded or rated. */
101 private $gradedorrated = null;
103 public function __construct($current, $section, $cm, $course) {
104 global $CFG;
106 $this->current = $current;
107 $this->_instance = $current->instance;
108 $this->_section = $section;
109 $this->_cm = $cm;
110 $this->_course = $course;
111 if ($this->_cm) {
112 $this->context = context_module::instance($this->_cm->id);
113 } else {
114 $this->context = context_course::instance($course->id);
117 // Set the course format.
118 require_once($CFG->dirroot . '/course/format/lib.php');
119 $this->courseformat = course_get_format($course);
121 // Guess module name if not set.
122 if (is_null($this->_modname)) {
123 $matches = array();
124 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
125 debugging('Rename form to mod_xx_mod_form, where xx is name of your module');
126 print_error('unknownmodulename');
128 $this->_modname = $matches[1];
130 $this->init_features();
131 parent::__construct('modedit.php');
135 * Old syntax of class constructor. Deprecated in PHP7.
137 * @deprecated since Moodle 3.1
139 public function moodleform_mod($current, $section, $cm, $course) {
140 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
141 self::__construct($current, $section, $cm, $course);
145 * Get the current data for the form.
146 * @return stdClass|null
148 public function get_current() {
149 return $this->current;
153 * Get the DB record for the current instance.
154 * @return stdClass|null
156 public function get_instance() {
157 return $this->_instance;
161 * Get the course section number (relative).
162 * @return int
164 public function get_section() {
165 return $this->_section;
169 * Get the course id.
170 * @return int
172 public function get_course() {
173 return $this->_course;
177 * Get the course module object.
178 * @return stdClass|null
180 public function get_coursemodule() {
181 return $this->_cm;
185 * Return the course context for new modules, or the module context for existing modules.
186 * @return context
188 public function get_context() {
189 return $this->context;
193 * Return the features this module supports.
194 * @return stdClass
196 public function get_features() {
197 return $this->_features;
201 protected function init_features() {
202 global $CFG;
204 $this->_features = new stdClass();
205 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, false);
206 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
207 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
208 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
209 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
210 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
211 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
212 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
213 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
214 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
215 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
216 $this->_features->canrescale = (component_callback_exists('mod_' . $this->_modname, 'rescale_activity_grades') !== false);
220 * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
221 * This method is also called in the bulk activity completion form.
223 * Only available on moodleform_mod.
225 * @param array $default_values passed by reference
227 function data_preprocessing(&$default_values){
228 if (empty($default_values['scale'])) {
229 $default_values['assessed'] = 0;
232 if (empty($default_values['assessed'])){
233 $default_values['ratingtime'] = 0;
234 } else {
235 $default_values['ratingtime']=
236 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
241 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
243 function definition_after_data() {
244 global $CFG, $COURSE;
245 $mform =& $this->_form;
247 if ($id = $mform->getElementValue('update')) {
248 $modulename = $mform->getElementValue('modulename');
249 $instance = $mform->getElementValue('instance');
250 $component = "mod_{$modulename}";
252 if ($this->_features->gradecat) {
253 $hasgradeitems = false;
254 $items = grade_item::fetch_all([
255 'itemtype' => 'mod',
256 'itemmodule' => $modulename,
257 'iteminstance' => $instance,
258 'courseid' => $COURSE->id,
261 $gradecategories = [];
262 $removecategories = [];
263 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
264 if (!empty($items)) {
265 foreach ($items as $item) {
266 if (!empty($item->outcomeid)) {
267 $elname = 'outcome_'.$item->outcomeid;
268 if ($mform->elementExists($elname)) {
269 $mform->hardFreeze($elname); // prevent removing of existing outcomes
271 } else {
272 $hasgradeitems = true;
276 foreach ($items as $item) {
277 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber(
278 $component,
279 $item->itemnumber,
280 'gradecat'
283 if (!isset($gradecategories[$gradecatfieldname])) {
284 $gradecategories[$gradecatfieldname] = $item->categoryid;
285 } else if ($gradecategories[$gradecatfieldname] != $item->categoryid) {
286 $removecategories[$gradecatfieldname] = true;
291 foreach ($removecategories as $toremove) {
292 if ($mform->elementExists($toremove)) {
293 $mform->removeElement($toremove);
299 if ($COURSE->groupmodeforce) {
300 if ($mform->elementExists('groupmode')) {
301 // The groupmode can not be changed if forced from course settings.
302 $mform->hardFreeze('groupmode');
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).
308 if (empty($this->_cm) || !$this->_cm->groupingid) {
309 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
310 $mform->hideIf('groupingid', 'groupmode', 'eq', NOGROUPS);
312 } else if (!$mform->elementExists('groupmode')) {
313 // Groupings have no use without groupmode.
314 if ($mform->elementExists('groupingid')) {
315 $mform->removeElement('groupingid');
317 // Nor does the group restrictions button.
318 if ($mform->elementExists('restrictgroupbutton')) {
319 $mform->removeElement('restrictgroupbutton');
324 // Completion: If necessary, freeze fields
325 $completion = new completion_info($COURSE);
326 if ($completion->is_enabled()) {
327 // If anybody has completed the activity, these options will be 'locked'
328 $completedcount = empty($this->_cm)
330 : $completion->count_user_data($this->_cm);
332 $freeze = false;
333 if (!$completedcount) {
334 if ($mform->elementExists('unlockcompletion')) {
335 $mform->removeElement('unlockcompletion');
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);
341 } else {
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')) {
346 // Yes, add in warning text and set the hidden variable
347 $mform->insertElementBefore(
348 $mform->createElement('static', 'completedunlocked',
349 get_string('completedunlocked', 'completion'),
350 get_string('completedunlockedtext', 'completion')),
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(
358 $mform->createElement('static', 'completedwarning',
359 get_string('completedwarning', 'completion'),
360 get_string('completedwarningtext', 'completion', $completedcount)),
361 'unlockcompletion');
362 $freeze = true;
366 if ($freeze) {
367 $mform->freeze('completion');
368 if ($mform->elementExists('completionview')) {
369 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
371 if ($mform->elementExists('completionusegrade')) {
372 $mform->freeze('completionusegrade');
374 if ($mform->elementExists('completionpassgrade')) {
375 $mform->freeze('completionpassgrade');
377 // Has the completion pass grade completion criteria been set?
378 // If it has then we shouldn't change the gradepass field.
379 if ($mform->exportValue('completionpassgrade')) {
380 $mform->freeze('gradepass');
383 if ($mform->elementExists('completiongradeitemnumber')) {
384 $mform->freeze('completiongradeitemnumber');
386 $mform->freeze($this->_customcompletionelements);
390 // Freeze admin defaults if required (and not different from default)
391 $this->apply_admin_locked_flags();
393 $this->plugin_extend_coursemodule_definition_after_data();
396 // form verification
397 function validation($data, $files) {
398 global $COURSE, $DB, $CFG;
399 $errors = parent::validation($data, $files);
401 $mform =& $this->_form;
403 $errors = array();
405 if ($mform->elementExists('name')) {
406 $name = trim($data['name']);
407 if ($name == '') {
408 $errors['name'] = get_string('required');
412 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
413 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
414 if ($data['coursemodule']) {
415 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
416 } else {
417 $cm = null;
420 if ($mform->elementExists('cmidnumber')) {
421 // verify the idnumber
422 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
423 $errors['cmidnumber'] = get_string('idnumbertaken');
427 $component = "mod_{$this->_modname}";
428 $itemnames = component_gradeitems::get_itemname_mapping_for_component($component);
429 foreach ($itemnames as $itemnumber => $itemname) {
430 $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
431 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
432 $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
433 $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
435 // Ratings: Don't let them select an aggregate type without selecting a scale.
436 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
437 // invalid. If ratings have been selected then the user must select either a scale or max points.
438 // This matches (horrible) logic in data_preprocessing.
439 if (isset($data[$assessedfieldname]) && $data[$assessedfieldname] > 0 && empty($data[$scalefieldname])) {
440 $errors[$assessedfieldname] = get_string('scaleselectionrequired', 'rating');
443 // Check that the grade pass is a valid number.
444 $gradepassvalid = false;
445 if (isset($data[$gradepassfieldname])) {
446 if (unformat_float($data[$gradepassfieldname], true) === false) {
447 $errors[$gradepassfieldname] = get_string('err_numeric', 'form');
448 } else {
449 $gradepassvalid = true;
453 // Grade to pass: ensure that the grade to pass is valid for points and scales.
454 // If we are working with a scale, convert into a positive number for validation.
455 if ($gradepassvalid && isset($data[$gradepassfieldname]) && (!empty($data[$gradefieldname]) || !empty($data[$scalefieldname]))) {
456 $scale = !empty($data[$gradefieldname]) ? $data[$gradefieldname] : $data[$scalefieldname];
457 if ($scale < 0) {
458 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
459 $grade = count(explode(',', $scalevalues->scale));
460 } else {
461 $grade = $scale;
463 if (unformat_float($data[$gradepassfieldname]) > $grade) {
464 $errors[$gradepassfieldname] = get_string('gradepassgreaterthangrade', 'grades', $grade);
468 // We have a grade if there is a non-falsey value for:
469 // - the assessedfieldname for Ratings there; or
470 // - the gradefieldname for Ratings there.
471 if (empty($data[$assessedfieldname]) && empty($data[$gradefieldname])) {
472 // There are no grades set therefore completion is not allowed.
473 if (isset($data['completiongradeitemnumber']) && $data['completiongradeitemnumber'] == (string) $itemnumber) {
474 $errors['completiongradeitemnumber'] = get_string(
475 'badcompletiongradeitemnumber',
476 'completion',
477 get_string("grade_{$itemname}_name", $component)
482 if (isset($data['completionpassgrade']) && $data['completionpassgrade']) {
483 // We need to check whether there's a valid gradepass value.
484 // This can either be in completiongradeitemnumber when there are multiple options OR,
485 // The first grade item if completionusegrade is specified.
486 $validategradepass = false;
487 if (isset($data['completiongradeitemnumber'])) {
488 if ($data['completiongradeitemnumber'] == (string)$itemnumber) {
489 $validategradepass = true;
491 } else if (isset($data['completionusegrade']) && $data['completionusegrade']) {
492 $validategradepass = true;
495 // Confirm gradepass is a valid non-zero value.
496 if ($validategradepass && (!isset($data[$gradepassfieldname]) || grade_floatval($data[$gradepassfieldname]) == 0)) {
497 $errors['completionpassgrade'] = get_string(
498 'activitygradetopassnotset',
499 'completion'
505 // Completion: Don't let them choose automatic completion without turning
506 // on some conditions. Ignore this check when completion settings are
507 // locked, as the options are then disabled.
508 $automaticcompletion = array_key_exists('completion', $data);
509 $automaticcompletion = $automaticcompletion && $data['completion'] == COMPLETION_TRACKING_AUTOMATIC;
510 $automaticcompletion = $automaticcompletion && !empty($data['completionunlocked']);
512 if ($automaticcompletion) {
513 // View to complete.
514 $rulesenabled = !empty($data['completionview']);
516 // Use grade to complete (only one grade item).
517 $rulesenabled = $rulesenabled || !empty($data['completionusegrade']) || !empty($data['completionpassgrade']);
519 // Use grade to complete (specific grade item).
520 if (!$rulesenabled && isset($data['completiongradeitemnumber'])) {
521 $rulesenabled = $data['completiongradeitemnumber'] != '';
524 // Module-specific completion rules.
525 $rulesenabled = $rulesenabled || $this->completion_rule_enabled($data);
527 if (!$rulesenabled) {
528 // No rules are enabled. Can't set automatically completed without rules.
529 $errors['completion'] = get_string('badautocompletion', 'completion');
533 // Availability: Check availability field does not have errors.
534 if (!empty($CFG->enableavailability)) {
535 \core_availability\frontend::report_validation_errors($data, $errors);
538 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
539 if (!empty($pluginerrors)) {
540 $errors = array_merge($errors, $pluginerrors);
543 return $errors;
547 * Extend the validation function from any other plugin.
549 * @param stdClass $data The form data.
550 * @return array $errors The list of errors keyed by element name.
552 protected function plugin_extend_coursemodule_validation($data) {
553 $errors = array();
555 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
556 foreach ($callbacks as $type => $plugins) {
557 foreach ($plugins as $plugin => $pluginfunction) {
558 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
559 $pluginerrors = $pluginfunction($this, $data);
560 if (!empty($pluginerrors)) {
561 $errors = array_merge($errors, $pluginerrors);
565 return $errors;
569 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
570 * form definition (new entry form); this function is used to load in data where values
571 * already exist and data is being edited (edit entry form).
573 * @param mixed $default_values object or array of default values
575 function set_data($default_values) {
576 if (is_object($default_values)) {
577 $default_values = (array)$default_values;
580 $this->data_preprocessing($default_values);
581 parent::set_data($default_values);
585 * Adds all the standard elements to a form to edit the settings for an activity module.
587 protected function standard_coursemodule_elements() {
588 global $COURSE, $CFG, $DB;
589 $mform =& $this->_form;
591 $this->_outcomesused = false;
592 if ($this->_features->outcomes) {
593 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
594 $this->_outcomesused = true;
595 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
596 foreach($outcomes as $outcome) {
597 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
602 if ($this->_features->rating) {
603 $this->add_rating_settings($mform, 0);
606 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
608 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section);
609 $allowstealth = !empty($CFG->allowstealth) && $this->courseformat->allow_stealth_module_visibility($this->_cm, $section);
610 if ($allowstealth && $section->visible) {
611 $modvisiblelabel = 'modvisiblewithstealth';
612 } else if ($section->visible) {
613 $modvisiblelabel = 'modvisible';
614 } else {
615 $modvisiblelabel = 'modvisiblehiddensection';
617 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
618 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible, 'cm' => $this->_cm));
619 $mform->addHelpButton('visible', $modvisiblelabel);
620 if (!empty($this->_cm)) {
621 $context = context_module::instance($this->_cm->id);
622 if (!has_capability('moodle/course:activityvisibility', $context)) {
623 $mform->hardFreeze('visible');
627 if ($this->_features->idnumber) {
628 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
629 $mform->setType('cmidnumber', PARAM_RAW);
630 $mform->addHelpButton('cmidnumber', 'idnumbermod');
633 if ($CFG->downloadcoursecontentallowed) {
634 $choices = [
635 DOWNLOAD_COURSE_CONTENT_DISABLED => get_string('no'),
636 DOWNLOAD_COURSE_CONTENT_ENABLED => get_string('yes'),
638 $mform->addElement('select', 'downloadcontent', get_string('downloadcontent', 'course'), $choices);
639 $downloadcontentdefault = $this->_cm->downloadcontent ?? DOWNLOAD_COURSE_CONTENT_ENABLED;
640 $mform->addHelpButton('downloadcontent', 'downloadcontent', 'course');
641 if (has_capability('moodle/course:configuredownloadcontent', $this->get_context())) {
642 $mform->setDefault('downloadcontent', $downloadcontentdefault);
643 } else {
644 $mform->hardFreeze('downloadcontent');
645 $mform->setConstant('downloadcontent', $downloadcontentdefault);
649 if ($this->_features->groups) {
650 $options = array(NOGROUPS => get_string('groupsnone'),
651 SEPARATEGROUPS => get_string('groupsseparate'),
652 VISIBLEGROUPS => get_string('groupsvisible'));
653 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
654 $mform->addHelpButton('groupmode', 'groupmode', 'group');
657 if ($this->_features->groupings) {
658 // Groupings selector - used to select grouping for groups in activity.
659 $options = array();
660 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
661 foreach ($groupings as $grouping) {
662 $options[$grouping->id] = format_string($grouping->name);
665 core_collator::asort($options);
666 $options = array(0 => get_string('none')) + $options;
667 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
668 $mform->addHelpButton('groupingid', 'grouping', 'group');
671 if (!empty($CFG->enableavailability)) {
672 // Add special button to end of previous section if groups/groupings
673 // are enabled.
675 $availabilityplugins = \core\plugininfo\availability::get_enabled_plugins();
676 $groupavailability = $this->_features->groups && array_key_exists('group', $availabilityplugins);
677 $groupingavailability = $this->_features->groupings && array_key_exists('grouping', $availabilityplugins);
679 if ($groupavailability || $groupingavailability) {
680 // When creating the button, we need to set type=button to prevent it behaving as a submit.
681 $mform->addElement('static', 'restrictgroupbutton', '',
682 html_writer::tag('button', get_string('restrictbygroup', 'availability'), [
683 'id' => 'restrictbygroup',
684 'type' => 'button',
685 'disabled' => 'disabled',
686 'class' => 'btn btn-secondary',
687 'data-groupavailability' => $groupavailability,
688 'data-groupingavailability' => $groupingavailability
693 // Availability field. This is just a textarea; the user interface
694 // interaction is all implemented in JavaScript.
695 $mform->addElement('header', 'availabilityconditionsheader',
696 get_string('restrictaccess', 'availability'));
697 // Note: This field cannot be named 'availability' because that
698 // conflicts with fields in existing modules (such as assign).
699 // So it uses a long name that will not conflict.
700 $mform->addElement('textarea', 'availabilityconditionsjson',
701 get_string('accessrestrictions', 'availability'));
702 // The _cm variable may not be a proper cm_info, so get one from modinfo.
703 if ($this->_cm) {
704 $modinfo = get_fast_modinfo($COURSE);
705 $cm = $modinfo->get_cm($this->_cm->id);
706 } else {
707 $cm = null;
709 \core_availability\frontend::include_all_javascript($COURSE, $cm);
712 // Conditional activities: completion tracking section
713 if(!isset($completion)) {
714 $completion = new completion_info($COURSE);
716 if ($completion->is_enabled()) {
717 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
718 // Unlock button for if people have completed it (will
719 // be removed in definition_after_data if they haven't)
720 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
721 $mform->registerNoSubmitButton('unlockcompletion');
722 $mform->addElement('hidden', 'completionunlocked', 0);
723 $mform->setType('completionunlocked', PARAM_INT);
725 $trackingdefault = COMPLETION_TRACKING_NONE;
726 // If system and activity default is on, set it.
727 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
728 $hasrules = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_HAS_RULES, true);
729 $tracksviews = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, true);
730 if ($hasrules || $tracksviews) {
731 $trackingdefault = COMPLETION_TRACKING_AUTOMATIC;
732 } else {
733 $trackingdefault = COMPLETION_TRACKING_MANUAL;
737 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
738 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
739 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
740 $mform->setDefault('completion', $trackingdefault);
741 $mform->addHelpButton('completion', 'completion', 'completion');
743 // Automatic completion once you view it
744 $gotcompletionoptions = false;
745 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
746 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
747 get_string('completionview_desc', 'completion'));
748 $mform->hideIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
749 // Check by default if automatic completion tracking is set.
750 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC) {
751 $mform->setDefault('completionview', 1);
753 $gotcompletionoptions = true;
756 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
757 // This activity supports grading.
758 $gotcompletionoptions = true;
760 $component = "mod_{$this->_modname}";
761 $itemnames = component_gradeitems::get_itemname_mapping_for_component($component);
763 if (count($itemnames) === 1) {
764 // Only one gradeitem in this activity.
765 // We use the completionusegrade field here.
766 $mform->addElement(
767 'checkbox',
768 'completionusegrade',
769 get_string('completionusegrade', 'completion'),
770 get_string('completionusegrade_desc', 'completion')
772 $mform->hideIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
773 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
775 // Complete if the user has reached the pass grade.
776 $mform->addElement(
777 'checkbox',
778 'completionpassgrade', null,
779 get_string('completionpassgrade_desc', 'completion')
781 $mform->hideIf('completionpassgrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
782 $mform->disabledIf('completionpassgrade', 'completionusegrade', 'notchecked');
783 $mform->addHelpButton('completionpassgrade', 'completionpassgrade', 'completion');
785 // The disabledIf logic differs between ratings and other grade items due to different field types.
786 if ($this->_features->rating) {
787 // If using the rating system, there is no grade unless ratings are enabled.
788 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
789 $mform->disabledIf('completionpassgrade', 'assessed', 'eq', 0);
790 } else {
791 // All other field types use the '$gradefieldname' field's modgrade_type.
792 $itemnumbers = array_keys($itemnames);
793 $itemnumber = array_shift($itemnumbers);
794 $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
795 $mform->disabledIf('completionusegrade', "{$gradefieldname}[modgrade_type]", 'eq', 'none');
796 $mform->disabledIf('completionpassgrade', "{$gradefieldname}[modgrade_type]", 'eq', 'none');
798 } else if (count($itemnames) > 1) {
799 // There are multiple grade items in this activity.
800 // Show them all.
801 $options = [
802 '' => get_string('activitygradenotrequired', 'completion'),
804 foreach ($itemnames as $itemnumber => $itemname) {
805 $options[$itemnumber] = get_string("grade_{$itemname}_name", $component);
808 $mform->addElement(
809 'select',
810 'completiongradeitemnumber',
811 get_string('completionusegrade', 'completion'),
812 $options
814 $mform->hideIf('completiongradeitemnumber', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
816 // Complete if the user has reached the pass grade.
817 $mform->addElement(
818 'checkbox',
819 'completionpassgrade', null,
820 get_string('completionpassgrade_desc', 'completion')
822 $mform->hideIf('completionpassgrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
823 $mform->disabledIf('completionpassgrade', 'completiongradeitemnumber', 'eq', '');
824 $mform->addHelpButton('completionpassgrade', 'completionpassgrade', 'completion');
828 // Automatic completion according to module-specific rules
829 $this->_customcompletionelements = $this->add_completion_rules();
830 foreach ($this->_customcompletionelements as $element) {
831 $mform->hideIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
834 $gotcompletionoptions = $gotcompletionoptions ||
835 count($this->_customcompletionelements)>0;
837 // Automatic option only appears if possible
838 if ($gotcompletionoptions) {
839 $mform->getElement('completion')->addOption(
840 get_string('completion_automatic', 'completion'),
841 COMPLETION_TRACKING_AUTOMATIC);
844 // Completion expected at particular date? (For progress tracking)
845 $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
846 array('optional' => true));
847 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
848 $mform->hideIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
851 // Populate module tags.
852 if (core_tag_tag::is_enabled('core', 'course_modules')) {
853 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
854 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
855 if ($this->_cm) {
856 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
857 $mform->setDefault('tags', $tags);
861 $this->standard_hidden_coursemodule_elements();
863 $this->plugin_extend_coursemodule_standard_elements();
867 * Add rating settings.
869 * @param moodleform_mod $mform
870 * @param int $itemnumber
872 protected function add_rating_settings($mform, int $itemnumber) {
873 global $CFG, $COURSE;
875 if ($this->gradedorrated && $this->gradedorrated !== 'rated') {
876 return;
878 $this->gradedorrated = 'rated';
880 require_once("{$CFG->dirroot}/rating/lib.php");
881 $rm = new rating_manager();
883 $component = "mod_{$this->_modname}";
884 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
885 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
886 $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
887 $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
889 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
891 $isupdate = !empty($this->_cm);
893 $rolenamestring = null;
894 if ($isupdate) {
895 $context = context_module::instance($this->_cm->id);
896 $capabilities = ['moodle/rating:rate', "mod/{$this->_cm->modname}:rate"];
897 $rolenames = get_role_names_with_caps_in_context($context, $capabilities);
898 $rolenamestring = implode(', ', $rolenames);
899 } else {
900 $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
903 $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
904 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
906 $mform->addElement('select', $assessedfieldname, get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
907 $mform->setDefault($assessedfieldname, 0);
908 $mform->addHelpButton($assessedfieldname, 'aggregatetype', 'rating');
910 $gradeoptions = [
911 'isupdate' => $isupdate,
912 'currentgrade' => false,
913 'hasgrades' => false,
914 'canrescale' => false,
915 'useratings' => true,
917 if ($isupdate) {
918 $gradeitem = grade_item::fetch([
919 'itemtype' => 'mod',
920 'itemmodule' => $this->_cm->modname,
921 'iteminstance' => $this->_cm->instance,
922 'itemnumber' => $itemnumber,
923 'courseid' => $COURSE->id,
925 if ($gradeitem) {
926 $gradeoptions['currentgrade'] = $gradeitem->grademax;
927 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
928 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
929 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
933 $mform->addElement('modgrade', $scalefieldname, get_string('scale'), $gradeoptions);
934 $mform->hideIf($scalefieldname, $assessedfieldname, 'eq', 0);
935 $mform->addHelpButton($scalefieldname, 'modgrade', 'grades');
936 $mform->setDefault($scalefieldname, $CFG->gradepointdefault);
938 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
939 $mform->hideIf('ratingtime', $assessedfieldname, 'eq', 0);
941 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
942 $mform->hideIf('assesstimestart', $assessedfieldname, 'eq', 0);
943 $mform->hideIf('assesstimestart', 'ratingtime');
945 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
946 $mform->hideIf('assesstimefinish', $assessedfieldname, 'eq', 0);
947 $mform->hideIf('assesstimefinish', 'ratingtime');
949 if ($this->_features->gradecat) {
950 $mform->addElement(
951 'select',
952 $gradecatfieldname,
953 get_string('gradecategoryonmodform', 'grades'),
954 grade_get_categories_menu($COURSE->id, $this->_outcomesused)
956 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
957 $mform->hideIf($gradecatfieldname, $assessedfieldname, 'eq', 0);
958 $mform->hideIf($gradecatfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
961 // Grade to pass.
962 $mform->addElement('text', $gradepassfieldname, get_string('gradepass', 'grades'));
963 $mform->addHelpButton($gradepassfieldname, 'gradepass', 'grades');
964 $mform->setDefault($gradepassfieldname, '');
965 $mform->setType($gradepassfieldname, PARAM_RAW);
966 $mform->hideIf($gradepassfieldname, $assessedfieldname, 'eq', '0');
967 $mform->hideIf($gradepassfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
971 * Plugins can extend the coursemodule settings form.
973 protected function plugin_extend_coursemodule_standard_elements() {
974 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
975 foreach ($callbacks as $type => $plugins) {
976 foreach ($plugins as $plugin => $pluginfunction) {
977 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
978 // directly.
979 $pluginfunction($this, $this->_form);
985 * Plugins can extend the coursemodule settings form after the data is set.
987 protected function plugin_extend_coursemodule_definition_after_data() {
988 $callbacks = get_plugins_with_function('coursemodule_definition_after_data', 'lib.php');
989 foreach ($callbacks as $type => $plugins) {
990 foreach ($plugins as $plugin => $pluginfunction) {
991 $pluginfunction($this, $this->_form);
997 * Can be overridden to add custom completion rules if the module wishes
998 * them. If overriding this, you should also override completion_rule_enabled.
999 * <p>
1000 * Just add elements to the form as needed and return the list of IDs. The
1001 * system will call disabledIf and handle other behaviour for each returned
1002 * ID.
1003 * @return array Array of string IDs of added items, empty array if none
1005 function add_completion_rules() {
1006 return array();
1010 * Called during validation. Override to indicate, based on the data, whether
1011 * a custom completion rule is enabled (selected).
1013 * @param array $data Input data (not yet validated)
1014 * @return bool True if one or more rules is enabled, false if none are;
1015 * default returns false
1017 function completion_rule_enabled($data) {
1018 return false;
1021 function standard_hidden_coursemodule_elements(){
1022 $mform =& $this->_form;
1023 $mform->addElement('hidden', 'course', 0);
1024 $mform->setType('course', PARAM_INT);
1026 $mform->addElement('hidden', 'coursemodule', 0);
1027 $mform->setType('coursemodule', PARAM_INT);
1029 $mform->addElement('hidden', 'section', 0);
1030 $mform->setType('section', PARAM_INT);
1032 $mform->addElement('hidden', 'module', 0);
1033 $mform->setType('module', PARAM_INT);
1035 $mform->addElement('hidden', 'modulename', '');
1036 $mform->setType('modulename', PARAM_PLUGIN);
1038 $mform->addElement('hidden', 'instance', 0);
1039 $mform->setType('instance', PARAM_INT);
1041 $mform->addElement('hidden', 'add', 0);
1042 $mform->setType('add', PARAM_ALPHANUM);
1044 $mform->addElement('hidden', 'update', 0);
1045 $mform->setType('update', PARAM_INT);
1047 $mform->addElement('hidden', 'return', 0);
1048 $mform->setType('return', PARAM_BOOL);
1050 $mform->addElement('hidden', 'sr', 0);
1051 $mform->setType('sr', PARAM_INT);
1054 public function standard_grading_coursemodule_elements() {
1055 global $COURSE, $CFG;
1057 if ($this->gradedorrated && $this->gradedorrated !== 'graded') {
1058 return;
1060 if ($this->_features->rating) {
1061 return;
1063 $this->gradedorrated = 'graded';
1065 $itemnumber = 0;
1066 $component = "mod_{$this->_modname}";
1067 $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
1068 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
1069 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
1071 $mform =& $this->_form;
1072 $isupdate = !empty($this->_cm);
1073 $gradeoptions = array('isupdate' => $isupdate,
1074 'currentgrade' => false,
1075 'hasgrades' => false,
1076 'canrescale' => $this->_features->canrescale,
1077 'useratings' => $this->_features->rating);
1079 if ($this->_features->hasgrades) {
1080 if ($this->_features->gradecat) {
1081 $mform->addElement('header', 'modstandardgrade', get_string('gradenoun'));
1084 //if supports grades and grades arent being handled via ratings
1085 if ($isupdate) {
1086 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
1087 'itemmodule' => $this->_cm->modname,
1088 'iteminstance' => $this->_cm->instance,
1089 'itemnumber' => 0,
1090 'courseid' => $COURSE->id));
1091 if ($gradeitem) {
1092 $gradeoptions['currentgrade'] = $gradeitem->grademax;
1093 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
1094 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
1095 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
1098 $mform->addElement('modgrade', $gradefieldname, get_string('gradenoun'), $gradeoptions);
1099 $mform->addHelpButton($gradefieldname, 'modgrade', 'grades');
1100 $mform->setDefault($gradefieldname, $CFG->gradepointdefault);
1102 if ($this->_features->advancedgrading
1103 and !empty($this->current->_advancedgradingdata['methods'])
1104 and !empty($this->current->_advancedgradingdata['areas'])) {
1106 if (count($this->current->_advancedgradingdata['areas']) == 1) {
1107 // if there is just one gradable area (most cases), display just the selector
1108 // without its name to make UI simplier
1109 $areadata = reset($this->current->_advancedgradingdata['areas']);
1110 $areaname = key($this->current->_advancedgradingdata['areas']);
1111 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
1112 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
1113 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
1114 $mform->hideIf('advancedgradingmethod_'.$areaname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1116 } else {
1117 // the module defines multiple gradable areas, display a selector
1118 // for each of them together with a name of the area
1119 $areasgroup = array();
1120 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
1121 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
1122 $areadata['title'], $this->current->_advancedgradingdata['methods']);
1123 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
1125 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
1126 array(' ', '<br />'), false);
1130 if ($this->_features->gradecat) {
1131 $mform->addElement('select', $gradecatfieldname,
1132 get_string('gradecategoryonmodform', 'grades'),
1133 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
1134 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
1135 $mform->hideIf($gradecatfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1138 // Grade to pass.
1139 $mform->addElement('text', $gradepassfieldname, get_string($gradepassfieldname, 'grades'));
1140 $mform->addHelpButton($gradepassfieldname, $gradepassfieldname, 'grades');
1141 $mform->setDefault($gradepassfieldname, '');
1142 $mform->setType($gradepassfieldname, PARAM_RAW);
1143 $mform->hideIf($gradepassfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1148 * Add an editor for an activity's introduction field.
1149 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
1150 * @param null $required Override system default for requiremodintro
1151 * @param null $customlabel Override default label for editor
1152 * @throws coding_exception
1154 protected function add_intro_editor($required=null, $customlabel=null) {
1155 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
1156 debugging($str, DEBUG_DEVELOPER);
1158 $this->standard_intro_elements($customlabel);
1163 * Add an editor for an activity's introduction field.
1165 * @param null $customlabel Override default label for editor
1166 * @throws coding_exception
1168 protected function standard_intro_elements($customlabel=null) {
1169 global $CFG;
1171 $required = $CFG->requiremodintro;
1173 $mform = $this->_form;
1174 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
1176 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
1177 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
1178 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
1179 if ($required) {
1180 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
1183 // If the 'show description' feature is enabled, this checkbox appears below the intro.
1184 // We want to hide that when using the singleactivity course format because it is confusing.
1185 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
1186 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
1187 $mform->addHelpButton('showdescription', 'showdescription');
1192 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
1194 * @param bool $cancel show cancel button
1195 * @param string $submitlabel null means default, false means none, string is label text
1196 * @param string $submit2label null means default, false means none, string is label text
1197 * @return void
1199 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
1200 if (is_null($submitlabel)) {
1201 $submitlabel = get_string('savechangesanddisplay');
1204 if (is_null($submit2label)) {
1205 $submit2label = get_string('savechangesandreturntocourse');
1208 $mform = $this->_form;
1210 $mform->addElement('checkbox', 'coursecontentnotification', get_string('coursecontentnotification', 'course'));
1211 $mform->addHelpButton('coursecontentnotification', 'coursecontentnotification', 'course');
1212 $mform->closeHeaderBefore('coursecontentnotification');
1214 // elements in a row need a group
1215 $buttonarray = array();
1217 // Label for the submit button to return to the course.
1218 // Ignore this button in single activity format because it is confusing.
1219 if ($submit2label !== false && $this->courseformat->has_view_page()) {
1220 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
1223 if ($submitlabel !== false) {
1224 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1227 if ($cancel) {
1228 $buttonarray[] = &$mform->createElement('cancel');
1231 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1232 $mform->setType('buttonar', PARAM_RAW);
1236 * Get the list of admin settings for this module and apply any locked settings.
1237 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
1238 * in that function because set_data has not been called yet.
1240 * @return void
1242 protected function apply_admin_locked_flags() {
1243 global $OUTPUT;
1245 if (!$this->applyadminlockedflags) {
1246 return;
1249 $settings = get_config($this->_modname);
1250 $mform = $this->_form;
1251 $lockedicon = html_writer::tag('span',
1252 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1253 array('class' => 'action-icon'));
1254 $isupdate = !empty($this->_cm);
1256 foreach ($settings as $name => $value) {
1257 if (strpos('_', $name) !== false) {
1258 continue;
1260 if ($mform->elementExists($name)) {
1261 $element = $mform->getElement($name);
1262 $lockedsetting = $name . '_locked';
1263 if (!empty($settings->$lockedsetting)) {
1264 // Always lock locked settings for new modules,
1265 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1266 $value = $settings->$name;
1267 if ($isupdate && isset($this->current->$name)) {
1268 $value = $this->current->$name;
1270 if ($value == $settings->$name) {
1271 $mform->setConstant($name, $settings->$name);
1272 $element->setLabel($element->getLabel() . $lockedicon);
1273 // Do not use hardfreeze because we need the hidden input to check dependencies.
1274 $element->freeze();
1282 * Get the list of admin settings for this module and apply any defaults/advanced/locked/required settings.
1284 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1285 * default date/time value should be relative to. If not passed, all
1286 * date/time fields are set relative to the users current midnight.
1287 * @return void
1289 public function apply_admin_defaults($datetimeoffsets = array()) {
1290 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1291 $this->applyadminlockedflags = true;
1293 $settings = get_config($this->_modname);
1294 $mform = $this->_form;
1295 $usermidnight = usergetmidnight(time());
1296 $isupdate = !empty($this->_cm);
1298 foreach ($settings as $name => $value) {
1299 if (strpos('_', $name) !== false) {
1300 continue;
1302 if ($mform->elementExists($name)) {
1303 $element = $mform->getElement($name);
1304 if (!$isupdate) {
1305 if ($element->getType() == 'date_time_selector') {
1306 $enabledsetting = $name . '_enabled';
1307 if (empty($settings->$enabledsetting)) {
1308 $mform->setDefault($name, 0);
1309 } else {
1310 $relativetime = $usermidnight;
1311 if (isset($datetimeoffsets[$name])) {
1312 $relativetime = $datetimeoffsets[$name];
1314 $mform->setDefault($name, $relativetime + $settings->$name);
1316 } else {
1317 $mform->setDefault($name, $settings->$name);
1320 $advancedsetting = $name . '_adv';
1321 if (!empty($settings->$advancedsetting)) {
1322 $mform->setAdvanced($name);
1324 $requiredsetting = $name . '_required';
1325 if (!empty($settings->$requiredsetting)) {
1326 $mform->addRule($name, null, 'required', null, 'client');
1333 * Allows modules to modify the data returned by form get_data().
1334 * This method is also called in the bulk activity completion form.
1336 * Only available on moodleform_mod.
1338 * @param stdClass $data passed by reference
1340 public function data_postprocessing($data) {
1344 * Return submitted data if properly submitted or returns NULL if validation fails or
1345 * if there is no submitted data.
1347 * Do not override this method, override data_postprocessing() instead.
1349 * @return object submitted data; NULL if not valid or not submitted or cancelled
1351 public function get_data() {
1352 $data = parent::get_data();
1353 if ($data) {
1354 // Convert the grade pass value - we may be using a language which uses commas,
1355 // rather than decimal points, in numbers. These need to be converted so that
1356 // they can be added to the DB.
1357 if (isset($data->gradepass)) {
1358 $data->gradepass = unformat_float($data->gradepass);
1361 // Trim name for all activity name.
1362 if (isset($data->name)) {
1363 $data->name = trim($data->name);
1366 $this->data_postprocessing($data);
1368 return $data;