2 // This file is part of Moodle - http://moodle.org/
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.
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 defined('MOODLE_INTERNAL') ||
die;
19 require_once($CFG->libdir
.'/formslib.php');
20 require_once($CFG->libdir
.'/gradelib.php');
21 require_once($CFG->libdir
.'/plagiarismlib.php');
23 use core_grades\component_gradeitems
;
26 * This class adds extra methods to form wrapper specific to be used for module add / update forms
27 * mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html Moodleform.
29 * @package core_course
30 * @copyright Andrew Nicols <andrew@nicols.co.uk>
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 abstract class moodleform_mod
extends moodleform
{
35 use \core_completion\form\form_trait
;
40 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
41 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
48 * Section of course that module instance will be put in or is in.
49 * This is always the section number itself (column 'section' from 'course_sections' table).
55 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
70 * List of modform features
74 * @var array Custom completion-rule elements, if enabled
76 protected $_customcompletionelements;
78 * @var string name of module.
81 /** current context, course or module depends if already exists*/
84 /** a flag indicating whether outcomes are being used*/
85 protected $_outcomesused;
88 * @var bool A flag used to indicate that this module should lock settings
89 * based on admin settings flags in definition_after_data.
91 protected $applyadminlockedflags = false;
93 /** @var object The course format of the current course. */
94 protected $courseformat;
96 /** @var string Whether this is graded or rated. */
97 private $gradedorrated = null;
99 public function __construct($current, $section, $cm, $course) {
102 $this->current
= $current;
103 $this->_instance
= $current->instance
;
104 $this->_section
= $section;
106 $this->_course
= $course;
108 $this->context
= context_module
::instance($this->_cm
->id
);
110 $this->context
= context_course
::instance($course->id
);
113 // Set the course format.
114 require_once($CFG->dirroot
. '/course/format/lib.php');
115 $this->courseformat
= course_get_format($course);
117 // Guess module name if not set.
118 if (is_null($this->_modname
)) {
120 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
121 debugging('Rename form to mod_xx_mod_form, where xx is name of your module');
122 throw new \
moodle_exception('unknownmodulename');
124 $this->_modname
= $matches[1];
126 $this->init_features();
127 parent
::__construct('modedit.php');
131 * Old syntax of class constructor. Deprecated in PHP7.
133 * @deprecated since Moodle 3.1
135 public function moodleform_mod($current, $section, $cm, $course) {
136 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
137 self
::__construct($current, $section, $cm, $course);
141 * Get the current data for the form.
142 * @return stdClass|null
144 public function get_current() {
145 return $this->current
;
149 * Get the DB record for the current instance.
150 * @return stdClass|null
152 public function get_instance() {
153 return $this->_instance
;
157 * Get the course section number (relative).
160 public function get_section() {
161 return $this->_section
;
168 public function get_course() {
169 return $this->_course
;
173 * Get the course module object.
174 * @return stdClass|null
176 public function get_coursemodule() {
181 * Return the course context for new modules, or the module context for existing modules.
184 public function get_context() {
185 return $this->context
;
189 * Return the features this module supports.
192 public function get_features() {
193 return $this->_features
;
196 protected function init_features() {
199 $this->_features
= new stdClass();
200 $this->_features
->groups
= plugin_supports('mod', $this->_modname
, FEATURE_GROUPS
, false);
201 $this->_features
->groupings
= plugin_supports('mod', $this->_modname
, FEATURE_GROUPINGS
, false);
202 $this->_features
->outcomes
= (!empty($CFG->enableoutcomes
) and plugin_supports('mod', $this->_modname
, FEATURE_GRADE_OUTCOMES
, true));
203 $this->_features
->hasgrades
= plugin_supports('mod', $this->_modname
, FEATURE_GRADE_HAS_GRADE
, false);
204 $this->_features
->idnumber
= plugin_supports('mod', $this->_modname
, FEATURE_IDNUMBER
, true);
205 $this->_features
->introeditor
= plugin_supports('mod', $this->_modname
, FEATURE_MOD_INTRO
, true);
206 $this->_features
->defaultcompletion
= plugin_supports('mod', $this->_modname
, FEATURE_MODEDIT_DEFAULT_COMPLETION
, true);
207 $this->_features
->rating
= plugin_supports('mod', $this->_modname
, FEATURE_RATE
, false);
208 $this->_features
->showdescription
= plugin_supports('mod', $this->_modname
, FEATURE_SHOW_DESCRIPTION
, false);
209 $this->_features
->gradecat
= ($this->_features
->outcomes
or $this->_features
->hasgrades
);
210 $this->_features
->advancedgrading
= plugin_supports('mod', $this->_modname
, FEATURE_ADVANCED_GRADING
, false);
211 $this->_features
->hasnoview
= plugin_supports('mod', $this->_modname
, FEATURE_NO_VIEW_LINK
, false);
212 $this->_features
->canrescale
= (component_callback_exists('mod_' . $this->_modname
, 'rescale_activity_grades') !== false);
216 * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
217 * This method is also called in the bulk activity completion form.
219 * Only available on moodleform_mod.
221 * @param array $default_values passed by reference
223 function data_preprocessing(&$default_values){
224 if (empty($default_values['scale'])) {
225 $default_values['assessed'] = 0;
228 if (empty($default_values['assessed'])){
229 $default_values['ratingtime'] = 0;
231 $default_values['ratingtime']=
232 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ?
1 : 0;
235 // Amend completion settings.
236 if (isset($default_values['completiongradeitemnumber']) &&
237 !is_null($default_values['completiongradeitemnumber'])) {
238 $default_values['receiveagrade'] = 1;
243 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
245 function definition_after_data() {
246 global $CFG, $COURSE;
247 $mform =& $this->_form
;
249 if ($id = $mform->getElementValue('update')) {
250 $modulename = $mform->getElementValue('modulename');
251 $instance = $mform->getElementValue('instance');
252 $component = "mod_{$modulename}";
254 if ($this->_features
->gradecat
) {
255 $hasgradeitems = false;
256 $items = grade_item
::fetch_all([
258 'itemmodule' => $modulename,
259 'iteminstance' => $instance,
260 'courseid' => $COURSE->id
,
263 $gradecategories = [];
264 $removecategories = [];
265 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
266 if (!empty($items)) {
267 foreach ($items as $item) {
268 if (!empty($item->outcomeid
)) {
269 $elname = 'outcome_'.$item->outcomeid
;
270 if ($mform->elementExists($elname)) {
271 $mform->hardFreeze($elname); // prevent removing of existing outcomes
274 $hasgradeitems = true;
278 foreach ($items as $item) {
279 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber(
285 if (!isset($gradecategories[$gradecatfieldname])) {
286 $gradecategories[$gradecatfieldname] = $item->categoryid
;
287 } else if ($gradecategories[$gradecatfieldname] != $item->categoryid
) {
288 $removecategories[$gradecatfieldname] = true;
293 foreach ($removecategories as $toremove) {
294 if ($mform->elementExists($toremove)) {
295 $mform->removeElement($toremove);
301 if ($COURSE->groupmodeforce
) {
302 if ($mform->elementExists('groupmode')) {
303 // The groupmode can not be changed if forced from course settings.
304 $mform->hardFreeze('groupmode');
308 // Don't disable/remove groupingid if it is currently set to something, otherwise you cannot turn it off at same
309 // time as turning off other option (MDL-30764).
310 if (empty($this->_cm
) ||
!$this->_cm
->groupingid
) {
311 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce
)) {
312 $mform->hideIf('groupingid', 'groupmode', 'eq', NOGROUPS
);
314 } else if (!$mform->elementExists('groupmode')) {
315 // Groupings have no use without groupmode.
316 if ($mform->elementExists('groupingid')) {
317 $mform->removeElement('groupingid');
319 // Nor does the group restrictions button.
320 if ($mform->elementExists('restrictgroupbutton')) {
321 $mform->removeElement('restrictgroupbutton');
326 // Completion: If necessary, freeze fields.
329 $cm = get_fast_modinfo($COURSE)->get_cm($this->_cm
->id
);
331 $this->definition_after_data_completion($cm);
333 // Freeze admin defaults if required (and not different from default)
334 $this->apply_admin_locked_flags();
336 $this->plugin_extend_coursemodule_definition_after_data();
340 function validation($data, $files) {
341 global $COURSE, $DB, $CFG;
343 $mform =& $this->_form
;
345 $errors = parent
::validation($data, $files);
347 if ($mform->elementExists('name')) {
348 $name = trim($data['name']);
350 $errors['name'] = get_string('required');
354 $grade_item = grade_item
::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
355 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id
));
356 if ($data['coursemodule']) {
357 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
362 if ($mform->elementExists('cmidnumber')) {
363 // verify the idnumber
364 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id
, $grade_item, $cm)) {
365 $errors['cmidnumber'] = get_string('idnumbertaken');
369 $component = "mod_{$this->_modname}";
370 $itemnames = component_gradeitems
::get_itemname_mapping_for_component($component);
371 foreach ($itemnames as $itemnumber => $itemname) {
372 $gradefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
373 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
374 $assessedfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
375 $scalefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
377 // Ratings: Don't let them select an aggregate type without selecting a scale.
378 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
379 // invalid. If ratings have been selected then the user must select either a scale or max points.
380 // This matches (horrible) logic in data_preprocessing.
381 if (isset($data[$assessedfieldname]) && $data[$assessedfieldname] > 0 && empty($data[$scalefieldname])) {
382 $errors[$assessedfieldname] = get_string('scaleselectionrequired', 'rating');
385 // Check that the grade pass is a valid number.
386 $gradepassvalid = false;
387 if (isset($data[$gradepassfieldname])) {
388 if (unformat_float($data[$gradepassfieldname], true) === false) {
389 $errors[$gradepassfieldname] = get_string('err_numeric', 'form');
391 $gradepassvalid = true;
395 // Grade to pass: ensure that the grade to pass is valid for points and scales.
396 // If we are working with a scale, convert into a positive number for validation.
397 if ($gradepassvalid && isset($data[$gradepassfieldname]) && (!empty($data[$gradefieldname]) ||
!empty($data[$scalefieldname]))) {
398 $scale = !empty($data[$gradefieldname]) ?
$data[$gradefieldname] : $data[$scalefieldname];
400 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
401 $grade = count(explode(',', $scalevalues->scale
));
405 if (unformat_float($data[$gradepassfieldname]) > $grade) {
406 $errors[$gradepassfieldname] = get_string('gradepassgreaterthangrade', 'grades', $grade);
410 // We have a grade if there is a non-falsey value for:
411 // - the assessedfieldname for Ratings there; or
412 // - the gradefieldname for Ratings there.
413 if (empty($data[$assessedfieldname]) && empty($data[$gradefieldname])) {
414 // There are no grades set therefore completion is not allowed.
415 if (isset($data['completiongradeitemnumber']) && $data['completiongradeitemnumber'] == (string) $itemnumber) {
416 $errors['completiongradeitemnumber'] = get_string(
417 'badcompletiongradeitemnumber',
419 get_string("grade_{$itemname}_name", $component)
424 if (isset($data['completionpassgrade']) && $data['completionpassgrade']) {
425 // We need to check whether there's a valid gradepass value.
426 // This can either be in completiongradeitemnumber when there are multiple options OR,
427 // The first grade item if completionusegrade is specified.
428 $validategradepass = false;
429 if (isset($data['completiongradeitemnumber'])) {
430 if ($data['completiongradeitemnumber'] == (string)$itemnumber) {
431 $validategradepass = true;
433 } else if (isset($data['completionusegrade']) && $data['completionusegrade']) {
434 $validategradepass = true;
437 // We need to make all the validations related with $gradepassfieldname
438 // with them being correct floats, keeping the originals unmodified for
439 // later validations / showing the form back...
440 // TODO: Note that once MDL-73994 is fixed we'll have to re-visit this and
441 // adapt the code below to the new values arriving here, without forgetting
442 // the special case of empties and nulls.
443 $gradepass = isset($data[$gradepassfieldname]) ?
unformat_float($data[$gradepassfieldname]) : null;
445 // Confirm gradepass is a valid non-empty (null or zero) value.
446 if ($validategradepass && (is_null($gradepass) ||
$gradepass == 0)) {
447 $errors['completionpassgrade'] = get_string(
448 'activitygradetopassnotset',
455 // Completion: Check completion fields don't have errors.
456 $errors = array_merge($errors, $this->validate_completion($data));
458 // Availability: Check availability field does not have errors.
459 if (!empty($CFG->enableavailability
)) {
460 \core_availability\frontend
::report_validation_errors($data, $errors);
463 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
464 if (!empty($pluginerrors)) {
465 $errors = array_merge($errors, $pluginerrors);
472 * Extend the validation function from any other plugin.
474 * @param stdClass $data The form data.
475 * @return array $errors The list of errors keyed by element name.
477 protected function plugin_extend_coursemodule_validation($data) {
480 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
481 foreach ($callbacks as $type => $plugins) {
482 foreach ($plugins as $plugin => $pluginfunction) {
483 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
484 $pluginerrors = $pluginfunction($this, $data);
485 if (!empty($pluginerrors)) {
486 $errors = array_merge($errors, $pluginerrors);
494 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
495 * form definition (new entry form); this function is used to load in data where values
496 * already exist and data is being edited (edit entry form).
498 * @param mixed $default_values object or array of default values
500 function set_data($default_values) {
501 if (is_object($default_values)) {
502 $default_values = (array)$default_values;
505 $this->data_preprocessing($default_values);
506 parent
::set_data($default_values);
510 * Adds all the standard elements to a form to edit the settings for an activity module.
512 protected function standard_coursemodule_elements() {
513 global $COURSE, $CFG, $DB, $OUTPUT;
514 $mform =& $this->_form
;
516 $this->_outcomesused
= false;
517 if ($this->_features
->outcomes
) {
518 if ($outcomes = grade_outcome
::fetch_all_available($COURSE->id
)) {
519 $this->_outcomesused
= true;
520 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
521 foreach($outcomes as $outcome) {
522 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id
, $outcome->get_name());
527 if ($this->_features
->rating
) {
528 $this->add_rating_settings($mform, 0);
531 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
533 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section
);
535 !empty($CFG->allowstealth
) &&
536 $this->courseformat
->allow_stealth_module_visibility($this->_cm
, $section) &&
537 !$this->_features
->hasnoview
;
538 if ($allowstealth && $section->visible
) {
539 $modvisiblelabel = 'modvisiblewithstealth';
540 } else if ($section->visible
) {
541 $modvisiblelabel = 'modvisible';
543 $modvisiblelabel = 'modvisiblehiddensection';
545 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
546 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible
, 'cm' => $this->_cm
));
547 $mform->addHelpButton('visible', $modvisiblelabel);
548 if (!empty($this->_cm
) && !has_capability('moodle/course:activityvisibility', $this->get_context())) {
549 $mform->hardFreeze('visible');
552 if ($this->_features
->idnumber
) {
553 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
554 $mform->setType('cmidnumber', PARAM_RAW
);
555 $mform->addHelpButton('cmidnumber', 'idnumbermod');
558 if (has_capability('moodle/course:setforcedlanguage', $this->get_context())) {
559 $languages = ['' => get_string('forceno')];
560 $languages +
= get_string_manager()->get_list_of_translations();
562 $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
565 if ($CFG->downloadcoursecontentallowed
) {
567 DOWNLOAD_COURSE_CONTENT_DISABLED
=> get_string('no'),
568 DOWNLOAD_COURSE_CONTENT_ENABLED
=> get_string('yes'),
570 $mform->addElement('select', 'downloadcontent', get_string('downloadcontent', 'course'), $choices);
571 $downloadcontentdefault = $this->_cm
->downloadcontent ?? DOWNLOAD_COURSE_CONTENT_ENABLED
;
572 $mform->addHelpButton('downloadcontent', 'downloadcontent', 'course');
573 if (has_capability('moodle/course:configuredownloadcontent', $this->get_context())) {
574 $mform->setDefault('downloadcontent', $downloadcontentdefault);
576 $mform->hardFreeze('downloadcontent');
577 $mform->setConstant('downloadcontent', $downloadcontentdefault);
581 if ($this->_features
->groups
) {
582 $options = array(NOGROUPS
=> get_string('groupsnone'),
583 SEPARATEGROUPS
=> get_string('groupsseparate'),
584 VISIBLEGROUPS
=> get_string('groupsvisible'));
585 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS
);
586 $mform->addHelpButton('groupmode', 'groupmode', 'group');
589 if ($this->_features
->groupings
) {
590 // Groupings selector - used to select grouping for groups in activity.
592 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id
))) {
593 foreach ($groupings as $grouping) {
594 $options[$grouping->id
] = format_string($grouping->name
);
597 core_collator
::asort($options);
598 $options = array(0 => get_string('none')) +
$options;
599 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
600 $mform->addHelpButton('groupingid', 'grouping', 'group');
603 if (!empty($CFG->enableavailability
)) {
604 // Add special button to end of previous section if groups/groupings
607 $availabilityplugins = \core\plugininfo\availability
::get_enabled_plugins();
608 $groupavailability = $this->_features
->groups
&& array_key_exists('group', $availabilityplugins);
609 $groupingavailability = $this->_features
->groupings
&& array_key_exists('grouping', $availabilityplugins);
611 if ($groupavailability ||
$groupingavailability) {
612 // When creating the button, we need to set type=button to prevent it behaving as a submit.
613 $mform->addElement('static', 'restrictgroupbutton', '',
614 html_writer
::tag('button', get_string('restrictbygroup', 'availability'), [
615 'id' => 'restrictbygroup',
617 'disabled' => 'disabled',
618 'class' => 'btn btn-secondary',
619 'data-groupavailability' => $groupavailability,
620 'data-groupingavailability' => $groupingavailability
625 // Availability field. This is just a textarea; the user interface
626 // interaction is all implemented in JavaScript.
627 $mform->addElement('header', 'availabilityconditionsheader',
628 get_string('restrictaccess', 'availability'));
629 // Note: This field cannot be named 'availability' because that
630 // conflicts with fields in existing modules (such as assign).
631 // So it uses a long name that will not conflict.
632 $mform->addElement('textarea', 'availabilityconditionsjson',
633 get_string('accessrestrictions', 'availability'),
634 ['class' => 'd-none']
636 // Availability loading indicator.
637 $loadingcontainer = $OUTPUT->container(
638 $OUTPUT->render_from_template('core/loading', []),
639 'd-flex justify-content-center py-5 icon-size-5',
640 'availabilityconditions-loading'
642 $mform->addElement('html', $loadingcontainer);
644 // The _cm variable may not be a proper cm_info, so get one from modinfo.
646 $modinfo = get_fast_modinfo($COURSE);
647 $cm = $modinfo->get_cm($this->_cm
->id
);
651 \core_availability\frontend
::include_all_javascript($COURSE, $cm);
654 // Conditional activities: completion tracking section
655 if(!isset($completion)) {
656 $completion = new completion_info($COURSE);
659 // Add the completion tracking elements to the form.
660 if ($completion->is_enabled()) {
661 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
662 $this->add_completion_elements(null, false, false, false, $this->_course
->id
);
665 // Populate module tags.
666 if (core_tag_tag
::is_enabled('core', 'course_modules')) {
667 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
668 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
670 $tags = core_tag_tag
::get_item_tags_array('core', 'course_modules', $this->_cm
->id
);
671 $mform->setDefault('tags', $tags);
675 $this->standard_hidden_coursemodule_elements();
677 $this->plugin_extend_coursemodule_standard_elements();
681 * Add rating settings.
683 * @param moodleform_mod $mform
684 * @param int $itemnumber
686 protected function add_rating_settings($mform, int $itemnumber) {
687 global $CFG, $COURSE;
689 if ($this->gradedorrated
&& $this->gradedorrated
!== 'rated') {
692 $this->gradedorrated
= 'rated';
694 require_once("{$CFG->dirroot}/rating/lib.php");
695 $rm = new rating_manager();
697 $component = "mod_{$this->_modname}";
698 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
699 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
700 $assessedfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
701 $scalefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
703 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
705 $isupdate = !empty($this->_cm
);
707 $rolenamestring = null;
709 $capabilities = ['moodle/rating:rate', "mod/{$this->_cm->modname}:rate"];
710 $rolenames = get_role_names_with_caps_in_context($this->get_context(), $capabilities);
711 $rolenamestring = implode(', ', $rolenames);
713 $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
716 $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
717 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
719 $mform->addElement('select', $assessedfieldname, get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
720 $mform->setDefault($assessedfieldname, 0);
721 $mform->addHelpButton($assessedfieldname, 'aggregatetype', 'rating');
724 'isupdate' => $isupdate,
725 'currentgrade' => false,
726 'hasgrades' => false,
727 'canrescale' => false,
728 'useratings' => true,
731 $gradeitem = grade_item
::fetch([
733 'itemmodule' => $this->_cm
->modname
,
734 'iteminstance' => $this->_cm
->instance
,
735 'itemnumber' => $itemnumber,
736 'courseid' => $COURSE->id
,
739 $gradeoptions['currentgrade'] = $gradeitem->grademax
;
740 $gradeoptions['currentgradetype'] = $gradeitem->gradetype
;
741 $gradeoptions['currentscaleid'] = $gradeitem->scaleid
;
742 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
746 $mform->addElement('modgrade', $scalefieldname, get_string('scale'), $gradeoptions);
747 $mform->hideIf($scalefieldname, $assessedfieldname, 'eq', 0);
748 $mform->addHelpButton($scalefieldname, 'modgrade', 'grades');
749 $mform->setDefault($scalefieldname, $CFG->gradepointdefault
);
751 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
752 $mform->hideIf('ratingtime', $assessedfieldname, 'eq', 0);
754 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
755 $mform->hideIf('assesstimestart', $assessedfieldname, 'eq', 0);
756 $mform->hideIf('assesstimestart', 'ratingtime');
758 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
759 $mform->hideIf('assesstimefinish', $assessedfieldname, 'eq', 0);
760 $mform->hideIf('assesstimefinish', 'ratingtime');
762 if ($this->_features
->gradecat
) {
766 get_string('gradecategoryonmodform', 'grades'),
767 grade_get_categories_menu($COURSE->id
, $this->_outcomesused
)
769 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
770 $mform->hideIf($gradecatfieldname, $assessedfieldname, 'eq', 0);
771 $mform->hideIf($gradecatfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
775 $mform->addElement('float', $gradepassfieldname, get_string('gradepass', 'grades'));
776 $mform->addHelpButton($gradepassfieldname, 'gradepass', 'grades');
777 $mform->setDefault($gradepassfieldname, '');
778 $mform->hideIf($gradepassfieldname, $assessedfieldname, 'eq', '0');
779 $mform->hideIf($gradepassfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
783 * Plugins can extend the coursemodule settings form.
785 protected function plugin_extend_coursemodule_standard_elements() {
786 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
787 foreach ($callbacks as $type => $plugins) {
788 foreach ($plugins as $plugin => $pluginfunction) {
789 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
791 $pluginfunction($this, $this->_form
);
797 * Plugins can extend the coursemodule settings form after the data is set.
799 protected function plugin_extend_coursemodule_definition_after_data() {
800 $callbacks = get_plugins_with_function('coursemodule_definition_after_data', 'lib.php');
801 foreach ($callbacks as $type => $plugins) {
802 foreach ($plugins as $plugin => $pluginfunction) {
803 $pluginfunction($this, $this->_form
);
809 * Can be overridden to add custom completion rules if the module wishes
810 * them. If overriding this, you should also override completion_rule_enabled.
812 * Just add elements to the form as needed and return the list of IDs. The
813 * system will call disabledIf and handle other behaviour for each returned
815 * @return array Array of string IDs of added items, empty array if none
817 function add_completion_rules() {
822 * Called during validation. Override to indicate, based on the data, whether
823 * a custom completion rule is enabled (selected).
825 * @param array $data Input data (not yet validated)
826 * @return bool True if one or more rules is enabled, false if none are;
827 * default returns false
829 function completion_rule_enabled($data) {
834 * Add completion grading elements to the form and return the list of element ids.
836 * @return array Array of string IDs of added items, empty array if none
838 public function add_completiongrade_rules(): array {
842 function standard_hidden_coursemodule_elements(){
843 $mform =& $this->_form
;
844 $mform->addElement('hidden', 'course', 0);
845 $mform->setType('course', PARAM_INT
);
847 $mform->addElement('hidden', 'coursemodule', 0);
848 $mform->setType('coursemodule', PARAM_INT
);
850 $mform->addElement('hidden', 'section', 0);
851 $mform->setType('section', PARAM_INT
);
853 $mform->addElement('hidden', 'module', 0);
854 $mform->setType('module', PARAM_INT
);
856 $mform->addElement('hidden', 'modulename', '');
857 $mform->setType('modulename', PARAM_PLUGIN
);
859 $mform->addElement('hidden', 'instance', 0);
860 $mform->setType('instance', PARAM_INT
);
862 $mform->addElement('hidden', 'add', 0);
863 $mform->setType('add', PARAM_ALPHANUM
);
865 $mform->addElement('hidden', 'update', 0);
866 $mform->setType('update', PARAM_INT
);
868 $mform->addElement('hidden', 'return', 0);
869 $mform->setType('return', PARAM_BOOL
);
871 // The section number where to return: -1 means no section (0 can't be used because it is a valid section number and
872 // null can't be used because it's converted to 0).
873 $mform->addElement('hidden', 'sr', -1);
874 $mform->setType('sr', PARAM_INT
);
876 $mform->addElement('hidden', 'beforemod', 0);
877 $mform->setType('beforemod', PARAM_INT
);
879 $mform->addElement('hidden', 'showonly', '');
880 $mform->setType('showonly', PARAM_ALPHANUMEXT
);
883 public function standard_grading_coursemodule_elements() {
884 global $COURSE, $CFG;
886 if ($this->gradedorrated
&& $this->gradedorrated
!== 'graded') {
889 if ($this->_features
->rating
) {
892 $this->gradedorrated
= 'graded';
895 $component = "mod_{$this->_modname}";
896 $gradefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
897 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
898 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
900 $mform =& $this->_form
;
901 $isupdate = !empty($this->_cm
);
902 $gradeoptions = array('isupdate' => $isupdate,
903 'currentgrade' => false,
904 'hasgrades' => false,
905 'canrescale' => $this->_features
->canrescale
,
906 'useratings' => $this->_features
->rating
);
908 if ($this->_features
->hasgrades
) {
909 if ($this->_features
->gradecat
) {
910 $mform->addElement('header', 'modstandardgrade', get_string('gradenoun'));
913 //if supports grades and grades arent being handled via ratings
915 $gradeitem = grade_item
::fetch(array('itemtype' => 'mod',
916 'itemmodule' => $this->_cm
->modname
,
917 'iteminstance' => $this->_cm
->instance
,
919 'courseid' => $COURSE->id
));
921 $gradeoptions['currentgrade'] = $gradeitem->grademax
;
922 $gradeoptions['currentgradetype'] = $gradeitem->gradetype
;
923 $gradeoptions['currentscaleid'] = $gradeitem->scaleid
;
924 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
927 $mform->addElement('modgrade', $gradefieldname, get_string('gradenoun'), $gradeoptions);
928 $mform->addHelpButton($gradefieldname, 'modgrade', 'grades');
929 $mform->setDefault($gradefieldname, $CFG->gradepointdefault
);
931 if ($this->_features
->advancedgrading
932 and !empty($this->current
->_advancedgradingdata
['methods'])
933 and !empty($this->current
->_advancedgradingdata
['areas'])) {
935 if (count($this->current
->_advancedgradingdata
['areas']) == 1) {
936 // if there is just one gradable area (most cases), display just the selector
937 // without its name to make UI simplier
938 $areadata = reset($this->current
->_advancedgradingdata
['areas']);
939 $areaname = key($this->current
->_advancedgradingdata
['areas']);
940 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
941 get_string('gradingmethod', 'core_grading'), $this->current
->_advancedgradingdata
['methods']);
942 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
943 $mform->hideIf('advancedgradingmethod_'.$areaname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
946 // the module defines multiple gradable areas, display a selector
947 // for each of them together with a name of the area
948 $areasgroup = array();
949 foreach ($this->current
->_advancedgradingdata
['areas'] as $areaname => $areadata) {
950 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
951 $areadata['title'], $this->current
->_advancedgradingdata
['methods']);
952 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
954 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
955 array(' ', '<br />'), false);
959 if ($this->_features
->gradecat
) {
960 $mform->addElement('select', $gradecatfieldname,
961 get_string('gradecategoryonmodform', 'grades'),
962 grade_get_categories_menu($COURSE->id
, $this->_outcomesused
));
963 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
964 $mform->hideIf($gradecatfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
968 $mform->addElement('float', $gradepassfieldname, get_string($gradepassfieldname, 'grades'));
969 $mform->addHelpButton($gradepassfieldname, $gradepassfieldname, 'grades');
970 $mform->setDefault($gradepassfieldname, '');
971 $mform->hideIf($gradepassfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
976 * Add an editor for an activity's introduction field.
977 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
978 * @param null $required Override system default for requiremodintro
979 * @param null $customlabel Override default label for editor
980 * @throws coding_exception
982 protected function add_intro_editor($required=null, $customlabel=null) {
983 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
984 debugging($str, DEBUG_DEVELOPER
);
986 $this->standard_intro_elements($customlabel);
991 * Add an editor for an activity's introduction field.
993 * @param null $customlabel Override default label for editor
994 * @throws coding_exception
996 protected function standard_intro_elements($customlabel=null) {
999 $required = $CFG->requiremodintro
;
1001 $mform = $this->_form
;
1002 $label = is_null($customlabel) ?
get_string('moduleintro') : $customlabel;
1004 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES
,
1005 'noclean' => true, 'context' => $this->context
, 'subdirs' => true));
1006 $mform->setType('introeditor', PARAM_RAW
); // no XSS prevention here, users must be trusted
1008 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
1011 // If the 'show description' feature is enabled, this checkbox appears below the intro.
1012 // We want to hide that when using the singleactivity course format because it is confusing.
1013 if ($this->_features
->showdescription
&& $this->courseformat
->has_view_page()) {
1014 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
1015 $mform->addHelpButton('showdescription', 'showdescription');
1020 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
1022 * @param bool $cancel show cancel button
1023 * @param string $submitlabel null means default, false means none, string is label text
1024 * @param string $submit2label null means default, false means none, string is label text
1027 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
1028 if (is_null($submitlabel)) {
1029 $submitlabel = get_string('savechangesanddisplay');
1032 if (is_null($submit2label)) {
1033 $submit2label = get_string('savechangesandreturntocourse');
1036 $mform = $this->_form
;
1038 $mform->addElement('checkbox', 'coursecontentnotification', get_string('coursecontentnotification', 'course'));
1039 $mform->addHelpButton('coursecontentnotification', 'coursecontentnotification', 'course');
1040 $mform->closeHeaderBefore('coursecontentnotification');
1042 // elements in a row need a group
1043 $buttonarray = array();
1045 // Label for the submit button to return to the course.
1046 // Ignore this button in single activity format because it is confusing.
1047 if ($submit2label !== false && $this->courseformat
->has_view_page()) {
1048 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
1051 if ($submitlabel !== false) {
1052 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1056 $buttonarray[] = &$mform->createElement('cancel');
1059 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1060 $mform->setType('buttonar', PARAM_RAW
);
1064 * Get the list of admin settings for this module and apply any locked settings.
1065 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
1066 * in that function because set_data has not been called yet.
1070 protected function apply_admin_locked_flags() {
1073 if (!$this->applyadminlockedflags
) {
1077 $settings = get_config($this->_modname
);
1078 $mform = $this->_form
;
1079 $lockedicon = html_writer
::tag('span',
1080 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1081 array('class' => 'action-icon'));
1082 $isupdate = !empty($this->_cm
);
1084 foreach ($settings as $name => $value) {
1085 if (strpos('_', $name) !== false) {
1088 if ($mform->elementExists($name)) {
1089 $element = $mform->getElement($name);
1090 $lockedsetting = $name . '_locked';
1091 if (!empty($settings->$lockedsetting)) {
1092 // Always lock locked settings for new modules,
1093 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1094 $value = $settings->$name;
1095 if ($isupdate && isset($this->current
->$name)) {
1096 $value = $this->current
->$name;
1098 if ($value == $settings->$name) {
1099 $mform->setConstant($name, $settings->$name);
1100 $element->setLabel($element->getLabel() . $lockedicon);
1101 // Do not use hardfreeze because we need the hidden input to check dependencies.
1110 * Get the list of admin settings for this module and apply any defaults/advanced/locked/required settings.
1112 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1113 * default date/time value should be relative to. If not passed, all
1114 * date/time fields are set relative to the users current midnight.
1117 public function apply_admin_defaults($datetimeoffsets = array()) {
1118 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1119 $this->applyadminlockedflags
= true;
1121 $settings = get_config($this->_modname
);
1122 $mform = $this->_form
;
1123 $usermidnight = usergetmidnight(time());
1124 $isupdate = !empty($this->_cm
);
1126 foreach ($settings as $name => $value) {
1127 if (strpos('_', $name) !== false) {
1130 if ($mform->elementExists($name)) {
1131 $element = $mform->getElement($name);
1133 if ($element->getType() == 'date_time_selector') {
1134 $enabledsetting = $name . '_enabled';
1135 if (empty($settings->$enabledsetting)) {
1136 $mform->setDefault($name, 0);
1138 $relativetime = $usermidnight;
1139 if (isset($datetimeoffsets[$name])) {
1140 $relativetime = $datetimeoffsets[$name];
1142 $mform->setDefault($name, $relativetime +
$settings->$name);
1145 $mform->setDefault($name, $settings->$name);
1148 $advancedsetting = $name . '_adv';
1149 if (!empty($settings->$advancedsetting)) {
1150 $mform->setAdvanced($name);
1152 $requiredsetting = $name . '_required';
1153 if (!empty($settings->$requiredsetting)) {
1154 $mform->addRule($name, null, 'required', null, 'client');
1161 * Allows modules to modify the data returned by form get_data().
1162 * This method is also called in the bulk activity completion form.
1164 * Only available on moodleform_mod.
1166 * @param stdClass $data passed by reference
1168 public function data_postprocessing($data) {
1172 * Return submitted data if properly submitted or returns NULL if validation fails or
1173 * if there is no submitted data.
1175 * Do not override this method, override data_postprocessing() instead.
1177 * @return object submitted data; NULL if not valid or not submitted or cancelled
1179 public function get_data() {
1180 $data = parent
::get_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
);
1189 // Trim name for all activity name.
1190 if (isset($data->name
)) {
1191 $data->name
= trim($data->name
);
1194 $this->data_postprocessing($data);