MDL-61363 tag: unit tests for get_items_tags function
[moodle.git] / course / moodleform_mod.php
blob024f15977222c8435abf4afdb1971fc96e0b8d24
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
90 $matches = array();
91 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
92 debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
93 print_error('unknownmodulename');
95 $this->_modname = $matches[1];
96 $this->init_features();
97 parent::__construct('modedit.php');
101 * Old syntax of class constructor. Deprecated in PHP7.
103 * @deprecated since Moodle 3.1
105 public function moodleform_mod($current, $section, $cm, $course) {
106 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
107 self::__construct($current, $section, $cm, $course);
111 * Get the current data for the form.
112 * @return stdClass|null
114 public function get_current() {
115 return $this->current;
119 * Get the DB record for the current instance.
120 * @return stdClass|null
122 public function get_instance() {
123 return $this->_instance;
127 * Get the course section number (relative).
128 * @return int
130 public function get_section() {
131 return $this->_section;
135 * Get the course id.
136 * @return int
138 public function get_course() {
139 return $this->_course;
143 * Get the course module object.
144 * @return stdClass|null
146 public function get_coursemodule() {
147 return $this->_cm;
151 * Return the course context for new modules, or the module context for existing modules.
152 * @return context
154 public function get_context() {
155 return $this->context;
159 * Return the features this module supports.
160 * @return stdClass
162 public function get_features() {
163 return $this->_features;
167 protected function init_features() {
168 global $CFG;
170 $this->_features = new stdClass();
171 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
172 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
173 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
174 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
175 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
176 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
177 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
178 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
179 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
180 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
181 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
182 $this->_features->canrescale = (component_callback_exists('mod_' . $this->_modname, 'rescale_activity_grades') !== false);
186 * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
187 * This method is also called in the bulk activity completion form.
189 * Only available on moodleform_mod.
191 * @param array $default_values passed by reference
193 function data_preprocessing(&$default_values){
194 if (empty($default_values['scale'])) {
195 $default_values['assessed'] = 0;
198 if (empty($default_values['assessed'])){
199 $default_values['ratingtime'] = 0;
200 } else {
201 $default_values['ratingtime']=
202 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
207 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
209 function definition_after_data() {
210 global $CFG, $COURSE;
211 $mform =& $this->_form;
213 if ($id = $mform->getElementValue('update')) {
214 $modulename = $mform->getElementValue('modulename');
215 $instance = $mform->getElementValue('instance');
217 if ($this->_features->gradecat) {
218 $gradecat = false;
219 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
220 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
221 if (!empty($outcomes)) {
222 $gradecat = true;
226 $hasgradeitems = false;
227 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
228 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
229 if (!empty($items)) {
230 foreach ($items as $item) {
231 if (!empty($item->outcomeid)) {
232 $elname = 'outcome_'.$item->outcomeid;
233 if ($mform->elementExists($elname)) {
234 $mform->hardFreeze($elname); // prevent removing of existing outcomes
236 } else {
237 $hasgradeitems = true;
241 foreach ($items as $item) {
242 if (is_bool($gradecat)) {
243 $gradecat = $item->categoryid;
244 continue;
246 if ($gradecat != $item->categoryid) {
247 //mixed categories
248 $gradecat = false;
249 break;
254 if (!$hasgradeitems && $mform->elementExists('gradepass')) {
255 // Remove form element 'Grade to pass' since there are no grade items (when rating not selected).
256 $mform->removeElement('gradepass');
259 if ($gradecat === false) {
260 // items and outcomes in different categories - remove the option
261 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
262 if ($mform->elementExists('gradecat')) {
263 $mform->removeElement('gradecat');
264 if ($this->_features->rating && !$mform->elementExists('gradepass')) {
265 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
266 $mform->removeElement('modstandardgrade');
273 if ($COURSE->groupmodeforce) {
274 if ($mform->elementExists('groupmode')) {
275 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
279 // Don't disable/remove groupingid if it is currently set to something,
280 // otherwise you cannot turn it off at same time as turning off other
281 // option (MDL-30764)
282 if (empty($this->_cm) || !$this->_cm->groupingid) {
283 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
284 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
286 } else if (!$mform->elementExists('groupmode')) {
287 // Groupings have no use without groupmode.
288 if ($mform->elementExists('groupingid')) {
289 $mform->removeElement('groupingid');
294 // Completion: If necessary, freeze fields
295 $completion = new completion_info($COURSE);
296 if ($completion->is_enabled()) {
297 // If anybody has completed the activity, these options will be 'locked'
298 $completedcount = empty($this->_cm)
300 : $completion->count_user_data($this->_cm);
302 $freeze = false;
303 if (!$completedcount) {
304 if ($mform->elementExists('unlockcompletion')) {
305 $mform->removeElement('unlockcompletion');
307 // Automatically set to unlocked (note: this is necessary
308 // in order to make it recalculate completion once the option
309 // is changed, maybe someone has completed it now)
310 $mform->getElement('completionunlocked')->setValue(1);
311 } else {
312 // Has the element been unlocked, either by the button being pressed
313 // in this request, or the field already being set from a previous one?
314 if ($mform->exportValue('unlockcompletion') ||
315 $mform->exportValue('completionunlocked')) {
316 // Yes, add in warning text and set the hidden variable
317 $mform->insertElementBefore(
318 $mform->createElement('static', 'completedunlocked',
319 get_string('completedunlocked', 'completion'),
320 get_string('completedunlockedtext', 'completion')),
321 'unlockcompletion');
322 $mform->removeElement('unlockcompletion');
323 $mform->getElement('completionunlocked')->setValue(1);
324 } else {
325 // No, add in the warning text with the count (now we know
326 // it) before the unlock button
327 $mform->insertElementBefore(
328 $mform->createElement('static', 'completedwarning',
329 get_string('completedwarning', 'completion'),
330 get_string('completedwarningtext', 'completion', $completedcount)),
331 'unlockcompletion');
332 $freeze = true;
336 if ($freeze) {
337 $mform->freeze('completion');
338 if ($mform->elementExists('completionview')) {
339 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
341 if ($mform->elementExists('completionusegrade')) {
342 $mform->freeze('completionusegrade');
344 $mform->freeze($this->_customcompletionelements);
348 // Freeze admin defaults if required (and not different from default)
349 $this->apply_admin_locked_flags();
352 // form verification
353 function validation($data, $files) {
354 global $COURSE, $DB, $CFG;
355 $errors = parent::validation($data, $files);
357 $mform =& $this->_form;
359 $errors = array();
361 if ($mform->elementExists('name')) {
362 $name = trim($data['name']);
363 if ($name == '') {
364 $errors['name'] = get_string('required');
368 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
369 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
370 if ($data['coursemodule']) {
371 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
372 } else {
373 $cm = null;
376 if ($mform->elementExists('cmidnumber')) {
377 // verify the idnumber
378 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
379 $errors['cmidnumber'] = get_string('idnumbertaken');
383 // Ratings: Don't let them select an aggregate type without selecting a scale.
384 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
385 // invalid. If ratings have been selected then the user must select either a scale or max points.
386 // This matches (horrible) logic in data_preprocessing.
387 if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
388 $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
391 // Check that the grade pass is a valid number.
392 $gradepassvalid = false;
393 if (isset($data['gradepass'])) {
394 if (unformat_float($data['gradepass'], true) === false) {
395 $errors['gradepass'] = get_string('err_numeric', 'form');
396 } else {
397 $gradepassvalid = true;
401 // Grade to pass: ensure that the grade to pass is valid for points and scales.
402 // If we are working with a scale, convert into a positive number for validation.
403 if ($gradepassvalid && isset($data['gradepass']) && (!empty($data['grade']) || !empty($data['scale']))) {
404 $scale = !empty($data['grade']) ? $data['grade'] : $data['scale'];
405 if ($scale < 0) {
406 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
407 $grade = count(explode(',', $scalevalues->scale));
408 } else {
409 $grade = $scale;
411 if ($data['gradepass'] > $grade) {
412 $errors['gradepass'] = get_string('gradepassgreaterthangrade', 'grades', $grade);
416 // Completion: Don't let them choose automatic completion without turning
417 // on some conditions. Ignore this check when completion settings are
418 // locked, as the options are then disabled.
419 if (array_key_exists('completion', $data) &&
420 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
421 !empty($data['completionunlocked'])) {
422 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
423 !$this->completion_rule_enabled($data)) {
424 $errors['completion'] = get_string('badautocompletion', 'completion');
428 // Availability: Check availability field does not have errors.
429 if (!empty($CFG->enableavailability)) {
430 \core_availability\frontend::report_validation_errors($data, $errors);
433 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
434 if (!empty($pluginerrors)) {
435 $errors = array_merge($errors, $pluginerrors);
438 return $errors;
442 * Extend the validation function from any other plugin.
444 * @param stdClass $data The form data.
445 * @return array $errors The list of errors keyed by element name.
447 protected function plugin_extend_coursemodule_validation($data) {
448 $errors = array();
450 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
451 foreach ($callbacks as $type => $plugins) {
452 foreach ($plugins as $plugin => $pluginfunction) {
453 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
454 $pluginerrors = $pluginfunction($this, $data);
455 if (!empty($pluginerrors)) {
456 $errors = array_merge($errors, $pluginerrors);
460 return $errors;
464 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
465 * form definition (new entry form); this function is used to load in data where values
466 * already exist and data is being edited (edit entry form).
468 * @param mixed $default_values object or array of default values
470 function set_data($default_values) {
471 if (is_object($default_values)) {
472 $default_values = (array)$default_values;
475 $this->data_preprocessing($default_values);
476 parent::set_data($default_values);
480 * Adds all the standard elements to a form to edit the settings for an activity module.
482 function standard_coursemodule_elements(){
483 global $COURSE, $CFG, $DB;
484 $mform =& $this->_form;
486 $this->_outcomesused = false;
487 if ($this->_features->outcomes) {
488 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
489 $this->_outcomesused = true;
490 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
491 foreach($outcomes as $outcome) {
492 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
498 if ($this->_features->rating) {
499 require_once($CFG->dirroot.'/rating/lib.php');
500 $rm = new rating_manager();
502 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
504 $permission=CAP_ALLOW;
505 $rolenamestring = null;
506 $isupdate = false;
507 if (!empty($this->_cm)) {
508 $isupdate = true;
509 $context = context_module::instance($this->_cm->id);
511 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
512 $rolenamestring = implode(', ', $rolenames);
513 } else {
514 $rolenamestring = get_string('capabilitychecknotavailable','rating');
516 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
517 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
519 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
520 $mform->setDefault('assessed', 0);
521 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
523 $gradeoptions = array('isupdate' => $isupdate,
524 'currentgrade' => false,
525 'hasgrades' => false,
526 'canrescale' => $this->_features->canrescale,
527 'useratings' => $this->_features->rating);
528 if ($isupdate) {
529 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
530 'itemmodule' => $this->_cm->modname,
531 'iteminstance' => $this->_cm->instance,
532 'itemnumber' => 0,
533 'courseid' => $COURSE->id));
534 if ($gradeitem) {
535 $gradeoptions['currentgrade'] = $gradeitem->grademax;
536 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
537 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
538 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
541 $mform->addElement('modgrade', 'scale', get_string('scale'), $gradeoptions);
542 $mform->disabledIf('scale', 'assessed', 'eq', 0);
543 $mform->addHelpButton('scale', 'modgrade', 'grades');
544 $mform->setDefault('scale', $CFG->gradepointdefault);
546 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
547 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
549 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
550 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
551 $mform->disabledIf('assesstimestart', 'ratingtime');
553 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
554 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
555 $mform->disabledIf('assesstimefinish', 'ratingtime');
558 //doing this here means splitting up the grade related settings on the lesson settings page
559 //$this->standard_grading_coursemodule_elements();
561 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
563 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section);
564 $allowstealth = !empty($CFG->allowstealth) && $this->courseformat->allow_stealth_module_visibility($this->_cm, $section);
565 if ($allowstealth && $section->visible) {
566 $modvisiblelabel = 'modvisiblewithstealth';
567 } else if ($section->visible) {
568 $modvisiblelabel = 'modvisible';
569 } else {
570 $modvisiblelabel = 'modvisiblehiddensection';
572 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
573 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible, 'cm' => $this->_cm));
574 $mform->addHelpButton('visible', $modvisiblelabel);
575 if (!empty($this->_cm)) {
576 $context = context_module::instance($this->_cm->id);
577 if (!has_capability('moodle/course:activityvisibility', $context)) {
578 $mform->hardFreeze('visible');
582 if ($this->_features->idnumber) {
583 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
584 $mform->setType('cmidnumber', PARAM_RAW);
585 $mform->addHelpButton('cmidnumber', 'idnumbermod');
588 if ($this->_features->groups) {
589 $options = array(NOGROUPS => get_string('groupsnone'),
590 SEPARATEGROUPS => get_string('groupsseparate'),
591 VISIBLEGROUPS => get_string('groupsvisible'));
592 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
593 $mform->addHelpButton('groupmode', 'groupmode', 'group');
596 if ($this->_features->groupings) {
597 // Groupings selector - used to select grouping for groups in activity.
598 $options = array();
599 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
600 foreach ($groupings as $grouping) {
601 $options[$grouping->id] = format_string($grouping->name);
604 core_collator::asort($options);
605 $options = array(0 => get_string('none')) + $options;
606 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
607 $mform->addHelpButton('groupingid', 'grouping', 'group');
610 if (!empty($CFG->enableavailability)) {
611 // Add special button to end of previous section if groups/groupings
612 // are enabled.
613 if ($this->_features->groups || $this->_features->groupings) {
614 $mform->addElement('static', 'restrictgroupbutton', '',
615 html_writer::tag('button', get_string('restrictbygroup', 'availability'),
616 array('id' => 'restrictbygroup', 'disabled' => 'disabled', 'class' => 'btn btn-secondary')));
619 // Availability field. This is just a textarea; the user interface
620 // interaction is all implemented in JavaScript.
621 $mform->addElement('header', 'availabilityconditionsheader',
622 get_string('restrictaccess', 'availability'));
623 // Note: This field cannot be named 'availability' because that
624 // conflicts with fields in existing modules (such as assign).
625 // So it uses a long name that will not conflict.
626 $mform->addElement('textarea', 'availabilityconditionsjson',
627 get_string('accessrestrictions', 'availability'));
628 // The _cm variable may not be a proper cm_info, so get one from modinfo.
629 if ($this->_cm) {
630 $modinfo = get_fast_modinfo($COURSE);
631 $cm = $modinfo->get_cm($this->_cm->id);
632 } else {
633 $cm = null;
635 \core_availability\frontend::include_all_javascript($COURSE, $cm);
638 // Conditional activities: completion tracking section
639 if(!isset($completion)) {
640 $completion = new completion_info($COURSE);
642 if ($completion->is_enabled()) {
643 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
644 // Unlock button for if people have completed it (will
645 // be removed in definition_after_data if they haven't)
646 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
647 $mform->registerNoSubmitButton('unlockcompletion');
648 $mform->addElement('hidden', 'completionunlocked', 0);
649 $mform->setType('completionunlocked', PARAM_INT);
651 $trackingdefault = COMPLETION_TRACKING_NONE;
652 // If system and activity default is on, set it.
653 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
654 $hasrules = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_HAS_RULES, true);
655 $tracksviews = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, true);
656 if ($hasrules || $tracksviews) {
657 $trackingdefault = COMPLETION_TRACKING_AUTOMATIC;
658 } else {
659 $trackingdefault = COMPLETION_TRACKING_MANUAL;
663 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
664 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
665 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
666 $mform->setDefault('completion', $trackingdefault);
667 $mform->addHelpButton('completion', 'completion', 'completion');
669 // Automatic completion once you view it
670 $gotcompletionoptions = false;
671 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
672 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
673 get_string('completionview_desc', 'completion'));
674 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
675 // Check by default if automatic completion tracking is set.
676 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC) {
677 $mform->setDefault('completionview', 1);
679 $gotcompletionoptions = true;
682 // Automatic completion once it's graded
683 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
684 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
685 get_string('completionusegrade_desc', 'completion'));
686 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
687 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
688 $gotcompletionoptions = true;
690 // If using the rating system, there is no grade unless ratings are enabled.
691 if ($this->_features->rating) {
692 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
696 // Automatic completion according to module-specific rules
697 $this->_customcompletionelements = $this->add_completion_rules();
698 foreach ($this->_customcompletionelements as $element) {
699 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
702 $gotcompletionoptions = $gotcompletionoptions ||
703 count($this->_customcompletionelements)>0;
705 // Automatic option only appears if possible
706 if ($gotcompletionoptions) {
707 $mform->getElement('completion')->addOption(
708 get_string('completion_automatic', 'completion'),
709 COMPLETION_TRACKING_AUTOMATIC);
712 // Completion expected at particular date? (For progress tracking)
713 $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
714 array('optional' => true));
715 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
716 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
719 // Populate module tags.
720 if (core_tag_tag::is_enabled('core', 'course_modules')) {
721 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
722 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
723 if ($this->_cm) {
724 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
725 $mform->setDefault('tags', $tags);
729 $this->standard_hidden_coursemodule_elements();
731 $this->plugin_extend_coursemodule_standard_elements();
735 * Plugins can extend the coursemodule settings form.
737 protected function plugin_extend_coursemodule_standard_elements() {
738 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
739 foreach ($callbacks as $type => $plugins) {
740 foreach ($plugins as $plugin => $pluginfunction) {
741 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
742 // directly.
743 $pluginfunction($this, $this->_form);
749 * Can be overridden to add custom completion rules if the module wishes
750 * them. If overriding this, you should also override completion_rule_enabled.
751 * <p>
752 * Just add elements to the form as needed and return the list of IDs. The
753 * system will call disabledIf and handle other behaviour for each returned
754 * ID.
755 * @return array Array of string IDs of added items, empty array if none
757 function add_completion_rules() {
758 return array();
762 * Called during validation. Override to indicate, based on the data, whether
763 * a custom completion rule is enabled (selected).
765 * @param array $data Input data (not yet validated)
766 * @return bool True if one or more rules is enabled, false if none are;
767 * default returns false
769 function completion_rule_enabled($data) {
770 return false;
773 function standard_hidden_coursemodule_elements(){
774 $mform =& $this->_form;
775 $mform->addElement('hidden', 'course', 0);
776 $mform->setType('course', PARAM_INT);
778 $mform->addElement('hidden', 'coursemodule', 0);
779 $mform->setType('coursemodule', PARAM_INT);
781 $mform->addElement('hidden', 'section', 0);
782 $mform->setType('section', PARAM_INT);
784 $mform->addElement('hidden', 'module', 0);
785 $mform->setType('module', PARAM_INT);
787 $mform->addElement('hidden', 'modulename', '');
788 $mform->setType('modulename', PARAM_PLUGIN);
790 $mform->addElement('hidden', 'instance', 0);
791 $mform->setType('instance', PARAM_INT);
793 $mform->addElement('hidden', 'add', 0);
794 $mform->setType('add', PARAM_ALPHA);
796 $mform->addElement('hidden', 'update', 0);
797 $mform->setType('update', PARAM_INT);
799 $mform->addElement('hidden', 'return', 0);
800 $mform->setType('return', PARAM_BOOL);
802 $mform->addElement('hidden', 'sr', 0);
803 $mform->setType('sr', PARAM_INT);
806 public function standard_grading_coursemodule_elements() {
807 global $COURSE, $CFG;
808 $mform =& $this->_form;
809 $isupdate = !empty($this->_cm);
810 $gradeoptions = array('isupdate' => $isupdate,
811 'currentgrade' => false,
812 'hasgrades' => false,
813 'canrescale' => $this->_features->canrescale,
814 'useratings' => $this->_features->rating);
816 if ($this->_features->hasgrades) {
818 if (!$this->_features->rating || $this->_features->gradecat) {
819 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
822 //if supports grades and grades arent being handled via ratings
823 if (!$this->_features->rating) {
825 if ($isupdate) {
826 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
827 'itemmodule' => $this->_cm->modname,
828 'iteminstance' => $this->_cm->instance,
829 'itemnumber' => 0,
830 'courseid' => $COURSE->id));
831 if ($gradeitem) {
832 $gradeoptions['currentgrade'] = $gradeitem->grademax;
833 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
834 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
835 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
838 $mform->addElement('modgrade', 'grade', get_string('grade'), $gradeoptions);
839 $mform->addHelpButton('grade', 'modgrade', 'grades');
840 $mform->setDefault('grade', $CFG->gradepointdefault);
843 if ($this->_features->advancedgrading
844 and !empty($this->current->_advancedgradingdata['methods'])
845 and !empty($this->current->_advancedgradingdata['areas'])) {
847 if (count($this->current->_advancedgradingdata['areas']) == 1) {
848 // if there is just one gradable area (most cases), display just the selector
849 // without its name to make UI simplier
850 $areadata = reset($this->current->_advancedgradingdata['areas']);
851 $areaname = key($this->current->_advancedgradingdata['areas']);
852 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
853 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
854 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
855 if (!$this->_features->rating) {
856 $mform->disabledIf('advancedgradingmethod_'.$areaname, 'grade[modgrade_type]', 'eq', 'none');
859 } else {
860 // the module defines multiple gradable areas, display a selector
861 // for each of them together with a name of the area
862 $areasgroup = array();
863 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
864 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
865 $areadata['title'], $this->current->_advancedgradingdata['methods']);
866 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
868 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
869 array(' ', '<br />'), false);
873 if ($this->_features->gradecat) {
874 $mform->addElement('select', 'gradecat',
875 get_string('gradecategoryonmodform', 'grades'),
876 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
877 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
878 if (!$this->_features->rating) {
879 $mform->disabledIf('gradecat', 'grade[modgrade_type]', 'eq', 'none');
883 // Grade to pass.
884 $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
885 $mform->addHelpButton('gradepass', 'gradepass', 'grades');
886 $mform->setDefault('gradepass', '');
887 $mform->setType('gradepass', PARAM_RAW);
888 if (!$this->_features->rating) {
889 $mform->disabledIf('gradepass', 'grade[modgrade_type]', 'eq', 'none');
890 } else {
891 $mform->disabledIf('gradepass', 'assessed', 'eq', '0');
897 * Add an editor for an activity's introduction field.
898 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
899 * @param null $required Override system default for requiremodintro
900 * @param null $customlabel Override default label for editor
901 * @throws coding_exception
903 protected function add_intro_editor($required=null, $customlabel=null) {
904 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
905 debugging($str, DEBUG_DEVELOPER);
907 $this->standard_intro_elements($customlabel);
912 * Add an editor for an activity's introduction field.
914 * @param null $customlabel Override default label for editor
915 * @throws coding_exception
917 protected function standard_intro_elements($customlabel=null) {
918 global $CFG;
920 $required = $CFG->requiremodintro;
922 $mform = $this->_form;
923 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
925 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
926 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
927 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
928 if ($required) {
929 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
932 // If the 'show description' feature is enabled, this checkbox appears below the intro.
933 // We want to hide that when using the singleactivity course format because it is confusing.
934 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
935 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
936 $mform->addHelpButton('showdescription', 'showdescription');
941 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
943 * @param bool $cancel show cancel button
944 * @param string $submitlabel null means default, false means none, string is label text
945 * @param string $submit2label null means default, false means none, string is label text
946 * @return void
948 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
949 if (is_null($submitlabel)) {
950 $submitlabel = get_string('savechangesanddisplay');
953 if (is_null($submit2label)) {
954 $submit2label = get_string('savechangesandreturntocourse');
957 $mform = $this->_form;
959 // elements in a row need a group
960 $buttonarray = array();
962 // Label for the submit button to return to the course.
963 // Ignore this button in single activity format because it is confusing.
964 if ($submit2label !== false && $this->courseformat->has_view_page()) {
965 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
968 if ($submitlabel !== false) {
969 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
972 if ($cancel) {
973 $buttonarray[] = &$mform->createElement('cancel');
976 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
977 $mform->setType('buttonar', PARAM_RAW);
978 $mform->closeHeaderBefore('buttonar');
982 * Get the list of admin settings for this module and apply any locked settings.
983 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
984 * in that function because set_data has not been called yet.
986 * @return void
988 protected function apply_admin_locked_flags() {
989 global $OUTPUT;
991 if (!$this->applyadminlockedflags) {
992 return;
995 $settings = get_config($this->_modname);
996 $mform = $this->_form;
997 $lockedicon = html_writer::tag('span',
998 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
999 array('class' => 'action-icon'));
1000 $isupdate = !empty($this->_cm);
1002 foreach ($settings as $name => $value) {
1003 if (strpos('_', $name) !== false) {
1004 continue;
1006 if ($mform->elementExists($name)) {
1007 $element = $mform->getElement($name);
1008 $lockedsetting = $name . '_locked';
1009 if (!empty($settings->$lockedsetting)) {
1010 // Always lock locked settings for new modules,
1011 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1012 $value = $settings->$name;
1013 if ($isupdate && isset($this->current->$name)) {
1014 $value = $this->current->$name;
1016 if ($value == $settings->$name) {
1017 $mform->setConstant($name, $settings->$name);
1018 $element->setLabel($element->getLabel() . $lockedicon);
1019 // Do not use hardfreeze because we need the hidden input to check dependencies.
1020 $element->freeze();
1028 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
1030 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1031 * default date/time value should be relative to. If not passed, all
1032 * date/time fields are set relative to the users current midnight.
1033 * @return void
1035 public function apply_admin_defaults($datetimeoffsets = array()) {
1036 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1037 $this->applyadminlockedflags = true;
1039 $settings = get_config($this->_modname);
1040 $mform = $this->_form;
1041 $usermidnight = usergetmidnight(time());
1042 $isupdate = !empty($this->_cm);
1044 foreach ($settings as $name => $value) {
1045 if (strpos('_', $name) !== false) {
1046 continue;
1048 if ($mform->elementExists($name)) {
1049 $element = $mform->getElement($name);
1050 if (!$isupdate) {
1051 if ($element->getType() == 'date_time_selector') {
1052 $enabledsetting = $name . '_enabled';
1053 if (empty($settings->$enabledsetting)) {
1054 $mform->setDefault($name, 0);
1055 } else {
1056 $relativetime = $usermidnight;
1057 if (isset($datetimeoffsets[$name])) {
1058 $relativetime = $datetimeoffsets[$name];
1060 $mform->setDefault($name, $relativetime + $settings->$name);
1062 } else {
1063 $mform->setDefault($name, $settings->$name);
1066 $advancedsetting = $name . '_adv';
1067 if (!empty($settings->$advancedsetting)) {
1068 $mform->setAdvanced($name);
1075 * Allows modules to modify the data returned by form get_data().
1076 * This method is also called in the bulk activity completion form.
1078 * Only available on moodleform_mod.
1080 * @param stdClass $data passed by reference
1082 public function data_postprocessing($data) {
1086 * Return submitted data if properly submitted or returns NULL if validation fails or
1087 * if there is no submitted data.
1089 * Do not override this method, override data_postprocessing() instead.
1091 * @return object submitted data; NULL if not valid or not submitted or cancelled
1093 public function get_data() {
1094 $data = parent::get_data();
1095 if ($data) {
1096 // Convert the grade pass value - we may be using a language which uses commas,
1097 // rather than decimal points, in numbers. These need to be converted so that
1098 // they can be added to the DB.
1099 if (isset($data->gradepass)) {
1100 $data->gradepass = unformat_float($data->gradepass);
1103 $this->data_postprocessing($data);
1105 return $data;