weekly release 3.9.14+
[moodle.git] / course / moodleform_mod.php
blobeef95ca6d47401d4725699a3cbefddfc370b09f6
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_grades\component_gradeitems;
32 /**
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 {
40 /** Current data */
41 protected $current;
42 /**
43 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
44 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
45 * update one.
47 * @var mixed
49 protected $_instance;
50 /**
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).
54 * @var int
56 protected $_section;
57 /**
58 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
59 * update one.
61 * @var mixed
63 protected $_cm;
65 /**
66 * Current course.
68 * @var mixed
70 protected $_course;
72 /**
73 * List of modform features
75 protected $_features;
76 /**
77 * @var array Custom completion-rule elements, if enabled
79 protected $_customcompletionelements;
80 /**
81 * @var string name of module.
83 protected $_modname;
84 /** current context, course or module depends if already exists*/
85 protected $context;
87 /** a flag indicating whether outcomes are being used*/
88 protected $_outcomesused;
90 /**
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) {
103 global $CFG;
105 $this->current = $current;
106 $this->_instance = $current->instance;
107 $this->_section = $section;
108 $this->_cm = $cm;
109 $this->_course = $course;
110 if ($this->_cm) {
111 $this->context = context_module::instance($this->_cm->id);
112 } else {
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)) {
122 $matches = array();
123 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
124 debugging('Rename form to mod_xx_mod_form, where xx is name of your module');
125 print_error('unknownmodulename');
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).
161 * @return int
163 public function get_section() {
164 return $this->_section;
168 * Get the course id.
169 * @return int
171 public function get_course() {
172 return $this->_course;
176 * Get the course module object.
177 * @return stdClass|null
179 public function get_coursemodule() {
180 return $this->_cm;
184 * Return the course context for new modules, or the module context for existing modules.
185 * @return context
187 public function get_context() {
188 return $this->context;
192 * Return the features this module supports.
193 * @return stdClass
195 public function get_features() {
196 return $this->_features;
200 protected function init_features() {
201 global $CFG;
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;
233 } else {
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([
254 'itemtype' => 'mod',
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
270 } else {
271 $hasgradeitems = true;
275 foreach ($items as $item) {
276 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber(
277 $component,
278 $item->itemnumber,
279 'gradecat'
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);
331 $freeze = false;
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);
340 } else {
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')),
350 'unlockcompletion');
351 $mform->removeElement('unlockcompletion');
352 $mform->getElement('completionunlocked')->setValue(1);
353 } else {
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)),
360 'unlockcompletion');
361 $freeze = true;
365 if ($freeze) {
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();
384 // form verification
385 function validation($data, $files) {
386 global $COURSE, $DB, $CFG;
387 $errors = parent::validation($data, $files);
389 $mform =& $this->_form;
391 $errors = array();
393 if ($mform->elementExists('name')) {
394 $name = trim($data['name']);
395 if ($name == '') {
396 $errors['name'] = get_string('required');
400 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
401 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
402 if ($data['coursemodule']) {
403 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
404 } else {
405 $cm = null;
408 if ($mform->elementExists('cmidnumber')) {
409 // verify the idnumber
410 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
411 $errors['cmidnumber'] = get_string('idnumbertaken');
415 $component = "mod_{$this->_modname}";
416 $itemnames = component_gradeitems::get_itemname_mapping_for_component($component);
417 foreach ($itemnames as $itemnumber => $itemname) {
418 $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
419 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
420 $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
421 $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
423 // Ratings: Don't let them select an aggregate type without selecting a scale.
424 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
425 // invalid. If ratings have been selected then the user must select either a scale or max points.
426 // This matches (horrible) logic in data_preprocessing.
427 if (isset($data[$assessedfieldname]) && $data[$assessedfieldname] > 0 && empty($data[$scalefieldname])) {
428 $errors[$assessedfieldname] = get_string('scaleselectionrequired', 'rating');
431 // Check that the grade pass is a valid number.
432 $gradepassvalid = false;
433 if (isset($data[$gradepassfieldname])) {
434 if (unformat_float($data[$gradepassfieldname], true) === false) {
435 $errors[$gradepassfieldname] = get_string('err_numeric', 'form');
436 } else {
437 $gradepassvalid = true;
441 // Grade to pass: ensure that the grade to pass is valid for points and scales.
442 // If we are working with a scale, convert into a positive number for validation.
443 if ($gradepassvalid && isset($data[$gradepassfieldname]) && (!empty($data[$gradefieldname]) || !empty($data[$scalefieldname]))) {
444 $scale = !empty($data[$gradefieldname]) ? $data[$gradefieldname] : $data[$scalefieldname];
445 if ($scale < 0) {
446 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
447 $grade = count(explode(',', $scalevalues->scale));
448 } else {
449 $grade = $scale;
451 if (unformat_float($data[$gradepassfieldname]) > $grade) {
452 $errors[$gradepassfieldname] = get_string('gradepassgreaterthangrade', 'grades', $grade);
456 // We have a grade if there is a non-falsey value for:
457 // - the assessedfieldname for Ratings there; or
458 // - the gradefieldname for Ratings there.
459 if (empty($data[$assessedfieldname]) && empty($data[$gradefieldname])) {
460 // There are no grades set therefore completion is not allowed.
461 if (isset($data['completiongradeitemnumber']) && $data['completiongradeitemnumber'] == (string) $itemnumber) {
462 $errors['completiongradeitemnumber'] = get_string(
463 'badcompletiongradeitemnumber',
464 'completion',
465 get_string("grade_{$itemname}_name", $component)
471 // Completion: Don't let them choose automatic completion without turning
472 // on some conditions. Ignore this check when completion settings are
473 // locked, as the options are then disabled.
474 $automaticcompletion = array_key_exists('completion', $data);
475 $automaticcompletion = $automaticcompletion && $data['completion'] == COMPLETION_TRACKING_AUTOMATIC;
476 $automaticcompletion = $automaticcompletion && !empty($data['completionunlocked']);
478 if ($automaticcompletion) {
479 // View to complete.
480 $rulesenabled = !empty($data['completionview']);
482 // Use grade to complete (only one grade item).
483 $rulesenabled = $rulesenabled || !empty($data['completionusegrade']);
485 // Use grade to complete (specific grade item).
486 if (!$rulesenabled && isset($data['completiongradeitemnumber'])) {
487 $rulesenabled = $data['completiongradeitemnumber'] != '';
490 // Module-specific completion rules.
491 $rulesenabled = $rulesenabled || $this->completion_rule_enabled($data);
493 if (!$rulesenabled) {
494 // No rules are enabled. Can't set automatically completed without rules.
495 $errors['completion'] = get_string('badautocompletion', 'completion');
499 // Availability: Check availability field does not have errors.
500 if (!empty($CFG->enableavailability)) {
501 \core_availability\frontend::report_validation_errors($data, $errors);
504 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
505 if (!empty($pluginerrors)) {
506 $errors = array_merge($errors, $pluginerrors);
509 return $errors;
513 * Extend the validation function from any other plugin.
515 * @param stdClass $data The form data.
516 * @return array $errors The list of errors keyed by element name.
518 protected function plugin_extend_coursemodule_validation($data) {
519 $errors = array();
521 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
522 foreach ($callbacks as $type => $plugins) {
523 foreach ($plugins as $plugin => $pluginfunction) {
524 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
525 $pluginerrors = $pluginfunction($this, $data);
526 if (!empty($pluginerrors)) {
527 $errors = array_merge($errors, $pluginerrors);
531 return $errors;
535 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
536 * form definition (new entry form); this function is used to load in data where values
537 * already exist and data is being edited (edit entry form).
539 * @param mixed $default_values object or array of default values
541 function set_data($default_values) {
542 if (is_object($default_values)) {
543 $default_values = (array)$default_values;
546 $this->data_preprocessing($default_values);
547 parent::set_data($default_values);
551 * Adds all the standard elements to a form to edit the settings for an activity module.
553 protected function standard_coursemodule_elements() {
554 global $COURSE, $CFG, $DB;
555 $mform =& $this->_form;
557 $this->_outcomesused = false;
558 if ($this->_features->outcomes) {
559 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
560 $this->_outcomesused = true;
561 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
562 foreach($outcomes as $outcome) {
563 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
568 if ($this->_features->rating) {
569 $this->add_rating_settings($mform, 0);
572 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
574 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section);
575 $allowstealth = !empty($CFG->allowstealth) && $this->courseformat->allow_stealth_module_visibility($this->_cm, $section);
576 if ($allowstealth && $section->visible) {
577 $modvisiblelabel = 'modvisiblewithstealth';
578 } else if ($section->visible) {
579 $modvisiblelabel = 'modvisible';
580 } else {
581 $modvisiblelabel = 'modvisiblehiddensection';
583 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
584 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible, 'cm' => $this->_cm));
585 $mform->addHelpButton('visible', $modvisiblelabel);
586 if (!empty($this->_cm)) {
587 $context = context_module::instance($this->_cm->id);
588 if (!has_capability('moodle/course:activityvisibility', $context)) {
589 $mform->hardFreeze('visible');
593 if ($this->_features->idnumber) {
594 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
595 $mform->setType('cmidnumber', PARAM_RAW);
596 $mform->addHelpButton('cmidnumber', 'idnumbermod');
599 if ($this->_features->groups) {
600 $options = array(NOGROUPS => get_string('groupsnone'),
601 SEPARATEGROUPS => get_string('groupsseparate'),
602 VISIBLEGROUPS => get_string('groupsvisible'));
603 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
604 $mform->addHelpButton('groupmode', 'groupmode', 'group');
607 if ($this->_features->groupings) {
608 // Groupings selector - used to select grouping for groups in activity.
609 $options = array();
610 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
611 foreach ($groupings as $grouping) {
612 $options[$grouping->id] = format_string($grouping->name);
615 core_collator::asort($options);
616 $options = array(0 => get_string('none')) + $options;
617 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
618 $mform->addHelpButton('groupingid', 'grouping', 'group');
621 if (!empty($CFG->enableavailability)) {
622 // Add special button to end of previous section if groups/groupings
623 // are enabled.
625 $availabilityplugins = \core\plugininfo\availability::get_enabled_plugins();
626 $groupavailability = $this->_features->groups && array_key_exists('group', $availabilityplugins);
627 $groupingavailability = $this->_features->groupings && array_key_exists('grouping', $availabilityplugins);
629 if ($groupavailability || $groupingavailability) {
630 // When creating the button, we need to set type=button to prevent it behaving as a submit.
631 $mform->addElement('static', 'restrictgroupbutton', '',
632 html_writer::tag('button', get_string('restrictbygroup', 'availability'), [
633 'id' => 'restrictbygroup',
634 'type' => 'button',
635 'disabled' => 'disabled',
636 'class' => 'btn btn-secondary',
637 'data-groupavailability' => $groupavailability,
638 'data-groupingavailability' => $groupingavailability
643 // Availability field. This is just a textarea; the user interface
644 // interaction is all implemented in JavaScript.
645 $mform->addElement('header', 'availabilityconditionsheader',
646 get_string('restrictaccess', 'availability'));
647 // Note: This field cannot be named 'availability' because that
648 // conflicts with fields in existing modules (such as assign).
649 // So it uses a long name that will not conflict.
650 $mform->addElement('textarea', 'availabilityconditionsjson',
651 get_string('accessrestrictions', 'availability'));
652 // The _cm variable may not be a proper cm_info, so get one from modinfo.
653 if ($this->_cm) {
654 $modinfo = get_fast_modinfo($COURSE);
655 $cm = $modinfo->get_cm($this->_cm->id);
656 } else {
657 $cm = null;
659 \core_availability\frontend::include_all_javascript($COURSE, $cm);
662 // Conditional activities: completion tracking section
663 if(!isset($completion)) {
664 $completion = new completion_info($COURSE);
666 if ($completion->is_enabled()) {
667 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
668 // Unlock button for if people have completed it (will
669 // be removed in definition_after_data if they haven't)
670 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
671 $mform->registerNoSubmitButton('unlockcompletion');
672 $mform->addElement('hidden', 'completionunlocked', 0);
673 $mform->setType('completionunlocked', PARAM_INT);
675 $trackingdefault = COMPLETION_TRACKING_NONE;
676 // If system and activity default is on, set it.
677 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
678 $hasrules = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_HAS_RULES, true);
679 $tracksviews = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, true);
680 if ($hasrules || $tracksviews) {
681 $trackingdefault = COMPLETION_TRACKING_AUTOMATIC;
682 } else {
683 $trackingdefault = COMPLETION_TRACKING_MANUAL;
687 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
688 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
689 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
690 $mform->setDefault('completion', $trackingdefault);
691 $mform->addHelpButton('completion', 'completion', 'completion');
693 // Automatic completion once you view it
694 $gotcompletionoptions = false;
695 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
696 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
697 get_string('completionview_desc', 'completion'));
698 $mform->hideIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
699 // Check by default if automatic completion tracking is set.
700 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC) {
701 $mform->setDefault('completionview', 1);
703 $gotcompletionoptions = true;
706 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
707 // This activity supports grading.
708 $gotcompletionoptions = true;
710 $component = "mod_{$this->_modname}";
711 $itemnames = component_gradeitems::get_itemname_mapping_for_component($component);
713 if (count($itemnames) === 1) {
714 // Only one gradeitem in this activity.
715 // We use the completionusegrade field here.
716 $mform->addElement(
717 'checkbox',
718 'completionusegrade',
719 get_string('completionusegrade', 'completion'),
720 get_string('completionusegrade_desc', 'completion')
722 $mform->hideIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
723 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
725 // The disabledIf logic differs between ratings and other grade items due to different field types.
726 if ($this->_features->rating) {
727 // If using the rating system, there is no grade unless ratings are enabled.
728 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
729 } else {
730 // All other field types use the '$gradefieldname' field's modgrade_type.
731 $itemnumbers = array_keys($itemnames);
732 $itemnumber = array_shift($itemnumbers);
733 $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
734 $mform->disabledIf('completionusegrade', "{$gradefieldname}[modgrade_type]", 'eq', 'none');
736 } else if (count($itemnames) > 1) {
737 // There are multiple grade items in this activity.
738 // Show them all.
739 $options = [
740 '' => get_string('activitygradenotrequired', 'completion'),
742 foreach ($itemnames as $itemnumber => $itemname) {
743 $options[$itemnumber] = get_string("grade_{$itemname}_name", $component);
746 $mform->addElement(
747 'select',
748 'completiongradeitemnumber',
749 get_string('completionusegrade', 'completion'),
750 $options
752 $mform->hideIf('completiongradeitemnumber', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
756 // Automatic completion according to module-specific rules
757 $this->_customcompletionelements = $this->add_completion_rules();
758 foreach ($this->_customcompletionelements as $element) {
759 $mform->hideIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
762 $gotcompletionoptions = $gotcompletionoptions ||
763 count($this->_customcompletionelements)>0;
765 // Automatic option only appears if possible
766 if ($gotcompletionoptions) {
767 $mform->getElement('completion')->addOption(
768 get_string('completion_automatic', 'completion'),
769 COMPLETION_TRACKING_AUTOMATIC);
772 // Completion expected at particular date? (For progress tracking)
773 $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
774 array('optional' => true));
775 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
776 $mform->hideIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
779 // Populate module tags.
780 if (core_tag_tag::is_enabled('core', 'course_modules')) {
781 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
782 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
783 if ($this->_cm) {
784 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
785 $mform->setDefault('tags', $tags);
789 $this->standard_hidden_coursemodule_elements();
791 $this->plugin_extend_coursemodule_standard_elements();
795 * Add rating settings.
797 * @param moodleform_mod $mform
798 * @param int $itemnumber
800 protected function add_rating_settings($mform, int $itemnumber) {
801 global $CFG, $COURSE;
803 if ($this->gradedorrated && $this->gradedorrated !== 'rated') {
804 return;
806 $this->gradedorrated = 'rated';
808 require_once("{$CFG->dirroot}/rating/lib.php");
809 $rm = new rating_manager();
811 $component = "mod_{$this->_modname}";
812 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
813 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
814 $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
815 $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
817 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
819 $isupdate = !empty($this->_cm);
821 $rolenamestring = null;
822 if ($isupdate) {
823 $context = context_module::instance($this->_cm->id);
824 $capabilities = ['moodle/rating:rate', "mod/{$this->_cm->modname}:rate"];
825 $rolenames = get_role_names_with_caps_in_context($context, $capabilities);
826 $rolenamestring = implode(', ', $rolenames);
827 } else {
828 $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
831 $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
832 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
834 $mform->addElement('select', $assessedfieldname, get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
835 $mform->setDefault($assessedfieldname, 0);
836 $mform->addHelpButton($assessedfieldname, 'aggregatetype', 'rating');
838 $gradeoptions = [
839 'isupdate' => $isupdate,
840 'currentgrade' => false,
841 'hasgrades' => false,
842 'canrescale' => false,
843 'useratings' => true,
845 if ($isupdate) {
846 $gradeitem = grade_item::fetch([
847 'itemtype' => 'mod',
848 'itemmodule' => $this->_cm->modname,
849 'iteminstance' => $this->_cm->instance,
850 'itemnumber' => $itemnumber,
851 'courseid' => $COURSE->id,
853 if ($gradeitem) {
854 $gradeoptions['currentgrade'] = $gradeitem->grademax;
855 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
856 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
857 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
861 $mform->addElement('modgrade', $scalefieldname, get_string('scale'), $gradeoptions);
862 $mform->hideIf($scalefieldname, $assessedfieldname, 'eq', 0);
863 $mform->addHelpButton($scalefieldname, 'modgrade', 'grades');
864 $mform->setDefault($scalefieldname, $CFG->gradepointdefault);
866 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
867 $mform->hideIf('ratingtime', $assessedfieldname, 'eq', 0);
869 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
870 $mform->hideIf('assesstimestart', $assessedfieldname, 'eq', 0);
871 $mform->hideIf('assesstimestart', 'ratingtime');
873 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
874 $mform->hideIf('assesstimefinish', $assessedfieldname, 'eq', 0);
875 $mform->hideIf('assesstimefinish', 'ratingtime');
877 if ($this->_features->gradecat) {
878 $mform->addElement(
879 'select',
880 $gradecatfieldname,
881 get_string('gradecategoryonmodform', 'grades'),
882 grade_get_categories_menu($COURSE->id, $this->_outcomesused)
884 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
885 $mform->hideIf($gradecatfieldname, $assessedfieldname, 'eq', 0);
886 $mform->hideIf($gradecatfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
889 // Grade to pass.
890 $mform->addElement('text', $gradepassfieldname, get_string('gradepass', 'grades'));
891 $mform->addHelpButton($gradepassfieldname, 'gradepass', 'grades');
892 $mform->setDefault($gradepassfieldname, '');
893 $mform->setType($gradepassfieldname, PARAM_RAW);
894 $mform->hideIf($gradepassfieldname, $assessedfieldname, 'eq', '0');
895 $mform->hideIf($gradepassfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
899 * Plugins can extend the coursemodule settings form.
901 protected function plugin_extend_coursemodule_standard_elements() {
902 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
903 foreach ($callbacks as $type => $plugins) {
904 foreach ($plugins as $plugin => $pluginfunction) {
905 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
906 // directly.
907 $pluginfunction($this, $this->_form);
913 * Can be overridden to add custom completion rules if the module wishes
914 * them. If overriding this, you should also override completion_rule_enabled.
915 * <p>
916 * Just add elements to the form as needed and return the list of IDs. The
917 * system will call disabledIf and handle other behaviour for each returned
918 * ID.
919 * @return array Array of string IDs of added items, empty array if none
921 function add_completion_rules() {
922 return array();
926 * Called during validation. Override to indicate, based on the data, whether
927 * a custom completion rule is enabled (selected).
929 * @param array $data Input data (not yet validated)
930 * @return bool True if one or more rules is enabled, false if none are;
931 * default returns false
933 function completion_rule_enabled($data) {
934 return false;
937 function standard_hidden_coursemodule_elements(){
938 $mform =& $this->_form;
939 $mform->addElement('hidden', 'course', 0);
940 $mform->setType('course', PARAM_INT);
942 $mform->addElement('hidden', 'coursemodule', 0);
943 $mform->setType('coursemodule', PARAM_INT);
945 $mform->addElement('hidden', 'section', 0);
946 $mform->setType('section', PARAM_INT);
948 $mform->addElement('hidden', 'module', 0);
949 $mform->setType('module', PARAM_INT);
951 $mform->addElement('hidden', 'modulename', '');
952 $mform->setType('modulename', PARAM_PLUGIN);
954 $mform->addElement('hidden', 'instance', 0);
955 $mform->setType('instance', PARAM_INT);
957 $mform->addElement('hidden', 'add', 0);
958 $mform->setType('add', PARAM_ALPHANUM);
960 $mform->addElement('hidden', 'update', 0);
961 $mform->setType('update', PARAM_INT);
963 $mform->addElement('hidden', 'return', 0);
964 $mform->setType('return', PARAM_BOOL);
966 $mform->addElement('hidden', 'sr', 0);
967 $mform->setType('sr', PARAM_INT);
970 public function standard_grading_coursemodule_elements() {
971 global $COURSE, $CFG;
973 if ($this->gradedorrated && $this->gradedorrated !== 'graded') {
974 return;
976 if ($this->_features->rating) {
977 return;
979 $this->gradedorrated = 'graded';
981 $itemnumber = 0;
982 $component = "mod_{$this->_modname}";
983 $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
984 $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
985 $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
987 $mform =& $this->_form;
988 $isupdate = !empty($this->_cm);
989 $gradeoptions = array('isupdate' => $isupdate,
990 'currentgrade' => false,
991 'hasgrades' => false,
992 'canrescale' => $this->_features->canrescale,
993 'useratings' => $this->_features->rating);
995 if ($this->_features->hasgrades) {
996 if ($this->_features->gradecat) {
997 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
1000 //if supports grades and grades arent being handled via ratings
1001 if ($isupdate) {
1002 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
1003 'itemmodule' => $this->_cm->modname,
1004 'iteminstance' => $this->_cm->instance,
1005 'itemnumber' => 0,
1006 'courseid' => $COURSE->id));
1007 if ($gradeitem) {
1008 $gradeoptions['currentgrade'] = $gradeitem->grademax;
1009 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
1010 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
1011 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
1014 $mform->addElement('modgrade', $gradefieldname, get_string('grade'), $gradeoptions);
1015 $mform->addHelpButton($gradefieldname, 'modgrade', 'grades');
1016 $mform->setDefault($gradefieldname, $CFG->gradepointdefault);
1018 if ($this->_features->advancedgrading
1019 and !empty($this->current->_advancedgradingdata['methods'])
1020 and !empty($this->current->_advancedgradingdata['areas'])) {
1022 if (count($this->current->_advancedgradingdata['areas']) == 1) {
1023 // if there is just one gradable area (most cases), display just the selector
1024 // without its name to make UI simplier
1025 $areadata = reset($this->current->_advancedgradingdata['areas']);
1026 $areaname = key($this->current->_advancedgradingdata['areas']);
1027 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
1028 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
1029 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
1030 $mform->hideIf('advancedgradingmethod_'.$areaname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1032 } else {
1033 // the module defines multiple gradable areas, display a selector
1034 // for each of them together with a name of the area
1035 $areasgroup = array();
1036 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
1037 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
1038 $areadata['title'], $this->current->_advancedgradingdata['methods']);
1039 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
1041 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
1042 array(' ', '<br />'), false);
1046 if ($this->_features->gradecat) {
1047 $mform->addElement('select', $gradecatfieldname,
1048 get_string('gradecategoryonmodform', 'grades'),
1049 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
1050 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
1051 $mform->hideIf($gradecatfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1054 // Grade to pass.
1055 $mform->addElement('text', $gradepassfieldname, get_string($gradepassfieldname, 'grades'));
1056 $mform->addHelpButton($gradepassfieldname, $gradepassfieldname, 'grades');
1057 $mform->setDefault($gradepassfieldname, '');
1058 $mform->setType($gradepassfieldname, PARAM_RAW);
1059 $mform->hideIf($gradepassfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
1064 * Add an editor for an activity's introduction field.
1065 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
1066 * @param null $required Override system default for requiremodintro
1067 * @param null $customlabel Override default label for editor
1068 * @throws coding_exception
1070 protected function add_intro_editor($required=null, $customlabel=null) {
1071 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
1072 debugging($str, DEBUG_DEVELOPER);
1074 $this->standard_intro_elements($customlabel);
1079 * Add an editor for an activity's introduction field.
1081 * @param null $customlabel Override default label for editor
1082 * @throws coding_exception
1084 protected function standard_intro_elements($customlabel=null) {
1085 global $CFG;
1087 $required = $CFG->requiremodintro;
1089 $mform = $this->_form;
1090 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
1092 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
1093 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
1094 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
1095 if ($required) {
1096 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
1099 // If the 'show description' feature is enabled, this checkbox appears below the intro.
1100 // We want to hide that when using the singleactivity course format because it is confusing.
1101 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
1102 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
1103 $mform->addHelpButton('showdescription', 'showdescription');
1108 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
1110 * @param bool $cancel show cancel button
1111 * @param string $submitlabel null means default, false means none, string is label text
1112 * @param string $submit2label null means default, false means none, string is label text
1113 * @return void
1115 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
1116 if (is_null($submitlabel)) {
1117 $submitlabel = get_string('savechangesanddisplay');
1120 if (is_null($submit2label)) {
1121 $submit2label = get_string('savechangesandreturntocourse');
1124 $mform = $this->_form;
1126 // elements in a row need a group
1127 $buttonarray = array();
1129 // Label for the submit button to return to the course.
1130 // Ignore this button in single activity format because it is confusing.
1131 if ($submit2label !== false && $this->courseformat->has_view_page()) {
1132 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
1135 if ($submitlabel !== false) {
1136 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1139 if ($cancel) {
1140 $buttonarray[] = &$mform->createElement('cancel');
1143 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1144 $mform->setType('buttonar', PARAM_RAW);
1145 $mform->closeHeaderBefore('buttonar');
1149 * Get the list of admin settings for this module and apply any locked settings.
1150 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
1151 * in that function because set_data has not been called yet.
1153 * @return void
1155 protected function apply_admin_locked_flags() {
1156 global $OUTPUT;
1158 if (!$this->applyadminlockedflags) {
1159 return;
1162 $settings = get_config($this->_modname);
1163 $mform = $this->_form;
1164 $lockedicon = html_writer::tag('span',
1165 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1166 array('class' => 'action-icon'));
1167 $isupdate = !empty($this->_cm);
1169 foreach ($settings as $name => $value) {
1170 if (strpos('_', $name) !== false) {
1171 continue;
1173 if ($mform->elementExists($name)) {
1174 $element = $mform->getElement($name);
1175 $lockedsetting = $name . '_locked';
1176 if (!empty($settings->$lockedsetting)) {
1177 // Always lock locked settings for new modules,
1178 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1179 $value = $settings->$name;
1180 if ($isupdate && isset($this->current->$name)) {
1181 $value = $this->current->$name;
1183 if ($value == $settings->$name) {
1184 $mform->setConstant($name, $settings->$name);
1185 $element->setLabel($element->getLabel() . $lockedicon);
1186 // Do not use hardfreeze because we need the hidden input to check dependencies.
1187 $element->freeze();
1195 * Get the list of admin settings for this module and apply any defaults/advanced/locked/required settings.
1197 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1198 * default date/time value should be relative to. If not passed, all
1199 * date/time fields are set relative to the users current midnight.
1200 * @return void
1202 public function apply_admin_defaults($datetimeoffsets = array()) {
1203 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1204 $this->applyadminlockedflags = true;
1206 $settings = get_config($this->_modname);
1207 $mform = $this->_form;
1208 $usermidnight = usergetmidnight(time());
1209 $isupdate = !empty($this->_cm);
1211 foreach ($settings as $name => $value) {
1212 if (strpos('_', $name) !== false) {
1213 continue;
1215 if ($mform->elementExists($name)) {
1216 $element = $mform->getElement($name);
1217 if (!$isupdate) {
1218 if ($element->getType() == 'date_time_selector') {
1219 $enabledsetting = $name . '_enabled';
1220 if (empty($settings->$enabledsetting)) {
1221 $mform->setDefault($name, 0);
1222 } else {
1223 $relativetime = $usermidnight;
1224 if (isset($datetimeoffsets[$name])) {
1225 $relativetime = $datetimeoffsets[$name];
1227 $mform->setDefault($name, $relativetime + $settings->$name);
1229 } else {
1230 $mform->setDefault($name, $settings->$name);
1233 $advancedsetting = $name . '_adv';
1234 if (!empty($settings->$advancedsetting)) {
1235 $mform->setAdvanced($name);
1237 $requiredsetting = $name . '_required';
1238 if (!empty($settings->$requiredsetting)) {
1239 $mform->addRule($name, null, 'required', null, 'client');
1246 * Allows modules to modify the data returned by form get_data().
1247 * This method is also called in the bulk activity completion form.
1249 * Only available on moodleform_mod.
1251 * @param stdClass $data passed by reference
1253 public function data_postprocessing($data) {
1257 * Return submitted data if properly submitted or returns NULL if validation fails or
1258 * if there is no submitted data.
1260 * Do not override this method, override data_postprocessing() instead.
1262 * @return object submitted data; NULL if not valid or not submitted or cancelled
1264 public function get_data() {
1265 $data = parent::get_data();
1266 if ($data) {
1267 // Convert the grade pass value - we may be using a language which uses commas,
1268 // rather than decimal points, in numbers. These need to be converted so that
1269 // they can be added to the DB.
1270 if (isset($data->gradepass)) {
1271 $data->gradepass = unformat_float($data->gradepass);
1274 $this->data_postprocessing($data);
1276 return $data;