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/>.
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_grades\component_gradeitems
;
33 * This class adds extra methods to form wrapper specific to be used for module add / update forms
34 * mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html Moodleform.
36 * @package core_course
37 * @copyright Andrew Nicols <andrew@nicols.co.uk>
39 abstract class moodleform_mod
extends moodleform
{
43 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
44 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
51 * Section of course that module instance will be put in or is in.
52 * This is always the section number itself (column 'section' from 'course_sections' table).
58 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
73 * List of modform features
77 * @var array Custom completion-rule elements, if enabled
79 protected $_customcompletionelements;
81 * @var string name of module.
84 /** current context, course or module depends if already exists*/
87 /** a flag indicating whether outcomes are being used*/
88 protected $_outcomesused;
91 * @var bool A flag used to indicate that this module should lock settings
92 * based on admin settings flags in definition_after_data.
94 protected $applyadminlockedflags = false;
96 /** @var object The course format of the current course. */
97 protected $courseformat;
99 /** @var string Whether this is graded or rated. */
100 private $gradedorrated = null;
102 public function __construct($current, $section, $cm, $course) {
105 $this->current
= $current;
106 $this->_instance
= $current->instance
;
107 $this->_section
= $section;
109 $this->_course
= $course;
111 $this->context
= context_module
::instance($this->_cm
->id
);
113 $this->context
= context_course
::instance($course->id
);
116 // Set the course format.
117 require_once($CFG->dirroot
. '/course/format/lib.php');
118 $this->courseformat
= course_get_format($course);
120 // Guess module name if not set.
121 if (is_null($this->_modname
)) {
123 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
124 debugging('Rename form to mod_xx_mod_form, where xx is name of your module');
125 print_error('unknownmodulename');
127 $this->_modname
= $matches[1];
129 $this->init_features();
130 parent
::__construct('modedit.php');
134 * Old syntax of class constructor. Deprecated in PHP7.
136 * @deprecated since Moodle 3.1
138 public function moodleform_mod($current, $section, $cm, $course) {
139 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
140 self
::__construct($current, $section, $cm, $course);
144 * Get the current data for the form.
145 * @return stdClass|null
147 public function get_current() {
148 return $this->current
;
152 * Get the DB record for the current instance.
153 * @return stdClass|null
155 public function get_instance() {
156 return $this->_instance
;
160 * Get the course section number (relative).
163 public function get_section() {
164 return $this->_section
;
171 public function get_course() {
172 return $this->_course
;
176 * Get the course module object.
177 * @return stdClass|null
179 public function get_coursemodule() {
184 * Return the course context for new modules, or the module context for existing modules.
187 public function get_context() {
188 return $this->context
;
192 * Return the features this module supports.
195 public function get_features() {
196 return $this->_features
;
200 protected function init_features() {
203 $this->_features
= new stdClass();
204 $this->_features
->groups
= plugin_supports('mod', $this->_modname
, FEATURE_GROUPS
, false);
205 $this->_features
->groupings
= plugin_supports('mod', $this->_modname
, FEATURE_GROUPINGS
, false);
206 $this->_features
->outcomes
= (!empty($CFG->enableoutcomes
) and plugin_supports('mod', $this->_modname
, FEATURE_GRADE_OUTCOMES
, true));
207 $this->_features
->hasgrades
= plugin_supports('mod', $this->_modname
, FEATURE_GRADE_HAS_GRADE
, false);
208 $this->_features
->idnumber
= plugin_supports('mod', $this->_modname
, FEATURE_IDNUMBER
, true);
209 $this->_features
->introeditor
= plugin_supports('mod', $this->_modname
, FEATURE_MOD_INTRO
, true);
210 $this->_features
->defaultcompletion
= plugin_supports('mod', $this->_modname
, FEATURE_MODEDIT_DEFAULT_COMPLETION
, true);
211 $this->_features
->rating
= plugin_supports('mod', $this->_modname
, FEATURE_RATE
, false);
212 $this->_features
->showdescription
= plugin_supports('mod', $this->_modname
, FEATURE_SHOW_DESCRIPTION
, false);
213 $this->_features
->gradecat
= ($this->_features
->outcomes
or $this->_features
->hasgrades
);
214 $this->_features
->advancedgrading
= plugin_supports('mod', $this->_modname
, FEATURE_ADVANCED_GRADING
, false);
215 $this->_features
->canrescale
= (component_callback_exists('mod_' . $this->_modname
, 'rescale_activity_grades') !== false);
219 * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
220 * This method is also called in the bulk activity completion form.
222 * Only available on moodleform_mod.
224 * @param array $default_values passed by reference
226 function data_preprocessing(&$default_values){
227 if (empty($default_values['scale'])) {
228 $default_values['assessed'] = 0;
231 if (empty($default_values['assessed'])){
232 $default_values['ratingtime'] = 0;
234 $default_values['ratingtime']=
235 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ?
1 : 0;
240 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
242 function definition_after_data() {
243 global $CFG, $COURSE;
244 $mform =& $this->_form
;
246 if ($id = $mform->getElementValue('update')) {
247 $modulename = $mform->getElementValue('modulename');
248 $instance = $mform->getElementValue('instance');
249 $component = "mod_{$modulename}";
251 if ($this->_features
->gradecat
) {
252 $hasgradeitems = false;
253 $items = grade_item
::fetch_all([
255 'itemmodule' => $modulename,
256 'iteminstance' => $instance,
257 'courseid' => $COURSE->id
,
260 $gradecategories = [];
261 $removecategories = [];
262 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
263 if (!empty($items)) {
264 foreach ($items as $item) {
265 if (!empty($item->outcomeid
)) {
266 $elname = 'outcome_'.$item->outcomeid
;
267 if ($mform->elementExists($elname)) {
268 $mform->hardFreeze($elname); // prevent removing of existing outcomes
271 $hasgradeitems = true;
275 foreach ($items as $item) {
276 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber(
282 if (!isset($gradecategories[$gradecatfieldname])) {
283 $gradecategories[$gradecatfieldname] = $item->categoryid
;
284 } else if ($gradecategories[$gradecatfieldname] != $item->categoryid
) {
285 $removecategories[$gradecatfieldname] = true;
290 foreach ($removecategories as $toremove) {
291 if ($mform->elementExists($toremove)) {
292 $mform->removeElement($toremove);
298 if ($COURSE->groupmodeforce
) {
299 if ($mform->elementExists('groupmode')) {
300 // The groupmode can not be changed if forced from course settings.
301 $mform->hardFreeze('groupmode');
305 // Don't disable/remove groupingid if it is currently set to something, otherwise you cannot turn it off at same
306 // time as turning off other option (MDL-30764).
307 if (empty($this->_cm
) ||
!$this->_cm
->groupingid
) {
308 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce
)) {
309 $mform->hideIf('groupingid', 'groupmode', 'eq', NOGROUPS
);
311 } else if (!$mform->elementExists('groupmode')) {
312 // Groupings have no use without groupmode.
313 if ($mform->elementExists('groupingid')) {
314 $mform->removeElement('groupingid');
316 // Nor does the group restrictions button.
317 if ($mform->elementExists('restrictgroupbutton')) {
318 $mform->removeElement('restrictgroupbutton');
323 // Completion: If necessary, freeze fields
324 $completion = new completion_info($COURSE);
325 if ($completion->is_enabled()) {
326 // If anybody has completed the activity, these options will be 'locked'
327 $completedcount = empty($this->_cm
)
329 : $completion->count_user_data($this->_cm
);
332 if (!$completedcount) {
333 if ($mform->elementExists('unlockcompletion')) {
334 $mform->removeElement('unlockcompletion');
336 // Automatically set to unlocked (note: this is necessary
337 // in order to make it recalculate completion once the option
338 // is changed, maybe someone has completed it now)
339 $mform->getElement('completionunlocked')->setValue(1);
341 // Has the element been unlocked, either by the button being pressed
342 // in this request, or the field already being set from a previous one?
343 if ($mform->exportValue('unlockcompletion') ||
344 $mform->exportValue('completionunlocked')) {
345 // Yes, add in warning text and set the hidden variable
346 $mform->insertElementBefore(
347 $mform->createElement('static', 'completedunlocked',
348 get_string('completedunlocked', 'completion'),
349 get_string('completedunlockedtext', 'completion')),
351 $mform->removeElement('unlockcompletion');
352 $mform->getElement('completionunlocked')->setValue(1);
354 // No, add in the warning text with the count (now we know
355 // it) before the unlock button
356 $mform->insertElementBefore(
357 $mform->createElement('static', 'completedwarning',
358 get_string('completedwarning', 'completion'),
359 get_string('completedwarningtext', 'completion', $completedcount)),
366 $mform->freeze('completion');
367 if ($mform->elementExists('completionview')) {
368 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
370 if ($mform->elementExists('completionusegrade')) {
371 $mform->freeze('completionusegrade');
373 if ($mform->elementExists('completiongradeitemnumber')) {
374 $mform->freeze('completiongradeitemnumber');
376 $mform->freeze($this->_customcompletionelements
);
380 // Freeze admin defaults if required (and not different from default)
381 $this->apply_admin_locked_flags();
383 $this->plugin_extend_coursemodule_definition_after_data();
387 function validation($data, $files) {
388 global $COURSE, $DB, $CFG;
389 $errors = parent
::validation($data, $files);
391 $mform =& $this->_form
;
395 if ($mform->elementExists('name')) {
396 $name = trim($data['name']);
398 $errors['name'] = get_string('required');
402 $grade_item = grade_item
::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
403 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id
));
404 if ($data['coursemodule']) {
405 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
410 if ($mform->elementExists('cmidnumber')) {
411 // verify the idnumber
412 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id
, $grade_item, $cm)) {
413 $errors['cmidnumber'] = get_string('idnumbertaken');
417 $component = "mod_{$this->_modname}";
418 $itemnames = component_gradeitems
::get_itemname_mapping_for_component($component);
419 foreach ($itemnames as $itemnumber => $itemname) {
420 $gradefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
421 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
422 $assessedfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
423 $scalefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
425 // Ratings: Don't let them select an aggregate type without selecting a scale.
426 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
427 // invalid. If ratings have been selected then the user must select either a scale or max points.
428 // This matches (horrible) logic in data_preprocessing.
429 if (isset($data[$assessedfieldname]) && $data[$assessedfieldname] > 0 && empty($data[$scalefieldname])) {
430 $errors[$assessedfieldname] = get_string('scaleselectionrequired', 'rating');
433 // Check that the grade pass is a valid number.
434 $gradepassvalid = false;
435 if (isset($data[$gradepassfieldname])) {
436 if (unformat_float($data[$gradepassfieldname], true) === false) {
437 $errors[$gradepassfieldname] = get_string('err_numeric', 'form');
439 $gradepassvalid = true;
443 // Grade to pass: ensure that the grade to pass is valid for points and scales.
444 // If we are working with a scale, convert into a positive number for validation.
445 if ($gradepassvalid && isset($data[$gradepassfieldname]) && (!empty($data[$gradefieldname]) ||
!empty($data[$scalefieldname]))) {
446 $scale = !empty($data[$gradefieldname]) ?
$data[$gradefieldname] : $data[$scalefieldname];
448 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
449 $grade = count(explode(',', $scalevalues->scale
));
453 if (unformat_float($data[$gradepassfieldname]) > $grade) {
454 $errors[$gradepassfieldname] = get_string('gradepassgreaterthangrade', 'grades', $grade);
458 // We have a grade if there is a non-falsey value for:
459 // - the assessedfieldname for Ratings there; or
460 // - the gradefieldname for Ratings there.
461 if (empty($data[$assessedfieldname]) && empty($data[$gradefieldname])) {
462 // There are no grades set therefore completion is not allowed.
463 if (isset($data['completiongradeitemnumber']) && $data['completiongradeitemnumber'] == (string) $itemnumber) {
464 $errors['completiongradeitemnumber'] = get_string(
465 'badcompletiongradeitemnumber',
467 get_string("grade_{$itemname}_name", $component)
473 // Completion: Don't let them choose automatic completion without turning
474 // on some conditions. Ignore this check when completion settings are
475 // locked, as the options are then disabled.
476 $automaticcompletion = array_key_exists('completion', $data);
477 $automaticcompletion = $automaticcompletion && $data['completion'] == COMPLETION_TRACKING_AUTOMATIC
;
478 $automaticcompletion = $automaticcompletion && !empty($data['completionunlocked']);
480 if ($automaticcompletion) {
482 $rulesenabled = !empty($data['completionview']);
484 // Use grade to complete (only one grade item).
485 $rulesenabled = $rulesenabled ||
!empty($data['completionusegrade']);
487 // Use grade to complete (specific grade item).
488 if (!$rulesenabled && isset($data['completiongradeitemnumber'])) {
489 $rulesenabled = $data['completiongradeitemnumber'] != '';
492 // Module-specific completion rules.
493 $rulesenabled = $rulesenabled ||
$this->completion_rule_enabled($data);
495 if (!$rulesenabled) {
496 // No rules are enabled. Can't set automatically completed without rules.
497 $errors['completion'] = get_string('badautocompletion', 'completion');
501 // Availability: Check availability field does not have errors.
502 if (!empty($CFG->enableavailability
)) {
503 \core_availability\frontend
::report_validation_errors($data, $errors);
506 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
507 if (!empty($pluginerrors)) {
508 $errors = array_merge($errors, $pluginerrors);
515 * Extend the validation function from any other plugin.
517 * @param stdClass $data The form data.
518 * @return array $errors The list of errors keyed by element name.
520 protected function plugin_extend_coursemodule_validation($data) {
523 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
524 foreach ($callbacks as $type => $plugins) {
525 foreach ($plugins as $plugin => $pluginfunction) {
526 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
527 $pluginerrors = $pluginfunction($this, $data);
528 if (!empty($pluginerrors)) {
529 $errors = array_merge($errors, $pluginerrors);
537 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
538 * form definition (new entry form); this function is used to load in data where values
539 * already exist and data is being edited (edit entry form).
541 * @param mixed $default_values object or array of default values
543 function set_data($default_values) {
544 if (is_object($default_values)) {
545 $default_values = (array)$default_values;
548 $this->data_preprocessing($default_values);
549 parent
::set_data($default_values);
553 * Adds all the standard elements to a form to edit the settings for an activity module.
555 protected function standard_coursemodule_elements() {
556 global $COURSE, $CFG, $DB;
557 $mform =& $this->_form
;
559 $this->_outcomesused
= false;
560 if ($this->_features
->outcomes
) {
561 if ($outcomes = grade_outcome
::fetch_all_available($COURSE->id
)) {
562 $this->_outcomesused
= true;
563 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
564 foreach($outcomes as $outcome) {
565 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id
, $outcome->get_name());
570 if ($this->_features
->rating
) {
571 $this->add_rating_settings($mform, 0);
574 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
576 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section
);
577 $allowstealth = !empty($CFG->allowstealth
) && $this->courseformat
->allow_stealth_module_visibility($this->_cm
, $section);
578 if ($allowstealth && $section->visible
) {
579 $modvisiblelabel = 'modvisiblewithstealth';
580 } else if ($section->visible
) {
581 $modvisiblelabel = 'modvisible';
583 $modvisiblelabel = 'modvisiblehiddensection';
585 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
586 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible
, 'cm' => $this->_cm
));
587 $mform->addHelpButton('visible', $modvisiblelabel);
588 if (!empty($this->_cm
)) {
589 $context = context_module
::instance($this->_cm
->id
);
590 if (!has_capability('moodle/course:activityvisibility', $context)) {
591 $mform->hardFreeze('visible');
595 if ($this->_features
->idnumber
) {
596 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
597 $mform->setType('cmidnumber', PARAM_RAW
);
598 $mform->addHelpButton('cmidnumber', 'idnumbermod');
601 if ($this->_features
->groups
) {
602 $options = array(NOGROUPS
=> get_string('groupsnone'),
603 SEPARATEGROUPS
=> get_string('groupsseparate'),
604 VISIBLEGROUPS
=> get_string('groupsvisible'));
605 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS
);
606 $mform->addHelpButton('groupmode', 'groupmode', 'group');
609 if ($this->_features
->groupings
) {
610 // Groupings selector - used to select grouping for groups in activity.
612 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id
))) {
613 foreach ($groupings as $grouping) {
614 $options[$grouping->id
] = format_string($grouping->name
);
617 core_collator
::asort($options);
618 $options = array(0 => get_string('none')) +
$options;
619 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
620 $mform->addHelpButton('groupingid', 'grouping', 'group');
623 if (!empty($CFG->enableavailability
)) {
624 // Add special button to end of previous section if groups/groupings
626 if ($this->_features
->groups ||
$this->_features
->groupings
) {
627 $mform->addElement('static', 'restrictgroupbutton', '',
628 html_writer
::tag('button', get_string('restrictbygroup', 'availability'),
629 array('id' => 'restrictbygroup', 'disabled' => 'disabled', 'class' => 'btn btn-secondary')));
632 // Availability field. This is just a textarea; the user interface
633 // interaction is all implemented in JavaScript.
634 $mform->addElement('header', 'availabilityconditionsheader',
635 get_string('restrictaccess', 'availability'));
636 // Note: This field cannot be named 'availability' because that
637 // conflicts with fields in existing modules (such as assign).
638 // So it uses a long name that will not conflict.
639 $mform->addElement('textarea', 'availabilityconditionsjson',
640 get_string('accessrestrictions', 'availability'));
641 // The _cm variable may not be a proper cm_info, so get one from modinfo.
643 $modinfo = get_fast_modinfo($COURSE);
644 $cm = $modinfo->get_cm($this->_cm
->id
);
648 \core_availability\frontend
::include_all_javascript($COURSE, $cm);
651 // Conditional activities: completion tracking section
652 if(!isset($completion)) {
653 $completion = new completion_info($COURSE);
655 if ($completion->is_enabled()) {
656 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
657 // Unlock button for if people have completed it (will
658 // be removed in definition_after_data if they haven't)
659 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
660 $mform->registerNoSubmitButton('unlockcompletion');
661 $mform->addElement('hidden', 'completionunlocked', 0);
662 $mform->setType('completionunlocked', PARAM_INT
);
664 $trackingdefault = COMPLETION_TRACKING_NONE
;
665 // If system and activity default is on, set it.
666 if ($CFG->completiondefault
&& $this->_features
->defaultcompletion
) {
667 $hasrules = plugin_supports('mod', $this->_modname
, FEATURE_COMPLETION_HAS_RULES
, true);
668 $tracksviews = plugin_supports('mod', $this->_modname
, FEATURE_COMPLETION_TRACKS_VIEWS
, true);
669 if ($hasrules ||
$tracksviews) {
670 $trackingdefault = COMPLETION_TRACKING_AUTOMATIC
;
672 $trackingdefault = COMPLETION_TRACKING_MANUAL
;
676 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
677 array(COMPLETION_TRACKING_NONE
=>get_string('completion_none', 'completion'),
678 COMPLETION_TRACKING_MANUAL
=>get_string('completion_manual', 'completion')));
679 $mform->setDefault('completion', $trackingdefault);
680 $mform->addHelpButton('completion', 'completion', 'completion');
682 // Automatic completion once you view it
683 $gotcompletionoptions = false;
684 if (plugin_supports('mod', $this->_modname
, FEATURE_COMPLETION_TRACKS_VIEWS
, false)) {
685 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
686 get_string('completionview_desc', 'completion'));
687 $mform->hideIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC
);
688 // Check by default if automatic completion tracking is set.
689 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC
) {
690 $mform->setDefault('completionview', 1);
692 $gotcompletionoptions = true;
695 if (plugin_supports('mod', $this->_modname
, FEATURE_GRADE_HAS_GRADE
, false)) {
696 // This activity supports grading.
697 $gotcompletionoptions = true;
699 $component = "mod_{$this->_modname}";
700 $itemnames = component_gradeitems
::get_itemname_mapping_for_component($component);
702 if (count($itemnames) === 1) {
703 // Only one gradeitem in this activity.
704 // We use the completionusegrade field here.
707 'completionusegrade',
708 get_string('completionusegrade', 'completion'),
709 get_string('completionusegrade_desc', 'completion')
711 $mform->hideIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC
);
712 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
714 // The disabledIf logic differs between ratings and other grade items due to different field types.
715 if ($this->_features
->rating
) {
716 // If using the rating system, there is no grade unless ratings are enabled.
717 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
719 // All other field types use the '$gradefieldname' field's modgrade_type.
720 $itemnumbers = array_keys($itemnames);
721 $itemnumber = array_shift($itemnumbers);
722 $gradefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
723 $mform->disabledIf('completionusegrade', "{$gradefieldname}[modgrade_type]", 'eq', 'none');
725 } else if (count($itemnames) > 1) {
726 // There are multiple grade items in this activity.
729 '' => get_string('activitygradenotrequired', 'completion'),
731 foreach ($itemnames as $itemnumber => $itemname) {
732 $options[$itemnumber] = get_string("grade_{$itemname}_name", $component);
737 'completiongradeitemnumber',
738 get_string('completionusegrade', 'completion'),
741 $mform->hideIf('completiongradeitemnumber', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC
);
745 // Automatic completion according to module-specific rules
746 $this->_customcompletionelements
= $this->add_completion_rules();
747 foreach ($this->_customcompletionelements
as $element) {
748 $mform->hideIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC
);
751 $gotcompletionoptions = $gotcompletionoptions ||
752 count($this->_customcompletionelements
)>0;
754 // Automatic option only appears if possible
755 if ($gotcompletionoptions) {
756 $mform->getElement('completion')->addOption(
757 get_string('completion_automatic', 'completion'),
758 COMPLETION_TRACKING_AUTOMATIC
);
761 // Completion expected at particular date? (For progress tracking)
762 $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
763 array('optional' => true));
764 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
765 $mform->hideIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE
);
768 // Populate module tags.
769 if (core_tag_tag
::is_enabled('core', 'course_modules')) {
770 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
771 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
773 $tags = core_tag_tag
::get_item_tags_array('core', 'course_modules', $this->_cm
->id
);
774 $mform->setDefault('tags', $tags);
778 $this->standard_hidden_coursemodule_elements();
780 $this->plugin_extend_coursemodule_standard_elements();
784 * Add rating settings.
786 * @param moodleform_mod $mform
787 * @param int $itemnumber
789 protected function add_rating_settings($mform, int $itemnumber) {
790 global $CFG, $COURSE;
792 if ($this->gradedorrated
&& $this->gradedorrated
!== 'rated') {
795 $this->gradedorrated
= 'rated';
797 require_once("{$CFG->dirroot}/rating/lib.php");
798 $rm = new rating_manager();
800 $component = "mod_{$this->_modname}";
801 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
802 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
803 $assessedfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
804 $scalefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
806 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
808 $isupdate = !empty($this->_cm
);
810 $rolenamestring = null;
812 $context = context_module
::instance($this->_cm
->id
);
813 $capabilities = ['moodle/rating:rate', "mod/{$this->_cm->modname}:rate"];
814 $rolenames = get_role_names_with_caps_in_context($context, $capabilities);
815 $rolenamestring = implode(', ', $rolenames);
817 $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
820 $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
821 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
823 $mform->addElement('select', $assessedfieldname, get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
824 $mform->setDefault($assessedfieldname, 0);
825 $mform->addHelpButton($assessedfieldname, 'aggregatetype', 'rating');
828 'isupdate' => $isupdate,
829 'currentgrade' => false,
830 'hasgrades' => false,
831 'canrescale' => false,
832 'useratings' => true,
835 $gradeitem = grade_item
::fetch([
837 'itemmodule' => $this->_cm
->modname
,
838 'iteminstance' => $this->_cm
->instance
,
839 'itemnumber' => $itemnumber,
840 'courseid' => $COURSE->id
,
843 $gradeoptions['currentgrade'] = $gradeitem->grademax
;
844 $gradeoptions['currentgradetype'] = $gradeitem->gradetype
;
845 $gradeoptions['currentscaleid'] = $gradeitem->scaleid
;
846 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
850 $mform->addElement('modgrade', $scalefieldname, get_string('scale'), $gradeoptions);
851 $mform->hideIf($scalefieldname, $assessedfieldname, 'eq', 0);
852 $mform->addHelpButton($scalefieldname, 'modgrade', 'grades');
853 $mform->setDefault($scalefieldname, $CFG->gradepointdefault
);
855 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
856 $mform->hideIf('ratingtime', $assessedfieldname, 'eq', 0);
858 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
859 $mform->hideIf('assesstimestart', $assessedfieldname, 'eq', 0);
860 $mform->hideIf('assesstimestart', 'ratingtime');
862 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
863 $mform->hideIf('assesstimefinish', $assessedfieldname, 'eq', 0);
864 $mform->hideIf('assesstimefinish', 'ratingtime');
866 if ($this->_features
->gradecat
) {
870 get_string('gradecategoryonmodform', 'grades'),
871 grade_get_categories_menu($COURSE->id
, $this->_outcomesused
)
873 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
874 $mform->hideIf($gradecatfieldname, $assessedfieldname, 'eq', 0);
875 $mform->hideIf($gradecatfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
879 $mform->addElement('text', $gradepassfieldname, get_string('gradepass', 'grades'));
880 $mform->addHelpButton($gradepassfieldname, 'gradepass', 'grades');
881 $mform->setDefault($gradepassfieldname, '');
882 $mform->setType($gradepassfieldname, PARAM_RAW
);
883 $mform->hideIf($gradepassfieldname, $assessedfieldname, 'eq', '0');
884 $mform->hideIf($gradepassfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
888 * Plugins can extend the coursemodule settings form.
890 protected function plugin_extend_coursemodule_standard_elements() {
891 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
892 foreach ($callbacks as $type => $plugins) {
893 foreach ($plugins as $plugin => $pluginfunction) {
894 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
896 $pluginfunction($this, $this->_form
);
902 * Plugins can extend the coursemodule settings form after the data is set.
904 protected function plugin_extend_coursemodule_definition_after_data() {
905 $callbacks = get_plugins_with_function('coursemodule_definition_after_data', 'lib.php');
906 foreach ($callbacks as $type => $plugins) {
907 foreach ($plugins as $plugin => $pluginfunction) {
908 $pluginfunction($this, $this->_form
);
914 * Can be overridden to add custom completion rules if the module wishes
915 * them. If overriding this, you should also override completion_rule_enabled.
917 * Just add elements to the form as needed and return the list of IDs. The
918 * system will call disabledIf and handle other behaviour for each returned
920 * @return array Array of string IDs of added items, empty array if none
922 function add_completion_rules() {
927 * Called during validation. Override to indicate, based on the data, whether
928 * a custom completion rule is enabled (selected).
930 * @param array $data Input data (not yet validated)
931 * @return bool True if one or more rules is enabled, false if none are;
932 * default returns false
934 function completion_rule_enabled($data) {
938 function standard_hidden_coursemodule_elements(){
939 $mform =& $this->_form
;
940 $mform->addElement('hidden', 'course', 0);
941 $mform->setType('course', PARAM_INT
);
943 $mform->addElement('hidden', 'coursemodule', 0);
944 $mform->setType('coursemodule', PARAM_INT
);
946 $mform->addElement('hidden', 'section', 0);
947 $mform->setType('section', PARAM_INT
);
949 $mform->addElement('hidden', 'module', 0);
950 $mform->setType('module', PARAM_INT
);
952 $mform->addElement('hidden', 'modulename', '');
953 $mform->setType('modulename', PARAM_PLUGIN
);
955 $mform->addElement('hidden', 'instance', 0);
956 $mform->setType('instance', PARAM_INT
);
958 $mform->addElement('hidden', 'add', 0);
959 $mform->setType('add', PARAM_ALPHANUM
);
961 $mform->addElement('hidden', 'update', 0);
962 $mform->setType('update', PARAM_INT
);
964 $mform->addElement('hidden', 'return', 0);
965 $mform->setType('return', PARAM_BOOL
);
967 $mform->addElement('hidden', 'sr', 0);
968 $mform->setType('sr', PARAM_INT
);
971 public function standard_grading_coursemodule_elements() {
972 global $COURSE, $CFG;
974 if ($this->gradedorrated
&& $this->gradedorrated
!== 'graded') {
977 if ($this->_features
->rating
) {
980 $this->gradedorrated
= 'graded';
983 $component = "mod_{$this->_modname}";
984 $gradefieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
985 $gradecatfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
986 $gradepassfieldname = component_gradeitems
::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
988 $mform =& $this->_form
;
989 $isupdate = !empty($this->_cm
);
990 $gradeoptions = array('isupdate' => $isupdate,
991 'currentgrade' => false,
992 'hasgrades' => false,
993 'canrescale' => $this->_features
->canrescale
,
994 'useratings' => $this->_features
->rating
);
996 if ($this->_features
->hasgrades
) {
997 if ($this->_features
->gradecat
) {
998 $mform->addElement('header', 'modstandardgrade', get_string('gradenoun'));
1001 //if supports grades and grades arent being handled via ratings
1003 $gradeitem = grade_item
::fetch(array('itemtype' => 'mod',
1004 'itemmodule' => $this->_cm
->modname
,
1005 'iteminstance' => $this->_cm
->instance
,
1007 'courseid' => $COURSE->id
));
1009 $gradeoptions['currentgrade'] = $gradeitem->grademax
;
1010 $gradeoptions['currentgradetype'] = $gradeitem->gradetype
;
1011 $gradeoptions['currentscaleid'] = $gradeitem->scaleid
;
1012 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
1015 $mform->addElement('modgrade', $gradefieldname, get_string('gradenoun'), $gradeoptions);
1016 $mform->addHelpButton($gradefieldname, 'modgrade', 'grades');
1017 $mform->setDefault($gradefieldname, $CFG->gradepointdefault
);
1019 if ($this->_features
->advancedgrading
1020 and !empty($this->current
->_advancedgradingdata
['methods'])
1021 and !empty($this->current
->_advancedgradingdata
['areas'])) {
1023 if (count($this->current
->_advancedgradingdata
['areas']) == 1) {
1024 // if there is just one gradable area (most cases), display just the selector
1025 // without its name to make UI simplier
1026 $areadata = reset($this->current
->_advancedgradingdata
['areas']);
1027 $areaname = key($this->current
->_advancedgradingdata
['areas']);
1028 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
1029 get_string('gradingmethod', 'core_grading'), $this->current
->_advancedgradingdata
['methods']);
1030 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
1031 $mform->hideIf('advancedgradingmethod_'.$areaname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1034 // the module defines multiple gradable areas, display a selector
1035 // for each of them together with a name of the area
1036 $areasgroup = array();
1037 foreach ($this->current
->_advancedgradingdata
['areas'] as $areaname => $areadata) {
1038 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
1039 $areadata['title'], $this->current
->_advancedgradingdata
['methods']);
1040 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
1042 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
1043 array(' ', '<br />'), false);
1047 if ($this->_features
->gradecat
) {
1048 $mform->addElement('select', $gradecatfieldname,
1049 get_string('gradecategoryonmodform', 'grades'),
1050 grade_get_categories_menu($COURSE->id
, $this->_outcomesused
));
1051 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
1052 $mform->hideIf($gradecatfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1056 $mform->addElement('text', $gradepassfieldname, get_string($gradepassfieldname, 'grades'));
1057 $mform->addHelpButton($gradepassfieldname, $gradepassfieldname, 'grades');
1058 $mform->setDefault($gradepassfieldname, '');
1059 $mform->setType($gradepassfieldname, PARAM_RAW
);
1060 $mform->hideIf($gradepassfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1065 * Add an editor for an activity's introduction field.
1066 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
1067 * @param null $required Override system default for requiremodintro
1068 * @param null $customlabel Override default label for editor
1069 * @throws coding_exception
1071 protected function add_intro_editor($required=null, $customlabel=null) {
1072 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
1073 debugging($str, DEBUG_DEVELOPER
);
1075 $this->standard_intro_elements($customlabel);
1080 * Add an editor for an activity's introduction field.
1082 * @param null $customlabel Override default label for editor
1083 * @throws coding_exception
1085 protected function standard_intro_elements($customlabel=null) {
1088 $required = $CFG->requiremodintro
;
1090 $mform = $this->_form
;
1091 $label = is_null($customlabel) ?
get_string('moduleintro') : $customlabel;
1093 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES
,
1094 'noclean' => true, 'context' => $this->context
, 'subdirs' => true));
1095 $mform->setType('introeditor', PARAM_RAW
); // no XSS prevention here, users must be trusted
1097 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
1100 // If the 'show description' feature is enabled, this checkbox appears below the intro.
1101 // We want to hide that when using the singleactivity course format because it is confusing.
1102 if ($this->_features
->showdescription
&& $this->courseformat
->has_view_page()) {
1103 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
1104 $mform->addHelpButton('showdescription', 'showdescription');
1109 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
1111 * @param bool $cancel show cancel button
1112 * @param string $submitlabel null means default, false means none, string is label text
1113 * @param string $submit2label null means default, false means none, string is label text
1116 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
1117 if (is_null($submitlabel)) {
1118 $submitlabel = get_string('savechangesanddisplay');
1121 if (is_null($submit2label)) {
1122 $submit2label = get_string('savechangesandreturntocourse');
1125 $mform = $this->_form
;
1127 // elements in a row need a group
1128 $buttonarray = array();
1130 // Label for the submit button to return to the course.
1131 // Ignore this button in single activity format because it is confusing.
1132 if ($submit2label !== false && $this->courseformat
->has_view_page()) {
1133 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
1136 if ($submitlabel !== false) {
1137 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1141 $buttonarray[] = &$mform->createElement('cancel');
1144 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1145 $mform->setType('buttonar', PARAM_RAW
);
1146 $mform->closeHeaderBefore('buttonar');
1150 * Get the list of admin settings for this module and apply any locked settings.
1151 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
1152 * in that function because set_data has not been called yet.
1156 protected function apply_admin_locked_flags() {
1159 if (!$this->applyadminlockedflags
) {
1163 $settings = get_config($this->_modname
);
1164 $mform = $this->_form
;
1165 $lockedicon = html_writer
::tag('span',
1166 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1167 array('class' => 'action-icon'));
1168 $isupdate = !empty($this->_cm
);
1170 foreach ($settings as $name => $value) {
1171 if (strpos('_', $name) !== false) {
1174 if ($mform->elementExists($name)) {
1175 $element = $mform->getElement($name);
1176 $lockedsetting = $name . '_locked';
1177 if (!empty($settings->$lockedsetting)) {
1178 // Always lock locked settings for new modules,
1179 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1180 $value = $settings->$name;
1181 if ($isupdate && isset($this->current
->$name)) {
1182 $value = $this->current
->$name;
1184 if ($value == $settings->$name) {
1185 $mform->setConstant($name, $settings->$name);
1186 $element->setLabel($element->getLabel() . $lockedicon);
1187 // Do not use hardfreeze because we need the hidden input to check dependencies.
1196 * Get the list of admin settings for this module and apply any defaults/advanced/locked/required settings.
1198 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1199 * default date/time value should be relative to. If not passed, all
1200 * date/time fields are set relative to the users current midnight.
1203 public function apply_admin_defaults($datetimeoffsets = array()) {
1204 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1205 $this->applyadminlockedflags
= true;
1207 $settings = get_config($this->_modname
);
1208 $mform = $this->_form
;
1209 $usermidnight = usergetmidnight(time());
1210 $isupdate = !empty($this->_cm
);
1212 foreach ($settings as $name => $value) {
1213 if (strpos('_', $name) !== false) {
1216 if ($mform->elementExists($name)) {
1217 $element = $mform->getElement($name);
1219 if ($element->getType() == 'date_time_selector') {
1220 $enabledsetting = $name . '_enabled';
1221 if (empty($settings->$enabledsetting)) {
1222 $mform->setDefault($name, 0);
1224 $relativetime = $usermidnight;
1225 if (isset($datetimeoffsets[$name])) {
1226 $relativetime = $datetimeoffsets[$name];
1228 $mform->setDefault($name, $relativetime +
$settings->$name);
1231 $mform->setDefault($name, $settings->$name);
1234 $advancedsetting = $name . '_adv';
1235 if (!empty($settings->$advancedsetting)) {
1236 $mform->setAdvanced($name);
1238 $requiredsetting = $name . '_required';
1239 if (!empty($settings->$requiredsetting)) {
1240 $mform->addRule($name, null, 'required', null, 'client');
1247 * Allows modules to modify the data returned by form get_data().
1248 * This method is also called in the bulk activity completion form.
1250 * Only available on moodleform_mod.
1252 * @param stdClass $data passed by reference
1254 public function data_postprocessing($data) {
1258 * Return submitted data if properly submitted or returns NULL if validation fails or
1259 * if there is no submitted data.
1261 * Do not override this method, override data_postprocessing() instead.
1263 * @return object submitted data; NULL if not valid or not submitted or cancelled
1265 public function get_data() {
1266 $data = parent
::get_data();
1268 // Convert the grade pass value - we may be using a language which uses commas,
1269 // rather than decimal points, in numbers. These need to be converted so that
1270 // they can be added to the DB.
1271 if (isset($data->gradepass
)) {
1272 $data->gradepass
= unformat_float($data->gradepass
);
1275 // Trim name for all activity name.
1276 if (isset($data->name
)) {
1277 $data->name
= trim($data->name
);
1280 $this->data_postprocessing($data);