MDL-62950 behat: Correct use of nav
[moodle.git] / course / moodleform_mod.php
blobb38af38a3e9d10640db0a14e9f01ccea8191c085
1 <?php
2 require_once ($CFG->libdir.'/formslib.php');
3 require_once($CFG->libdir.'/completionlib.php');
4 require_once($CFG->libdir.'/gradelib.php');
5 require_once($CFG->libdir.'/plagiarismlib.php');
7 /**
8 * This class adds extra methods to form wrapper specific to be used for module
9 * add / update forms mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html
11 abstract class moodleform_mod extends moodleform {
12 /** Current data */
13 protected $current;
14 /**
15 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
16 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
17 * update one.
19 * @var mixed
21 protected $_instance;
22 /**
23 * Section of course that module instance will be put in or is in.
24 * This is always the section number itself (column 'section' from 'course_sections' table).
26 * @var int
28 protected $_section;
29 /**
30 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
31 * update one.
33 * @var mixed
35 protected $_cm;
37 /**
38 * Current course.
40 * @var mixed
42 protected $_course;
44 /**
45 * List of modform features
47 protected $_features;
48 /**
49 * @var array Custom completion-rule elements, if enabled
51 protected $_customcompletionelements;
52 /**
53 * @var string name of module.
55 protected $_modname;
56 /** current context, course or module depends if already exists*/
57 protected $context;
59 /** a flag indicating whether outcomes are being used*/
60 protected $_outcomesused;
62 /**
63 * @var bool A flag used to indicate that this module should lock settings
64 * based on admin settings flags in definition_after_data.
66 protected $applyadminlockedflags = false;
68 /** @var object The course format of the current course. */
69 protected $courseformat;
71 public function __construct($current, $section, $cm, $course) {
72 global $CFG;
74 $this->current = $current;
75 $this->_instance = $current->instance;
76 $this->_section = $section;
77 $this->_cm = $cm;
78 $this->_course = $course;
79 if ($this->_cm) {
80 $this->context = context_module::instance($this->_cm->id);
81 } else {
82 $this->context = context_course::instance($course->id);
85 // Set the course format.
86 require_once($CFG->dirroot . '/course/format/lib.php');
87 $this->courseformat = course_get_format($course);
89 // Guess module name if not set.
90 if (is_null($this->_modname)) {
91 $matches = array();
92 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
93 debugging('Rename form to mod_xx_mod_form, where xx is name of your module');
94 print_error('unknownmodulename');
96 $this->_modname = $matches[1];
98 $this->init_features();
99 parent::__construct('modedit.php');
103 * Old syntax of class constructor. Deprecated in PHP7.
105 * @deprecated since Moodle 3.1
107 public function moodleform_mod($current, $section, $cm, $course) {
108 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
109 self::__construct($current, $section, $cm, $course);
113 * Get the current data for the form.
114 * @return stdClass|null
116 public function get_current() {
117 return $this->current;
121 * Get the DB record for the current instance.
122 * @return stdClass|null
124 public function get_instance() {
125 return $this->_instance;
129 * Get the course section number (relative).
130 * @return int
132 public function get_section() {
133 return $this->_section;
137 * Get the course id.
138 * @return int
140 public function get_course() {
141 return $this->_course;
145 * Get the course module object.
146 * @return stdClass|null
148 public function get_coursemodule() {
149 return $this->_cm;
153 * Return the course context for new modules, or the module context for existing modules.
154 * @return context
156 public function get_context() {
157 return $this->context;
161 * Return the features this module supports.
162 * @return stdClass
164 public function get_features() {
165 return $this->_features;
169 protected function init_features() {
170 global $CFG;
172 $this->_features = new stdClass();
173 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
174 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
175 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
176 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
177 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
178 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
179 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
180 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
181 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
182 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
183 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
184 $this->_features->canrescale = (component_callback_exists('mod_' . $this->_modname, 'rescale_activity_grades') !== false);
188 * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
189 * This method is also called in the bulk activity completion form.
191 * Only available on moodleform_mod.
193 * @param array $default_values passed by reference
195 function data_preprocessing(&$default_values){
196 if (empty($default_values['scale'])) {
197 $default_values['assessed'] = 0;
200 if (empty($default_values['assessed'])){
201 $default_values['ratingtime'] = 0;
202 } else {
203 $default_values['ratingtime']=
204 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
209 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
211 function definition_after_data() {
212 global $CFG, $COURSE;
213 $mform =& $this->_form;
215 if ($id = $mform->getElementValue('update')) {
216 $modulename = $mform->getElementValue('modulename');
217 $instance = $mform->getElementValue('instance');
219 if ($this->_features->gradecat) {
220 $gradecat = false;
221 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
222 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
223 if (!empty($outcomes)) {
224 $gradecat = true;
228 $hasgradeitems = false;
229 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
230 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
231 if (!empty($items)) {
232 foreach ($items as $item) {
233 if (!empty($item->outcomeid)) {
234 $elname = 'outcome_'.$item->outcomeid;
235 if ($mform->elementExists($elname)) {
236 $mform->hardFreeze($elname); // prevent removing of existing outcomes
238 } else {
239 $hasgradeitems = true;
243 foreach ($items as $item) {
244 if (is_bool($gradecat)) {
245 $gradecat = $item->categoryid;
246 continue;
248 if ($gradecat != $item->categoryid) {
249 //mixed categories
250 $gradecat = false;
251 break;
256 if (!$hasgradeitems && $mform->elementExists('gradepass')) {
257 // Remove form element 'Grade to pass' since there are no grade items (when rating not selected).
258 $mform->removeElement('gradepass');
261 if ($gradecat === false) {
262 // items and outcomes in different categories - remove the option
263 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
264 if ($mform->elementExists('gradecat')) {
265 $mform->removeElement('gradecat');
266 if ($this->_features->rating && !$mform->elementExists('gradepass')) {
267 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
268 $mform->removeElement('modstandardgrade');
275 if ($COURSE->groupmodeforce) {
276 if ($mform->elementExists('groupmode')) {
277 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
281 // Don't disable/remove groupingid if it is currently set to something,
282 // otherwise you cannot turn it off at same time as turning off other
283 // option (MDL-30764)
284 if (empty($this->_cm) || !$this->_cm->groupingid) {
285 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
286 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
288 } else if (!$mform->elementExists('groupmode')) {
289 // Groupings have no use without groupmode.
290 if ($mform->elementExists('groupingid')) {
291 $mform->removeElement('groupingid');
296 // Completion: If necessary, freeze fields
297 $completion = new completion_info($COURSE);
298 if ($completion->is_enabled()) {
299 // If anybody has completed the activity, these options will be 'locked'
300 $completedcount = empty($this->_cm)
302 : $completion->count_user_data($this->_cm);
304 $freeze = false;
305 if (!$completedcount) {
306 if ($mform->elementExists('unlockcompletion')) {
307 $mform->removeElement('unlockcompletion');
309 // Automatically set to unlocked (note: this is necessary
310 // in order to make it recalculate completion once the option
311 // is changed, maybe someone has completed it now)
312 $mform->getElement('completionunlocked')->setValue(1);
313 } else {
314 // Has the element been unlocked, either by the button being pressed
315 // in this request, or the field already being set from a previous one?
316 if ($mform->exportValue('unlockcompletion') ||
317 $mform->exportValue('completionunlocked')) {
318 // Yes, add in warning text and set the hidden variable
319 $mform->insertElementBefore(
320 $mform->createElement('static', 'completedunlocked',
321 get_string('completedunlocked', 'completion'),
322 get_string('completedunlockedtext', 'completion')),
323 'unlockcompletion');
324 $mform->removeElement('unlockcompletion');
325 $mform->getElement('completionunlocked')->setValue(1);
326 } else {
327 // No, add in the warning text with the count (now we know
328 // it) before the unlock button
329 $mform->insertElementBefore(
330 $mform->createElement('static', 'completedwarning',
331 get_string('completedwarning', 'completion'),
332 get_string('completedwarningtext', 'completion', $completedcount)),
333 'unlockcompletion');
334 $freeze = true;
338 if ($freeze) {
339 $mform->freeze('completion');
340 if ($mform->elementExists('completionview')) {
341 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
343 if ($mform->elementExists('completionusegrade')) {
344 $mform->freeze('completionusegrade');
346 $mform->freeze($this->_customcompletionelements);
350 // Freeze admin defaults if required (and not different from default)
351 $this->apply_admin_locked_flags();
354 // form verification
355 function validation($data, $files) {
356 global $COURSE, $DB, $CFG;
357 $errors = parent::validation($data, $files);
359 $mform =& $this->_form;
361 $errors = array();
363 if ($mform->elementExists('name')) {
364 $name = trim($data['name']);
365 if ($name == '') {
366 $errors['name'] = get_string('required');
370 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
371 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
372 if ($data['coursemodule']) {
373 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
374 } else {
375 $cm = null;
378 if ($mform->elementExists('cmidnumber')) {
379 // verify the idnumber
380 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
381 $errors['cmidnumber'] = get_string('idnumbertaken');
385 // Ratings: Don't let them select an aggregate type without selecting a scale.
386 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
387 // invalid. If ratings have been selected then the user must select either a scale or max points.
388 // This matches (horrible) logic in data_preprocessing.
389 if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
390 $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
393 // Check that the grade pass is a valid number.
394 $gradepassvalid = false;
395 if (isset($data['gradepass'])) {
396 if (unformat_float($data['gradepass'], true) === false) {
397 $errors['gradepass'] = get_string('err_numeric', 'form');
398 } else {
399 $gradepassvalid = true;
403 // Grade to pass: ensure that the grade to pass is valid for points and scales.
404 // If we are working with a scale, convert into a positive number for validation.
405 if ($gradepassvalid && isset($data['gradepass']) && (!empty($data['grade']) || !empty($data['scale']))) {
406 $scale = !empty($data['grade']) ? $data['grade'] : $data['scale'];
407 if ($scale < 0) {
408 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
409 $grade = count(explode(',', $scalevalues->scale));
410 } else {
411 $grade = $scale;
413 if (unformat_float($data['gradepass']) > $grade) {
414 $errors['gradepass'] = get_string('gradepassgreaterthangrade', 'grades', $grade);
418 // Completion: Don't let them choose automatic completion without turning
419 // on some conditions. Ignore this check when completion settings are
420 // locked, as the options are then disabled.
421 if (array_key_exists('completion', $data) &&
422 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
423 !empty($data['completionunlocked'])) {
424 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
425 !$this->completion_rule_enabled($data)) {
426 $errors['completion'] = get_string('badautocompletion', 'completion');
430 // Availability: Check availability field does not have errors.
431 if (!empty($CFG->enableavailability)) {
432 \core_availability\frontend::report_validation_errors($data, $errors);
435 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
436 if (!empty($pluginerrors)) {
437 $errors = array_merge($errors, $pluginerrors);
440 return $errors;
444 * Extend the validation function from any other plugin.
446 * @param stdClass $data The form data.
447 * @return array $errors The list of errors keyed by element name.
449 protected function plugin_extend_coursemodule_validation($data) {
450 $errors = array();
452 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
453 foreach ($callbacks as $type => $plugins) {
454 foreach ($plugins as $plugin => $pluginfunction) {
455 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
456 $pluginerrors = $pluginfunction($this, $data);
457 if (!empty($pluginerrors)) {
458 $errors = array_merge($errors, $pluginerrors);
462 return $errors;
466 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
467 * form definition (new entry form); this function is used to load in data where values
468 * already exist and data is being edited (edit entry form).
470 * @param mixed $default_values object or array of default values
472 function set_data($default_values) {
473 if (is_object($default_values)) {
474 $default_values = (array)$default_values;
477 $this->data_preprocessing($default_values);
478 parent::set_data($default_values);
482 * Adds all the standard elements to a form to edit the settings for an activity module.
484 function standard_coursemodule_elements(){
485 global $COURSE, $CFG, $DB;
486 $mform =& $this->_form;
488 $this->_outcomesused = false;
489 if ($this->_features->outcomes) {
490 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
491 $this->_outcomesused = true;
492 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
493 foreach($outcomes as $outcome) {
494 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
500 if ($this->_features->rating) {
501 require_once($CFG->dirroot.'/rating/lib.php');
502 $rm = new rating_manager();
504 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
506 $permission=CAP_ALLOW;
507 $rolenamestring = null;
508 $isupdate = false;
509 if (!empty($this->_cm)) {
510 $isupdate = true;
511 $context = context_module::instance($this->_cm->id);
513 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
514 $rolenamestring = implode(', ', $rolenames);
515 } else {
516 $rolenamestring = get_string('capabilitychecknotavailable','rating');
518 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
519 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
521 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
522 $mform->setDefault('assessed', 0);
523 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
525 $gradeoptions = array('isupdate' => $isupdate,
526 'currentgrade' => false,
527 'hasgrades' => false,
528 'canrescale' => $this->_features->canrescale,
529 'useratings' => $this->_features->rating);
530 if ($isupdate) {
531 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
532 'itemmodule' => $this->_cm->modname,
533 'iteminstance' => $this->_cm->instance,
534 'itemnumber' => 0,
535 'courseid' => $COURSE->id));
536 if ($gradeitem) {
537 $gradeoptions['currentgrade'] = $gradeitem->grademax;
538 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
539 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
540 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
543 $mform->addElement('modgrade', 'scale', get_string('scale'), $gradeoptions);
544 $mform->disabledIf('scale', 'assessed', 'eq', 0);
545 $mform->addHelpButton('scale', 'modgrade', 'grades');
546 $mform->setDefault('scale', $CFG->gradepointdefault);
548 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
549 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
551 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
552 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
553 $mform->disabledIf('assesstimestart', 'ratingtime');
555 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
556 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
557 $mform->disabledIf('assesstimefinish', 'ratingtime');
560 //doing this here means splitting up the grade related settings on the lesson settings page
561 //$this->standard_grading_coursemodule_elements();
563 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
565 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section);
566 $allowstealth = !empty($CFG->allowstealth) && $this->courseformat->allow_stealth_module_visibility($this->_cm, $section);
567 if ($allowstealth && $section->visible) {
568 $modvisiblelabel = 'modvisiblewithstealth';
569 } else if ($section->visible) {
570 $modvisiblelabel = 'modvisible';
571 } else {
572 $modvisiblelabel = 'modvisiblehiddensection';
574 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
575 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible, 'cm' => $this->_cm));
576 $mform->addHelpButton('visible', $modvisiblelabel);
577 if (!empty($this->_cm)) {
578 $context = context_module::instance($this->_cm->id);
579 if (!has_capability('moodle/course:activityvisibility', $context)) {
580 $mform->hardFreeze('visible');
584 if ($this->_features->idnumber) {
585 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
586 $mform->setType('cmidnumber', PARAM_RAW);
587 $mform->addHelpButton('cmidnumber', 'idnumbermod');
590 if ($this->_features->groups) {
591 $options = array(NOGROUPS => get_string('groupsnone'),
592 SEPARATEGROUPS => get_string('groupsseparate'),
593 VISIBLEGROUPS => get_string('groupsvisible'));
594 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
595 $mform->addHelpButton('groupmode', 'groupmode', 'group');
598 if ($this->_features->groupings) {
599 // Groupings selector - used to select grouping for groups in activity.
600 $options = array();
601 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
602 foreach ($groupings as $grouping) {
603 $options[$grouping->id] = format_string($grouping->name);
606 core_collator::asort($options);
607 $options = array(0 => get_string('none')) + $options;
608 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
609 $mform->addHelpButton('groupingid', 'grouping', 'group');
612 if (!empty($CFG->enableavailability)) {
613 // Add special button to end of previous section if groups/groupings
614 // are enabled.
615 if ($this->_features->groups || $this->_features->groupings) {
616 $mform->addElement('static', 'restrictgroupbutton', '',
617 html_writer::tag('button', get_string('restrictbygroup', 'availability'),
618 array('id' => 'restrictbygroup', 'disabled' => 'disabled', 'class' => 'btn btn-secondary')));
621 // Availability field. This is just a textarea; the user interface
622 // interaction is all implemented in JavaScript.
623 $mform->addElement('header', 'availabilityconditionsheader',
624 get_string('restrictaccess', 'availability'));
625 // Note: This field cannot be named 'availability' because that
626 // conflicts with fields in existing modules (such as assign).
627 // So it uses a long name that will not conflict.
628 $mform->addElement('textarea', 'availabilityconditionsjson',
629 get_string('accessrestrictions', 'availability'));
630 // The _cm variable may not be a proper cm_info, so get one from modinfo.
631 if ($this->_cm) {
632 $modinfo = get_fast_modinfo($COURSE);
633 $cm = $modinfo->get_cm($this->_cm->id);
634 } else {
635 $cm = null;
637 \core_availability\frontend::include_all_javascript($COURSE, $cm);
640 // Conditional activities: completion tracking section
641 if(!isset($completion)) {
642 $completion = new completion_info($COURSE);
644 if ($completion->is_enabled()) {
645 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
646 // Unlock button for if people have completed it (will
647 // be removed in definition_after_data if they haven't)
648 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
649 $mform->registerNoSubmitButton('unlockcompletion');
650 $mform->addElement('hidden', 'completionunlocked', 0);
651 $mform->setType('completionunlocked', PARAM_INT);
653 $trackingdefault = COMPLETION_TRACKING_NONE;
654 // If system and activity default is on, set it.
655 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
656 $hasrules = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_HAS_RULES, true);
657 $tracksviews = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, true);
658 if ($hasrules || $tracksviews) {
659 $trackingdefault = COMPLETION_TRACKING_AUTOMATIC;
660 } else {
661 $trackingdefault = COMPLETION_TRACKING_MANUAL;
665 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
666 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
667 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
668 $mform->setDefault('completion', $trackingdefault);
669 $mform->addHelpButton('completion', 'completion', 'completion');
671 // Automatic completion once you view it
672 $gotcompletionoptions = false;
673 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
674 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
675 get_string('completionview_desc', 'completion'));
676 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
677 // Check by default if automatic completion tracking is set.
678 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC) {
679 $mform->setDefault('completionview', 1);
681 $gotcompletionoptions = true;
684 // Automatic completion once it's graded
685 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
686 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
687 get_string('completionusegrade_desc', 'completion'));
688 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
689 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
690 $gotcompletionoptions = true;
692 // If using the rating system, there is no grade unless ratings are enabled.
693 if ($this->_features->rating) {
694 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
698 // Automatic completion according to module-specific rules
699 $this->_customcompletionelements = $this->add_completion_rules();
700 foreach ($this->_customcompletionelements as $element) {
701 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
704 $gotcompletionoptions = $gotcompletionoptions ||
705 count($this->_customcompletionelements)>0;
707 // Automatic option only appears if possible
708 if ($gotcompletionoptions) {
709 $mform->getElement('completion')->addOption(
710 get_string('completion_automatic', 'completion'),
711 COMPLETION_TRACKING_AUTOMATIC);
714 // Completion expected at particular date? (For progress tracking)
715 $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
716 array('optional' => true));
717 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
718 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
721 // Populate module tags.
722 if (core_tag_tag::is_enabled('core', 'course_modules')) {
723 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
724 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
725 if ($this->_cm) {
726 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
727 $mform->setDefault('tags', $tags);
731 $this->standard_hidden_coursemodule_elements();
733 $this->plugin_extend_coursemodule_standard_elements();
737 * Plugins can extend the coursemodule settings form.
739 protected function plugin_extend_coursemodule_standard_elements() {
740 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
741 foreach ($callbacks as $type => $plugins) {
742 foreach ($plugins as $plugin => $pluginfunction) {
743 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
744 // directly.
745 $pluginfunction($this, $this->_form);
751 * Can be overridden to add custom completion rules if the module wishes
752 * them. If overriding this, you should also override completion_rule_enabled.
753 * <p>
754 * Just add elements to the form as needed and return the list of IDs. The
755 * system will call disabledIf and handle other behaviour for each returned
756 * ID.
757 * @return array Array of string IDs of added items, empty array if none
759 function add_completion_rules() {
760 return array();
764 * Called during validation. Override to indicate, based on the data, whether
765 * a custom completion rule is enabled (selected).
767 * @param array $data Input data (not yet validated)
768 * @return bool True if one or more rules is enabled, false if none are;
769 * default returns false
771 function completion_rule_enabled($data) {
772 return false;
775 function standard_hidden_coursemodule_elements(){
776 $mform =& $this->_form;
777 $mform->addElement('hidden', 'course', 0);
778 $mform->setType('course', PARAM_INT);
780 $mform->addElement('hidden', 'coursemodule', 0);
781 $mform->setType('coursemodule', PARAM_INT);
783 $mform->addElement('hidden', 'section', 0);
784 $mform->setType('section', PARAM_INT);
786 $mform->addElement('hidden', 'module', 0);
787 $mform->setType('module', PARAM_INT);
789 $mform->addElement('hidden', 'modulename', '');
790 $mform->setType('modulename', PARAM_PLUGIN);
792 $mform->addElement('hidden', 'instance', 0);
793 $mform->setType('instance', PARAM_INT);
795 $mform->addElement('hidden', 'add', 0);
796 $mform->setType('add', PARAM_ALPHA);
798 $mform->addElement('hidden', 'update', 0);
799 $mform->setType('update', PARAM_INT);
801 $mform->addElement('hidden', 'return', 0);
802 $mform->setType('return', PARAM_BOOL);
804 $mform->addElement('hidden', 'sr', 0);
805 $mform->setType('sr', PARAM_INT);
808 public function standard_grading_coursemodule_elements() {
809 global $COURSE, $CFG;
810 $mform =& $this->_form;
811 $isupdate = !empty($this->_cm);
812 $gradeoptions = array('isupdate' => $isupdate,
813 'currentgrade' => false,
814 'hasgrades' => false,
815 'canrescale' => $this->_features->canrescale,
816 'useratings' => $this->_features->rating);
818 if ($this->_features->hasgrades) {
820 if (!$this->_features->rating || $this->_features->gradecat) {
821 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
824 //if supports grades and grades arent being handled via ratings
825 if (!$this->_features->rating) {
827 if ($isupdate) {
828 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
829 'itemmodule' => $this->_cm->modname,
830 'iteminstance' => $this->_cm->instance,
831 'itemnumber' => 0,
832 'courseid' => $COURSE->id));
833 if ($gradeitem) {
834 $gradeoptions['currentgrade'] = $gradeitem->grademax;
835 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
836 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
837 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
840 $mform->addElement('modgrade', 'grade', get_string('grade'), $gradeoptions);
841 $mform->addHelpButton('grade', 'modgrade', 'grades');
842 $mform->setDefault('grade', $CFG->gradepointdefault);
845 if ($this->_features->advancedgrading
846 and !empty($this->current->_advancedgradingdata['methods'])
847 and !empty($this->current->_advancedgradingdata['areas'])) {
849 if (count($this->current->_advancedgradingdata['areas']) == 1) {
850 // if there is just one gradable area (most cases), display just the selector
851 // without its name to make UI simplier
852 $areadata = reset($this->current->_advancedgradingdata['areas']);
853 $areaname = key($this->current->_advancedgradingdata['areas']);
854 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
855 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
856 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
857 if (!$this->_features->rating) {
858 $mform->disabledIf('advancedgradingmethod_'.$areaname, 'grade[modgrade_type]', 'eq', 'none');
861 } else {
862 // the module defines multiple gradable areas, display a selector
863 // for each of them together with a name of the area
864 $areasgroup = array();
865 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
866 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
867 $areadata['title'], $this->current->_advancedgradingdata['methods']);
868 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
870 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
871 array(' ', '<br />'), false);
875 if ($this->_features->gradecat) {
876 $mform->addElement('select', 'gradecat',
877 get_string('gradecategoryonmodform', 'grades'),
878 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
879 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
880 if (!$this->_features->rating) {
881 $mform->disabledIf('gradecat', 'grade[modgrade_type]', 'eq', 'none');
885 // Grade to pass.
886 $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
887 $mform->addHelpButton('gradepass', 'gradepass', 'grades');
888 $mform->setDefault('gradepass', '');
889 $mform->setType('gradepass', PARAM_RAW);
890 if (!$this->_features->rating) {
891 $mform->disabledIf('gradepass', 'grade[modgrade_type]', 'eq', 'none');
892 } else {
893 $mform->disabledIf('gradepass', 'assessed', 'eq', '0');
899 * Add an editor for an activity's introduction field.
900 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
901 * @param null $required Override system default for requiremodintro
902 * @param null $customlabel Override default label for editor
903 * @throws coding_exception
905 protected function add_intro_editor($required=null, $customlabel=null) {
906 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
907 debugging($str, DEBUG_DEVELOPER);
909 $this->standard_intro_elements($customlabel);
914 * Add an editor for an activity's introduction field.
916 * @param null $customlabel Override default label for editor
917 * @throws coding_exception
919 protected function standard_intro_elements($customlabel=null) {
920 global $CFG;
922 $required = $CFG->requiremodintro;
924 $mform = $this->_form;
925 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
927 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
928 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
929 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
930 if ($required) {
931 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
934 // If the 'show description' feature is enabled, this checkbox appears below the intro.
935 // We want to hide that when using the singleactivity course format because it is confusing.
936 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
937 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
938 $mform->addHelpButton('showdescription', 'showdescription');
943 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
945 * @param bool $cancel show cancel button
946 * @param string $submitlabel null means default, false means none, string is label text
947 * @param string $submit2label null means default, false means none, string is label text
948 * @return void
950 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
951 if (is_null($submitlabel)) {
952 $submitlabel = get_string('savechangesanddisplay');
955 if (is_null($submit2label)) {
956 $submit2label = get_string('savechangesandreturntocourse');
959 $mform = $this->_form;
961 // elements in a row need a group
962 $buttonarray = array();
964 // Label for the submit button to return to the course.
965 // Ignore this button in single activity format because it is confusing.
966 if ($submit2label !== false && $this->courseformat->has_view_page()) {
967 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
970 if ($submitlabel !== false) {
971 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
974 if ($cancel) {
975 $buttonarray[] = &$mform->createElement('cancel');
978 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
979 $mform->setType('buttonar', PARAM_RAW);
980 $mform->closeHeaderBefore('buttonar');
984 * Get the list of admin settings for this module and apply any locked settings.
985 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
986 * in that function because set_data has not been called yet.
988 * @return void
990 protected function apply_admin_locked_flags() {
991 global $OUTPUT;
993 if (!$this->applyadminlockedflags) {
994 return;
997 $settings = get_config($this->_modname);
998 $mform = $this->_form;
999 $lockedicon = html_writer::tag('span',
1000 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1001 array('class' => 'action-icon'));
1002 $isupdate = !empty($this->_cm);
1004 foreach ($settings as $name => $value) {
1005 if (strpos('_', $name) !== false) {
1006 continue;
1008 if ($mform->elementExists($name)) {
1009 $element = $mform->getElement($name);
1010 $lockedsetting = $name . '_locked';
1011 if (!empty($settings->$lockedsetting)) {
1012 // Always lock locked settings for new modules,
1013 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1014 $value = $settings->$name;
1015 if ($isupdate && isset($this->current->$name)) {
1016 $value = $this->current->$name;
1018 if ($value == $settings->$name) {
1019 $mform->setConstant($name, $settings->$name);
1020 $element->setLabel($element->getLabel() . $lockedicon);
1021 // Do not use hardfreeze because we need the hidden input to check dependencies.
1022 $element->freeze();
1030 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
1032 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1033 * default date/time value should be relative to. If not passed, all
1034 * date/time fields are set relative to the users current midnight.
1035 * @return void
1037 public function apply_admin_defaults($datetimeoffsets = array()) {
1038 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1039 $this->applyadminlockedflags = true;
1041 $settings = get_config($this->_modname);
1042 $mform = $this->_form;
1043 $usermidnight = usergetmidnight(time());
1044 $isupdate = !empty($this->_cm);
1046 foreach ($settings as $name => $value) {
1047 if (strpos('_', $name) !== false) {
1048 continue;
1050 if ($mform->elementExists($name)) {
1051 $element = $mform->getElement($name);
1052 if (!$isupdate) {
1053 if ($element->getType() == 'date_time_selector') {
1054 $enabledsetting = $name . '_enabled';
1055 if (empty($settings->$enabledsetting)) {
1056 $mform->setDefault($name, 0);
1057 } else {
1058 $relativetime = $usermidnight;
1059 if (isset($datetimeoffsets[$name])) {
1060 $relativetime = $datetimeoffsets[$name];
1062 $mform->setDefault($name, $relativetime + $settings->$name);
1064 } else {
1065 $mform->setDefault($name, $settings->$name);
1068 $advancedsetting = $name . '_adv';
1069 if (!empty($settings->$advancedsetting)) {
1070 $mform->setAdvanced($name);
1077 * Allows modules to modify the data returned by form get_data().
1078 * This method is also called in the bulk activity completion form.
1080 * Only available on moodleform_mod.
1082 * @param stdClass $data passed by reference
1084 public function data_postprocessing($data) {
1088 * Return submitted data if properly submitted or returns NULL if validation fails or
1089 * if there is no submitted data.
1091 * Do not override this method, override data_postprocessing() instead.
1093 * @return object submitted data; NULL if not valid or not submitted or cancelled
1095 public function get_data() {
1096 $data = parent::get_data();
1097 if ($data) {
1098 // Convert the grade pass value - we may be using a language which uses commas,
1099 // rather than decimal points, in numbers. These need to be converted so that
1100 // they can be added to the DB.
1101 if (isset($data->gradepass)) {
1102 $data->gradepass = unformat_float($data->gradepass);
1105 $this->data_postprocessing($data);
1107 return $data;