MDL-66079 core_grades: Add support for multiple grade items in an activity
[moodle.git] / course / moodleform_mod.php
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.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Moodleform.
19  *
20  * @package   core_course
21  * @copyright Andrew Nicols <andrew@nicols.co.uk>
22  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
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.
35  *
36  * @package   core_course
37  * @copyright Andrew Nicols <andrew@nicols.co.uk>
38  */
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.
46      *
47      * @var mixed
48      */
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).
53      *
54      * @var int
55      */
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.
60       *
61      * @var mixed
62      */
63     protected $_cm;
65     /**
66      * Current course.
67      *
68      * @var mixed
69      */
70     protected $_course;
72     /**
73      * List of modform features
74      */
75     protected $_features;
76     /**
77      * @var array Custom completion-rule elements, if enabled
78      */
79     protected $_customcompletionelements;
80     /**
81      * @var string name of module.
82      */
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.
93      */
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);
114         }
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');
126             }
127             $this->_modname = $matches[1];
128         }
129         $this->init_features();
130         parent::__construct('modedit.php');
131     }
133     /**
134      * Old syntax of class constructor. Deprecated in PHP7.
135      *
136      * @deprecated since Moodle 3.1
137      */
138     public function moodleform_mod($current, $section, $cm, $course) {
139         debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
140         self::__construct($current, $section, $cm, $course);
141     }
143     /**
144      * Get the current data for the form.
145      * @return stdClass|null
146      */
147     public function get_current() {
148         return $this->current;
149     }
151     /**
152      * Get the DB record for the current instance.
153      * @return stdClass|null
154      */
155     public function get_instance() {
156         return $this->_instance;
157     }
159     /**
160      * Get the course section number (relative).
161      * @return int
162      */
163     public function get_section() {
164         return $this->_section;
165     }
167     /**
168      * Get the course id.
169      * @return int
170      */
171     public function get_course() {
172         return $this->_course;
173     }
175     /**
176      * Get the course module object.
177      * @return stdClass|null
178      */
179     public function get_coursemodule() {
180         return $this->_cm;
181     }
183     /**
184      * Return the course context for new modules, or the module context for existing modules.
185      * @return context
186      */
187     public function get_context() {
188         return $this->context;
189     }
191     /**
192      * Return the features this module supports.
193      * @return stdClass
194      */
195     public function get_features() {
196         return $this->_features;
197     }
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);
216     }
218     /**
219      * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
220      * This method is also called in the bulk activity completion form.
221      *
222      * Only available on moodleform_mod.
223      *
224      * @param array $default_values passed by reference
225      */
226     function data_preprocessing(&$default_values){
227         if (empty($default_values['scale'])) {
228             $default_values['assessed'] = 0;
229         }
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;
236         }
237     }
239     /**
240      * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
241      */
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,
258                 ]);
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
269                             }
270                         } else {
271                             $hasgradeitems = true;
272                         }
273                     }
275                     foreach ($items as $item) {
276                         $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber(
277                             $component,
278                             $item->itemnumber,
279                             'gradecat'
280                         );
282                         if (!isset($gradecategories[$gradecatfieldname])) {
283                             $gradecategories[$gradecatfieldname] = $item->categoryid;
284                         } else if ($gradecategories[$gradecatfieldname] != $item->categoryid) {
285                             $removecategories[$gradecatfieldname] = true;
286                         }
287                     }
288                 }
290                 foreach ($removecategories as $toremove) {
291                     if ($mform->elementExists($toremove)) {
292                         $mform->removeElement($toremove);
293                     }
294                 }
295             }
296         }
298         if ($COURSE->groupmodeforce) {
299             if ($mform->elementExists('groupmode')) {
300                 // The groupmode can not be changed if forced from course settings.
301                 //
302                 $mform->hardFreeze('groupmode');
303             }
304         }
306         // Don't disable/remove groupingid if it is currently set to something, otherwise you cannot turn it off at same
307         // time as turning off other option (MDL-30764).
308         if (empty($this->_cm) || !$this->_cm->groupingid) {
309             if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
310                 $mform->hideIf('groupingid', 'groupmode', 'eq', NOGROUPS);
312             } else if (!$mform->elementExists('groupmode')) {
313                 // Groupings have no use without groupmode.
314                 if ($mform->elementExists('groupingid')) {
315                     $mform->removeElement('groupingid');
316                 }
317                 // Nor does the group restrictions button.
318                 if ($mform->elementExists('restrictgroupbutton')) {
319                     $mform->removeElement('restrictgroupbutton');
320                 }
321             }
322         }
324         // Completion: If necessary, freeze fields
325         $completion = new completion_info($COURSE);
326         if ($completion->is_enabled()) {
327             // If anybody has completed the activity, these options will be 'locked'
328             $completedcount = empty($this->_cm)
329                 ? 0
330                 : $completion->count_user_data($this->_cm);
332             $freeze = false;
333             if (!$completedcount) {
334                 if ($mform->elementExists('unlockcompletion')) {
335                     $mform->removeElement('unlockcompletion');
336                 }
337                 // Automatically set to unlocked (note: this is necessary
338                 // in order to make it recalculate completion once the option
339                 // is changed, maybe someone has completed it now)
340                 $mform->getElement('completionunlocked')->setValue(1);
341             } else {
342                 // Has the element been unlocked, either by the button being pressed
343                 // in this request, or the field already being set from a previous one?
344                 if ($mform->exportValue('unlockcompletion') ||
345                         $mform->exportValue('completionunlocked')) {
346                     // Yes, add in warning text and set the hidden variable
347                     $mform->insertElementBefore(
348                         $mform->createElement('static', 'completedunlocked',
349                             get_string('completedunlocked', 'completion'),
350                             get_string('completedunlockedtext', 'completion')),
351                         'unlockcompletion');
352                     $mform->removeElement('unlockcompletion');
353                     $mform->getElement('completionunlocked')->setValue(1);
354                 } else {
355                     // No, add in the warning text with the count (now we know
356                     // it) before the unlock button
357                     $mform->insertElementBefore(
358                         $mform->createElement('static', 'completedwarning',
359                             get_string('completedwarning', 'completion'),
360                             get_string('completedwarningtext', 'completion', $completedcount)),
361                         'unlockcompletion');
362                     $freeze = true;
363                 }
364             }
366             if ($freeze) {
367                 $mform->freeze('completion');
368                 if ($mform->elementExists('completionview')) {
369                     $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
370                 }
371                 if ($mform->elementExists('completionusegrade')) {
372                     $mform->freeze('completionusegrade');
373                 }
374                 $mform->freeze($this->_customcompletionelements);
375             }
376         }
378         // Freeze admin defaults if required (and not different from default)
379         $this->apply_admin_locked_flags();
380     }
382     // form verification
383     function validation($data, $files) {
384         global $COURSE, $DB, $CFG;
385         $errors = parent::validation($data, $files);
387         $mform =& $this->_form;
389         $errors = array();
391         if ($mform->elementExists('name')) {
392             $name = trim($data['name']);
393             if ($name == '') {
394                 $errors['name'] = get_string('required');
395             }
396         }
398         $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
399                      'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
400         if ($data['coursemodule']) {
401             $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
402         } else {
403             $cm = null;
404         }
406         if ($mform->elementExists('cmidnumber')) {
407             // verify the idnumber
408             if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
409                 $errors['cmidnumber'] = get_string('idnumbertaken');
410             }
411         }
413         $component = "mod_{$this->_modname}";
414         $itemnames = component_gradeitems::get_itemname_mapping_for_component($component);
415         foreach ($itemnames as $itemnumber => $itemname) {
416             $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
417             $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
418             $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
419             $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
421             // Ratings: Don't let them select an aggregate type without selecting a scale.
422             // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
423             // invalid. If ratings have been selected then the user must select either a scale or max points.
424             // This matches (horrible) logic in data_preprocessing.
425             if (isset($data[$assessedfieldname]) && $data[$assessedfieldname] > 0 && empty($data[$scalefieldname])) {
426                 $errors[$assessedfieldname] = get_string('scaleselectionrequired', 'rating');
427             }
429             // Check that the grade pass is a valid number.
430             $gradepassvalid = false;
431             if (isset($data[$gradepassfieldname])) {
432                 if (unformat_float($data[$gradepassfieldname], true) === false) {
433                     $errors[$gradepassfieldname] = get_string('err_numeric', 'form');
434                 } else {
435                     $gradepassvalid = true;
436                 }
437             }
439             // Grade to pass: ensure that the grade to pass is valid for points and scales.
440             // If we are working with a scale, convert into a positive number for validation.
441             if ($gradepassvalid && isset($data[$gradepassfieldname]) && (!empty($data[$gradefieldname]) || !empty($data[$scalefieldname]))) {
442                 $scale = !empty($data[$gradefieldname]) ? $data[$gradefieldname] : $data[$scalefieldname];
443                 if ($scale < 0) {
444                     $scalevalues = $DB->get_record('scale', array('id' => -$scale));
445                     $grade = count(explode(',', $scalevalues->scale));
446                 } else {
447                     $grade = $scale;
448                 }
449                 if (unformat_float($data[$gradepassfieldname]) > $grade) {
450                     $errors[$gradepassfieldname] = get_string('gradepassgreaterthangrade', 'grades', $grade);
451                 }
452             }
453         }
455         // Completion: Don't let them choose automatic completion without turning
456         // on some conditions. Ignore this check when completion settings are
457         // locked, as the options are then disabled.
458         if (array_key_exists('completion', $data) &&
459                 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
460                 !empty($data['completionunlocked'])) {
461             if (empty($data['completionview']) && empty($data['completionusegrade']) &&
462                 !$this->completion_rule_enabled($data)) {
463                 $errors['completion'] = get_string('badautocompletion', 'completion');
464             }
465         }
467         // Availability: Check availability field does not have errors.
468         if (!empty($CFG->enableavailability)) {
469             \core_availability\frontend::report_validation_errors($data, $errors);
470         }
472         $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
473         if (!empty($pluginerrors)) {
474             $errors = array_merge($errors, $pluginerrors);
475         }
477         return $errors;
478     }
480     /**
481      * Extend the validation function from any other plugin.
482      *
483      * @param stdClass $data The form data.
484      * @return array $errors The list of errors keyed by element name.
485      */
486     protected function plugin_extend_coursemodule_validation($data) {
487         $errors = array();
489         $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
490         foreach ($callbacks as $type => $plugins) {
491             foreach ($plugins as $plugin => $pluginfunction) {
492                 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
493                 $pluginerrors = $pluginfunction($this, $data);
494                 if (!empty($pluginerrors)) {
495                     $errors = array_merge($errors, $pluginerrors);
496                 }
497             }
498         }
499         return $errors;
500     }
502     /**
503      * Load in existing data as form defaults. Usually new entry defaults are stored directly in
504      * form definition (new entry form); this function is used to load in data where values
505      * already exist and data is being edited (edit entry form).
506      *
507      * @param mixed $default_values object or array of default values
508      */
509     function set_data($default_values) {
510         if (is_object($default_values)) {
511             $default_values = (array)$default_values;
512         }
514         $this->data_preprocessing($default_values);
515         parent::set_data($default_values);
516     }
518     /**
519      * Adds all the standard elements to a form to edit the settings for an activity module.
520      */
521     protected function standard_coursemodule_elements() {
522         global $COURSE, $CFG, $DB;
523         $mform =& $this->_form;
525         $this->_outcomesused = false;
526         if ($this->_features->outcomes) {
527             if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
528                 $this->_outcomesused = true;
529                 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
530                 foreach($outcomes as $outcome) {
531                     $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
532                 }
533             }
534         }
536         if ($this->_features->rating) {
537             $this->add_rating_settings($mform, 0);
538         }
540         $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
542         $section = get_fast_modinfo($COURSE)->get_section_info($this->_section);
543         $allowstealth = !empty($CFG->allowstealth) && $this->courseformat->allow_stealth_module_visibility($this->_cm, $section);
544         if ($allowstealth && $section->visible) {
545             $modvisiblelabel = 'modvisiblewithstealth';
546         } else if ($section->visible) {
547             $modvisiblelabel = 'modvisible';
548         } else {
549             $modvisiblelabel = 'modvisiblehiddensection';
550         }
551         $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
552                 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible, 'cm' => $this->_cm));
553         $mform->addHelpButton('visible', $modvisiblelabel);
554         if (!empty($this->_cm)) {
555             $context = context_module::instance($this->_cm->id);
556             if (!has_capability('moodle/course:activityvisibility', $context)) {
557                 $mform->hardFreeze('visible');
558             }
559         }
561         if ($this->_features->idnumber) {
562             $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
563             $mform->setType('cmidnumber', PARAM_RAW);
564             $mform->addHelpButton('cmidnumber', 'idnumbermod');
565         }
567         if ($this->_features->groups) {
568             $options = array(NOGROUPS       => get_string('groupsnone'),
569                              SEPARATEGROUPS => get_string('groupsseparate'),
570                              VISIBLEGROUPS  => get_string('groupsvisible'));
571             $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
572             $mform->addHelpButton('groupmode', 'groupmode', 'group');
573         }
575         if ($this->_features->groupings) {
576             // Groupings selector - used to select grouping for groups in activity.
577             $options = array();
578             if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
579                 foreach ($groupings as $grouping) {
580                     $options[$grouping->id] = format_string($grouping->name);
581                 }
582             }
583             core_collator::asort($options);
584             $options = array(0 => get_string('none')) + $options;
585             $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
586             $mform->addHelpButton('groupingid', 'grouping', 'group');
587         }
589         if (!empty($CFG->enableavailability)) {
590             // Add special button to end of previous section if groups/groupings
591             // are enabled.
592             if ($this->_features->groups || $this->_features->groupings) {
593                 $mform->addElement('static', 'restrictgroupbutton', '',
594                         html_writer::tag('button', get_string('restrictbygroup', 'availability'),
595                         array('id' => 'restrictbygroup', 'disabled' => 'disabled', 'class' => 'btn btn-secondary')));
596             }
598             // Availability field. This is just a textarea; the user interface
599             // interaction is all implemented in JavaScript.
600             $mform->addElement('header', 'availabilityconditionsheader',
601                     get_string('restrictaccess', 'availability'));
602             // Note: This field cannot be named 'availability' because that
603             // conflicts with fields in existing modules (such as assign).
604             // So it uses a long name that will not conflict.
605             $mform->addElement('textarea', 'availabilityconditionsjson',
606                     get_string('accessrestrictions', 'availability'));
607             // The _cm variable may not be a proper cm_info, so get one from modinfo.
608             if ($this->_cm) {
609                 $modinfo = get_fast_modinfo($COURSE);
610                 $cm = $modinfo->get_cm($this->_cm->id);
611             } else {
612                 $cm = null;
613             }
614             \core_availability\frontend::include_all_javascript($COURSE, $cm);
615         }
617         // Conditional activities: completion tracking section
618         if(!isset($completion)) {
619             $completion = new completion_info($COURSE);
620         }
621         if ($completion->is_enabled()) {
622             $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
623             // Unlock button for if people have completed it (will
624             // be removed in definition_after_data if they haven't)
625             $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
626             $mform->registerNoSubmitButton('unlockcompletion');
627             $mform->addElement('hidden', 'completionunlocked', 0);
628             $mform->setType('completionunlocked', PARAM_INT);
630             $trackingdefault = COMPLETION_TRACKING_NONE;
631             // If system and activity default is on, set it.
632             if ($CFG->completiondefault && $this->_features->defaultcompletion) {
633                 $hasrules = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_HAS_RULES, true);
634                 $tracksviews = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, true);
635                 if ($hasrules || $tracksviews) {
636                     $trackingdefault = COMPLETION_TRACKING_AUTOMATIC;
637                 } else {
638                     $trackingdefault = COMPLETION_TRACKING_MANUAL;
639                 }
640             }
642             $mform->addElement('select', 'completion', get_string('completion', 'completion'),
643                 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
644                 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
645             $mform->setDefault('completion', $trackingdefault);
646             $mform->addHelpButton('completion', 'completion', 'completion');
648             // Automatic completion once you view it
649             $gotcompletionoptions = false;
650             if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
651                 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
652                     get_string('completionview_desc', 'completion'));
653                 $mform->hideIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
654                 // Check by default if automatic completion tracking is set.
655                 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC) {
656                     $mform->setDefault('completionview', 1);
657                 }
658                 $gotcompletionoptions = true;
659             }
661             // Automatic completion once it's graded
662             if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
663                 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
664                     get_string('completionusegrade_desc', 'completion'));
665                 $mform->hideIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
666                 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
667                 $gotcompletionoptions = true;
669                 // If using the rating system, there is no grade unless ratings are enabled.
670                 if ($this->_features->rating) {
671                     $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
672                 }
673             }
675             // Automatic completion according to module-specific rules
676             $this->_customcompletionelements = $this->add_completion_rules();
677             foreach ($this->_customcompletionelements as $element) {
678                 $mform->hideIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
679             }
681             $gotcompletionoptions = $gotcompletionoptions ||
682                 count($this->_customcompletionelements)>0;
684             // Automatic option only appears if possible
685             if ($gotcompletionoptions) {
686                 $mform->getElement('completion')->addOption(
687                     get_string('completion_automatic', 'completion'),
688                     COMPLETION_TRACKING_AUTOMATIC);
689             }
691             // Completion expected at particular date? (For progress tracking)
692             $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
693                     array('optional' => true));
694             $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
695             $mform->hideIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
696         }
698         // Populate module tags.
699         if (core_tag_tag::is_enabled('core', 'course_modules')) {
700             $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
701             $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
702             if ($this->_cm) {
703                 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
704                 $mform->setDefault('tags', $tags);
705             }
706         }
708         $this->standard_hidden_coursemodule_elements();
710         $this->plugin_extend_coursemodule_standard_elements();
711     }
713     /**
714      * Add rating settings.
715      *
716      * @param moodleform_mod $mform
717      * @param int $itemnumber
718      */
719     protected function add_rating_settings($mform, int $itemnumber) {
720         global $CFG, $COURSE;
722         if ($this->gradedorrated && $this->gradedorrated !== 'rated') {
723             return;
724         }
725         $this->gradedorrated = 'rated';
727         require_once("{$CFG->dirroot}/rating/lib.php");
728         $rm = new rating_manager();
730         $component = "mod_{$this->_modname}";
731         $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
732         $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
733         $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
734         $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
736         $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
738         $isupdate = !empty($this->_cm);
740         $rolenamestring = null;
741         if ($isupdate) {
742             $context = context_module::instance($this->_cm->id);
743             $capabilities = ['moodle/rating:rate', "mod/{$this->_cm->modname}:rate"];
744             $rolenames = get_role_names_with_caps_in_context($context, $capabilities);
745             $rolenamestring = implode(', ', $rolenames);
746         } else {
747             $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
748         }
750         $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
751         $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
753         $mform->addElement('select', $assessedfieldname, get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
754         $mform->setDefault($assessedfieldname, 0);
755         $mform->addHelpButton($assessedfieldname, 'aggregatetype', 'rating');
757         $gradeoptions = [
758             'isupdate' => $isupdate,
759             'currentgrade' => false,
760             'hasgrades' => false,
761             'canrescale' => false,
762             'useratings' => true,
763         ];
764         if ($isupdate) {
765             $gradeitem = grade_item::fetch([
766                 'itemtype' => 'mod',
767                 'itemmodule' => $this->_cm->modname,
768                 'iteminstance' => $this->_cm->instance,
769                 'itemnumber' => $itemnumber,
770                 'courseid' => $COURSE->id,
771             ]);
772             if ($gradeitem) {
773                 $gradeoptions['currentgrade'] = $gradeitem->grademax;
774                 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
775                 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
776                 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
777             }
778         }
780         $mform->addElement('modgrade', $scalefieldname, get_string('scale'), $gradeoptions);
781         $mform->hideIf($scalefieldname, $assessedfieldname, 'eq', 0);
782         $mform->addHelpButton($scalefieldname, 'modgrade', 'grades');
783         $mform->setDefault($scalefieldname, $CFG->gradepointdefault);
785         $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
786         $mform->hideIf('ratingtime', $assessedfieldname, 'eq', 0);
788         $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
789         $mform->hideIf('assesstimestart', $assessedfieldname, 'eq', 0);
790         $mform->hideIf('assesstimestart', 'ratingtime');
792         $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
793         $mform->hideIf('assesstimefinish', $assessedfieldname, 'eq', 0);
794         $mform->hideIf('assesstimefinish', 'ratingtime');
796         if ($this->_features->gradecat) {
797             $mform->addElement(
798                 'select',
799                 $gradecatfieldname,
800                 get_string('gradecategoryonmodform', 'grades'),
801                 grade_get_categories_menu($COURSE->id, $this->_outcomesused)
802             );
803             $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
804             $mform->hideIf($gradecatfieldname, $assessedfieldname, 'eq', 0);
805             $mform->hideIf($gradecatfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
806         }
808         // Grade to pass.
809         $mform->addElement('text', $gradepassfieldname, get_string('gradepass', 'grades'));
810         $mform->addHelpButton($gradepassfieldname, 'gradepass', 'grades');
811         $mform->setDefault($gradepassfieldname, '');
812         $mform->setType($gradepassfieldname, PARAM_RAW);
813         $mform->hideIf($gradepassfieldname, $assessedfieldname, 'eq', '0');
814         $mform->hideIf($gradepassfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
815     }
817     /**
818      * Plugins can extend the coursemodule settings form.
819      */
820     protected function plugin_extend_coursemodule_standard_elements() {
821         $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
822         foreach ($callbacks as $type => $plugins) {
823             foreach ($plugins as $plugin => $pluginfunction) {
824                 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
825                 // directly.
826                 $pluginfunction($this, $this->_form);
827             }
828         }
829     }
831     /**
832      * Can be overridden to add custom completion rules if the module wishes
833      * them. If overriding this, you should also override completion_rule_enabled.
834      * <p>
835      * Just add elements to the form as needed and return the list of IDs. The
836      * system will call disabledIf and handle other behaviour for each returned
837      * ID.
838      * @return array Array of string IDs of added items, empty array if none
839      */
840     function add_completion_rules() {
841         return array();
842     }
844     /**
845      * Called during validation. Override to indicate, based on the data, whether
846      * a custom completion rule is enabled (selected).
847      *
848      * @param array $data Input data (not yet validated)
849      * @return bool True if one or more rules is enabled, false if none are;
850      *   default returns false
851      */
852     function completion_rule_enabled($data) {
853         return false;
854     }
856     function standard_hidden_coursemodule_elements(){
857         $mform =& $this->_form;
858         $mform->addElement('hidden', 'course', 0);
859         $mform->setType('course', PARAM_INT);
861         $mform->addElement('hidden', 'coursemodule', 0);
862         $mform->setType('coursemodule', PARAM_INT);
864         $mform->addElement('hidden', 'section', 0);
865         $mform->setType('section', PARAM_INT);
867         $mform->addElement('hidden', 'module', 0);
868         $mform->setType('module', PARAM_INT);
870         $mform->addElement('hidden', 'modulename', '');
871         $mform->setType('modulename', PARAM_PLUGIN);
873         $mform->addElement('hidden', 'instance', 0);
874         $mform->setType('instance', PARAM_INT);
876         $mform->addElement('hidden', 'add', 0);
877         $mform->setType('add', PARAM_ALPHA);
879         $mform->addElement('hidden', 'update', 0);
880         $mform->setType('update', PARAM_INT);
882         $mform->addElement('hidden', 'return', 0);
883         $mform->setType('return', PARAM_BOOL);
885         $mform->addElement('hidden', 'sr', 0);
886         $mform->setType('sr', PARAM_INT);
887     }
889     public function standard_grading_coursemodule_elements() {
890         global $COURSE, $CFG;
892         if ($this->gradedorrated && $this->gradedorrated !== 'graded') {
893             return;
894         }
895         if ($this->_features->rating) {
896             return;
897         }
898         $this->gradedorrated = 'graded';
900         $itemnumber = 0;
901         $component = "mod_{$this->_modname}";
902         $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
903         $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
904         $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
906         $mform =& $this->_form;
907         $isupdate = !empty($this->_cm);
908         $gradeoptions = array('isupdate' => $isupdate,
909                               'currentgrade' => false,
910                               'hasgrades' => false,
911                               'canrescale' => $this->_features->canrescale,
912                               'useratings' => $this->_features->rating);
914         if ($this->_features->hasgrades) {
915             if ($this->_features->gradecat) {
916                 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
917             }
919             //if supports grades and grades arent being handled via ratings
920             if ($isupdate) {
921                 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
922                                                         'itemmodule' => $this->_cm->modname,
923                                                         'iteminstance' => $this->_cm->instance,
924                                                         'itemnumber' => 0,
925                                                         'courseid' => $COURSE->id));
926                 if ($gradeitem) {
927                     $gradeoptions['currentgrade'] = $gradeitem->grademax;
928                     $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
929                     $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
930                     $gradeoptions['hasgrades'] = $gradeitem->has_grades();
931                 }
932             }
933             $mform->addElement('modgrade', $gradefieldname, get_string('grade'), $gradeoptions);
934             $mform->addHelpButton($gradefieldname, 'modgrade', 'grades');
935             $mform->setDefault($gradefieldname, $CFG->gradepointdefault);
937             if ($this->_features->advancedgrading
938                     and !empty($this->current->_advancedgradingdata['methods'])
939                     and !empty($this->current->_advancedgradingdata['areas'])) {
941                 if (count($this->current->_advancedgradingdata['areas']) == 1) {
942                     // if there is just one gradable area (most cases), display just the selector
943                     // without its name to make UI simplier
944                     $areadata = reset($this->current->_advancedgradingdata['areas']);
945                     $areaname = key($this->current->_advancedgradingdata['areas']);
946                     $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
947                         get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
948                     $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
949                     $mform->hideIf('advancedgradingmethod_'.$areaname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
951                 } else {
952                     // the module defines multiple gradable areas, display a selector
953                     // for each of them together with a name of the area
954                     $areasgroup = array();
955                     foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
956                         $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
957                             $areadata['title'], $this->current->_advancedgradingdata['methods']);
958                         $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
959                     }
960                     $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
961                         array(' ', '<br />'), false);
962                 }
963             }
965             if ($this->_features->gradecat) {
966                 $mform->addElement('select', $gradecatfieldname,
967                         get_string('gradecategoryonmodform', 'grades'),
968                         grade_get_categories_menu($COURSE->id, $this->_outcomesused));
969                 $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
970                 $mform->hideIf($gradecatfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
971             }
973             // Grade to pass.
974             $mform->addElement('text', $gradepassfieldname, get_string($gradepassfieldname, 'grades'));
975             $mform->addHelpButton($gradepassfieldname, $gradepassfieldname, 'grades');
976             $mform->setDefault($gradepassfieldname, '');
977             $mform->setType($gradepassfieldname, PARAM_RAW);
978             $mform->hideIf($gradepassfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
979         }
980     }
982     /**
983      * Add an editor for an activity's introduction field.
984      * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
985      * @param null $required Override system default for requiremodintro
986      * @param null $customlabel Override default label for editor
987      * @throws coding_exception
988      */
989     protected function add_intro_editor($required=null, $customlabel=null) {
990         $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
991         debugging($str, DEBUG_DEVELOPER);
993         $this->standard_intro_elements($customlabel);
994     }
997     /**
998      * Add an editor for an activity's introduction field.
999      *
1000      * @param null $customlabel Override default label for editor
1001      * @throws coding_exception
1002      */
1003     protected function standard_intro_elements($customlabel=null) {
1004         global $CFG;
1006         $required = $CFG->requiremodintro;
1008         $mform = $this->_form;
1009         $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
1011         $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
1012             'noclean' => true, 'context' => $this->context, 'subdirs' => true));
1013         $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
1014         if ($required) {
1015             $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
1016         }
1018         // If the 'show description' feature is enabled, this checkbox appears below the intro.
1019         // We want to hide that when using the singleactivity course format because it is confusing.
1020         if ($this->_features->showdescription  && $this->courseformat->has_view_page()) {
1021             $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
1022             $mform->addHelpButton('showdescription', 'showdescription');
1023         }
1024     }
1026     /**
1027      * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
1028      *
1029      * @param bool $cancel show cancel button
1030      * @param string $submitlabel null means default, false means none, string is label text
1031      * @param string $submit2label  null means default, false means none, string is label text
1032      * @return void
1033      */
1034     function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
1035         if (is_null($submitlabel)) {
1036             $submitlabel = get_string('savechangesanddisplay');
1037         }
1039         if (is_null($submit2label)) {
1040             $submit2label = get_string('savechangesandreturntocourse');
1041         }
1043         $mform = $this->_form;
1045         // elements in a row need a group
1046         $buttonarray = array();
1048         // Label for the submit button to return to the course.
1049         // Ignore this button in single activity format because it is confusing.
1050         if ($submit2label !== false && $this->courseformat->has_view_page()) {
1051             $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
1052         }
1054         if ($submitlabel !== false) {
1055             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1056         }
1058         if ($cancel) {
1059             $buttonarray[] = &$mform->createElement('cancel');
1060         }
1062         $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1063         $mform->setType('buttonar', PARAM_RAW);
1064         $mform->closeHeaderBefore('buttonar');
1065     }
1067     /**
1068      * Get the list of admin settings for this module and apply any locked settings.
1069      * This cannot happen in apply_admin_defaults because we do not the current values of the settings
1070      * in that function because set_data has not been called yet.
1071      *
1072      * @return void
1073      */
1074     protected function apply_admin_locked_flags() {
1075         global $OUTPUT;
1077         if (!$this->applyadminlockedflags) {
1078             return;
1079         }
1081         $settings = get_config($this->_modname);
1082         $mform = $this->_form;
1083         $lockedicon = html_writer::tag('span',
1084                                        $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1085                                        array('class' => 'action-icon'));
1086         $isupdate = !empty($this->_cm);
1088         foreach ($settings as $name => $value) {
1089             if (strpos('_', $name) !== false) {
1090                 continue;
1091             }
1092             if ($mform->elementExists($name)) {
1093                 $element = $mform->getElement($name);
1094                 $lockedsetting = $name . '_locked';
1095                 if (!empty($settings->$lockedsetting)) {
1096                     // Always lock locked settings for new modules,
1097                     // for updates, only lock them if the current value is the same as the default (or there is no current value).
1098                     $value = $settings->$name;
1099                     if ($isupdate && isset($this->current->$name)) {
1100                         $value = $this->current->$name;
1101                     }
1102                     if ($value == $settings->$name) {
1103                         $mform->setConstant($name, $settings->$name);
1104                         $element->setLabel($element->getLabel() . $lockedicon);
1105                         // Do not use hardfreeze because we need the hidden input to check dependencies.
1106                         $element->freeze();
1107                     }
1108                 }
1109             }
1110         }
1111     }
1113     /**
1114      * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
1115      *
1116      * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1117      *                         default date/time value should be relative to. If not passed, all
1118      *                         date/time fields are set relative to the users current midnight.
1119      * @return void
1120      */
1121     public function apply_admin_defaults($datetimeoffsets = array()) {
1122         // This flag triggers the settings to be locked in apply_admin_locked_flags().
1123         $this->applyadminlockedflags = true;
1125         $settings = get_config($this->_modname);
1126         $mform = $this->_form;
1127         $usermidnight = usergetmidnight(time());
1128         $isupdate = !empty($this->_cm);
1130         foreach ($settings as $name => $value) {
1131             if (strpos('_', $name) !== false) {
1132                 continue;
1133             }
1134             if ($mform->elementExists($name)) {
1135                 $element = $mform->getElement($name);
1136                 if (!$isupdate) {
1137                     if ($element->getType() == 'date_time_selector') {
1138                         $enabledsetting = $name . '_enabled';
1139                         if (empty($settings->$enabledsetting)) {
1140                             $mform->setDefault($name, 0);
1141                         } else {
1142                             $relativetime = $usermidnight;
1143                             if (isset($datetimeoffsets[$name])) {
1144                                 $relativetime = $datetimeoffsets[$name];
1145                             }
1146                             $mform->setDefault($name, $relativetime + $settings->$name);
1147                         }
1148                     } else {
1149                         $mform->setDefault($name, $settings->$name);
1150                     }
1151                 }
1152                 $advancedsetting = $name . '_adv';
1153                 if (!empty($settings->$advancedsetting)) {
1154                     $mform->setAdvanced($name);
1155                 }
1156             }
1157         }
1158     }
1160     /**
1161      * Allows modules to modify the data returned by form get_data().
1162      * This method is also called in the bulk activity completion form.
1163      *
1164      * Only available on moodleform_mod.
1165      *
1166      * @param stdClass $data passed by reference
1167      */
1168     public function data_postprocessing($data) {
1169     }
1171     /**
1172      * Return submitted data if properly submitted or returns NULL if validation fails or
1173      * if there is no submitted data.
1174      *
1175      * Do not override this method, override data_postprocessing() instead.
1176      *
1177      * @return object submitted data; NULL if not valid or not submitted or cancelled
1178      */
1179     public function get_data() {
1180         $data = parent::get_data();
1181         if ($data) {
1182             // Convert the grade pass value - we may be using a language which uses commas,
1183             // rather than decimal points, in numbers. These need to be converted so that
1184             // they can be added to the DB.
1185             if (isset($data->gradepass)) {
1186                 $data->gradepass = unformat_float($data->gradepass);
1187             }
1189             $this->data_postprocessing($data);
1190         }
1191         return $data;
1192     }