Merge branch 'MDL-62560-master'
[moodle.git] / course / moodleform_mod.php
bloba3235ce1e00e1bd4fa928628b372b58e26e2b0d2
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');
293 // Nor does the group restrictions button.
294 if ($mform->elementExists('restrictgroupbutton')) {
295 $mform->removeElement('restrictgroupbutton');
300 // Completion: If necessary, freeze fields
301 $completion = new completion_info($COURSE);
302 if ($completion->is_enabled()) {
303 // If anybody has completed the activity, these options will be 'locked'
304 $completedcount = empty($this->_cm)
306 : $completion->count_user_data($this->_cm);
308 $freeze = false;
309 if (!$completedcount) {
310 if ($mform->elementExists('unlockcompletion')) {
311 $mform->removeElement('unlockcompletion');
313 // Automatically set to unlocked (note: this is necessary
314 // in order to make it recalculate completion once the option
315 // is changed, maybe someone has completed it now)
316 $mform->getElement('completionunlocked')->setValue(1);
317 } else {
318 // Has the element been unlocked, either by the button being pressed
319 // in this request, or the field already being set from a previous one?
320 if ($mform->exportValue('unlockcompletion') ||
321 $mform->exportValue('completionunlocked')) {
322 // Yes, add in warning text and set the hidden variable
323 $mform->insertElementBefore(
324 $mform->createElement('static', 'completedunlocked',
325 get_string('completedunlocked', 'completion'),
326 get_string('completedunlockedtext', 'completion')),
327 'unlockcompletion');
328 $mform->removeElement('unlockcompletion');
329 $mform->getElement('completionunlocked')->setValue(1);
330 } else {
331 // No, add in the warning text with the count (now we know
332 // it) before the unlock button
333 $mform->insertElementBefore(
334 $mform->createElement('static', 'completedwarning',
335 get_string('completedwarning', 'completion'),
336 get_string('completedwarningtext', 'completion', $completedcount)),
337 'unlockcompletion');
338 $freeze = true;
342 if ($freeze) {
343 $mform->freeze('completion');
344 if ($mform->elementExists('completionview')) {
345 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
347 if ($mform->elementExists('completionusegrade')) {
348 $mform->freeze('completionusegrade');
350 $mform->freeze($this->_customcompletionelements);
354 // Freeze admin defaults if required (and not different from default)
355 $this->apply_admin_locked_flags();
358 // form verification
359 function validation($data, $files) {
360 global $COURSE, $DB, $CFG;
361 $errors = parent::validation($data, $files);
363 $mform =& $this->_form;
365 $errors = array();
367 if ($mform->elementExists('name')) {
368 $name = trim($data['name']);
369 if ($name == '') {
370 $errors['name'] = get_string('required');
374 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
375 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
376 if ($data['coursemodule']) {
377 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
378 } else {
379 $cm = null;
382 if ($mform->elementExists('cmidnumber')) {
383 // verify the idnumber
384 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
385 $errors['cmidnumber'] = get_string('idnumbertaken');
389 // Ratings: Don't let them select an aggregate type without selecting a scale.
390 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
391 // invalid. If ratings have been selected then the user must select either a scale or max points.
392 // This matches (horrible) logic in data_preprocessing.
393 if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
394 $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
397 // Check that the grade pass is a valid number.
398 $gradepassvalid = false;
399 if (isset($data['gradepass'])) {
400 if (unformat_float($data['gradepass'], true) === false) {
401 $errors['gradepass'] = get_string('err_numeric', 'form');
402 } else {
403 $gradepassvalid = true;
407 // Grade to pass: ensure that the grade to pass is valid for points and scales.
408 // If we are working with a scale, convert into a positive number for validation.
409 if ($gradepassvalid && isset($data['gradepass']) && (!empty($data['grade']) || !empty($data['scale']))) {
410 $scale = !empty($data['grade']) ? $data['grade'] : $data['scale'];
411 if ($scale < 0) {
412 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
413 $grade = count(explode(',', $scalevalues->scale));
414 } else {
415 $grade = $scale;
417 if (unformat_float($data['gradepass']) > $grade) {
418 $errors['gradepass'] = get_string('gradepassgreaterthangrade', 'grades', $grade);
422 // Completion: Don't let them choose automatic completion without turning
423 // on some conditions. Ignore this check when completion settings are
424 // locked, as the options are then disabled.
425 if (array_key_exists('completion', $data) &&
426 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
427 !empty($data['completionunlocked'])) {
428 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
429 !$this->completion_rule_enabled($data)) {
430 $errors['completion'] = get_string('badautocompletion', 'completion');
434 // Availability: Check availability field does not have errors.
435 if (!empty($CFG->enableavailability)) {
436 \core_availability\frontend::report_validation_errors($data, $errors);
439 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
440 if (!empty($pluginerrors)) {
441 $errors = array_merge($errors, $pluginerrors);
444 return $errors;
448 * Extend the validation function from any other plugin.
450 * @param stdClass $data The form data.
451 * @return array $errors The list of errors keyed by element name.
453 protected function plugin_extend_coursemodule_validation($data) {
454 $errors = array();
456 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
457 foreach ($callbacks as $type => $plugins) {
458 foreach ($plugins as $plugin => $pluginfunction) {
459 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
460 $pluginerrors = $pluginfunction($this, $data);
461 if (!empty($pluginerrors)) {
462 $errors = array_merge($errors, $pluginerrors);
466 return $errors;
470 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
471 * form definition (new entry form); this function is used to load in data where values
472 * already exist and data is being edited (edit entry form).
474 * @param mixed $default_values object or array of default values
476 function set_data($default_values) {
477 if (is_object($default_values)) {
478 $default_values = (array)$default_values;
481 $this->data_preprocessing($default_values);
482 parent::set_data($default_values);
486 * Adds all the standard elements to a form to edit the settings for an activity module.
488 function standard_coursemodule_elements(){
489 global $COURSE, $CFG, $DB;
490 $mform =& $this->_form;
492 $this->_outcomesused = false;
493 if ($this->_features->outcomes) {
494 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
495 $this->_outcomesused = true;
496 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
497 foreach($outcomes as $outcome) {
498 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
504 if ($this->_features->rating) {
505 require_once($CFG->dirroot.'/rating/lib.php');
506 $rm = new rating_manager();
508 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
510 $permission=CAP_ALLOW;
511 $rolenamestring = null;
512 $isupdate = false;
513 if (!empty($this->_cm)) {
514 $isupdate = true;
515 $context = context_module::instance($this->_cm->id);
517 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
518 $rolenamestring = implode(', ', $rolenames);
519 } else {
520 $rolenamestring = get_string('capabilitychecknotavailable','rating');
522 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
523 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
525 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
526 $mform->setDefault('assessed', 0);
527 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
529 $gradeoptions = array('isupdate' => $isupdate,
530 'currentgrade' => false,
531 'hasgrades' => false,
532 'canrescale' => $this->_features->canrescale,
533 'useratings' => $this->_features->rating);
534 if ($isupdate) {
535 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
536 'itemmodule' => $this->_cm->modname,
537 'iteminstance' => $this->_cm->instance,
538 'itemnumber' => 0,
539 'courseid' => $COURSE->id));
540 if ($gradeitem) {
541 $gradeoptions['currentgrade'] = $gradeitem->grademax;
542 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
543 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
544 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
547 $mform->addElement('modgrade', 'scale', get_string('scale'), $gradeoptions);
548 $mform->disabledIf('scale', 'assessed', 'eq', 0);
549 $mform->addHelpButton('scale', 'modgrade', 'grades');
550 $mform->setDefault('scale', $CFG->gradepointdefault);
552 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
553 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
555 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
556 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
557 $mform->disabledIf('assesstimestart', 'ratingtime');
559 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
560 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
561 $mform->disabledIf('assesstimefinish', 'ratingtime');
564 //doing this here means splitting up the grade related settings on the lesson settings page
565 //$this->standard_grading_coursemodule_elements();
567 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
569 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section);
570 $allowstealth = !empty($CFG->allowstealth) && $this->courseformat->allow_stealth_module_visibility($this->_cm, $section);
571 if ($allowstealth && $section->visible) {
572 $modvisiblelabel = 'modvisiblewithstealth';
573 } else if ($section->visible) {
574 $modvisiblelabel = 'modvisible';
575 } else {
576 $modvisiblelabel = 'modvisiblehiddensection';
578 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
579 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible, 'cm' => $this->_cm));
580 $mform->addHelpButton('visible', $modvisiblelabel);
581 if (!empty($this->_cm)) {
582 $context = context_module::instance($this->_cm->id);
583 if (!has_capability('moodle/course:activityvisibility', $context)) {
584 $mform->hardFreeze('visible');
588 if ($this->_features->idnumber) {
589 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
590 $mform->setType('cmidnumber', PARAM_RAW);
591 $mform->addHelpButton('cmidnumber', 'idnumbermod');
594 if ($this->_features->groups) {
595 $options = array(NOGROUPS => get_string('groupsnone'),
596 SEPARATEGROUPS => get_string('groupsseparate'),
597 VISIBLEGROUPS => get_string('groupsvisible'));
598 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
599 $mform->addHelpButton('groupmode', 'groupmode', 'group');
602 if ($this->_features->groupings) {
603 // Groupings selector - used to select grouping for groups in activity.
604 $options = array();
605 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
606 foreach ($groupings as $grouping) {
607 $options[$grouping->id] = format_string($grouping->name);
610 core_collator::asort($options);
611 $options = array(0 => get_string('none')) + $options;
612 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
613 $mform->addHelpButton('groupingid', 'grouping', 'group');
616 if (!empty($CFG->enableavailability)) {
617 // Add special button to end of previous section if groups/groupings
618 // are enabled.
619 if ($this->_features->groups || $this->_features->groupings) {
620 $mform->addElement('static', 'restrictgroupbutton', '',
621 html_writer::tag('button', get_string('restrictbygroup', 'availability'),
622 array('id' => 'restrictbygroup', 'disabled' => 'disabled', 'class' => 'btn btn-secondary')));
625 // Availability field. This is just a textarea; the user interface
626 // interaction is all implemented in JavaScript.
627 $mform->addElement('header', 'availabilityconditionsheader',
628 get_string('restrictaccess', 'availability'));
629 // Note: This field cannot be named 'availability' because that
630 // conflicts with fields in existing modules (such as assign).
631 // So it uses a long name that will not conflict.
632 $mform->addElement('textarea', 'availabilityconditionsjson',
633 get_string('accessrestrictions', 'availability'));
634 // The _cm variable may not be a proper cm_info, so get one from modinfo.
635 if ($this->_cm) {
636 $modinfo = get_fast_modinfo($COURSE);
637 $cm = $modinfo->get_cm($this->_cm->id);
638 } else {
639 $cm = null;
641 \core_availability\frontend::include_all_javascript($COURSE, $cm);
644 // Conditional activities: completion tracking section
645 if(!isset($completion)) {
646 $completion = new completion_info($COURSE);
648 if ($completion->is_enabled()) {
649 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
650 // Unlock button for if people have completed it (will
651 // be removed in definition_after_data if they haven't)
652 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
653 $mform->registerNoSubmitButton('unlockcompletion');
654 $mform->addElement('hidden', 'completionunlocked', 0);
655 $mform->setType('completionunlocked', PARAM_INT);
657 $trackingdefault = COMPLETION_TRACKING_NONE;
658 // If system and activity default is on, set it.
659 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
660 $hasrules = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_HAS_RULES, true);
661 $tracksviews = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, true);
662 if ($hasrules || $tracksviews) {
663 $trackingdefault = COMPLETION_TRACKING_AUTOMATIC;
664 } else {
665 $trackingdefault = COMPLETION_TRACKING_MANUAL;
669 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
670 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
671 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
672 $mform->setDefault('completion', $trackingdefault);
673 $mform->addHelpButton('completion', 'completion', 'completion');
675 // Automatic completion once you view it
676 $gotcompletionoptions = false;
677 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
678 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
679 get_string('completionview_desc', 'completion'));
680 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
681 // Check by default if automatic completion tracking is set.
682 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC) {
683 $mform->setDefault('completionview', 1);
685 $gotcompletionoptions = true;
688 // Automatic completion once it's graded
689 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
690 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
691 get_string('completionusegrade_desc', 'completion'));
692 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
693 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
694 $gotcompletionoptions = true;
696 // If using the rating system, there is no grade unless ratings are enabled.
697 if ($this->_features->rating) {
698 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
702 // Automatic completion according to module-specific rules
703 $this->_customcompletionelements = $this->add_completion_rules();
704 foreach ($this->_customcompletionelements as $element) {
705 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
708 $gotcompletionoptions = $gotcompletionoptions ||
709 count($this->_customcompletionelements)>0;
711 // Automatic option only appears if possible
712 if ($gotcompletionoptions) {
713 $mform->getElement('completion')->addOption(
714 get_string('completion_automatic', 'completion'),
715 COMPLETION_TRACKING_AUTOMATIC);
718 // Completion expected at particular date? (For progress tracking)
719 $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
720 array('optional' => true));
721 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
722 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
725 // Populate module tags.
726 if (core_tag_tag::is_enabled('core', 'course_modules')) {
727 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
728 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
729 if ($this->_cm) {
730 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
731 $mform->setDefault('tags', $tags);
735 $this->standard_hidden_coursemodule_elements();
737 $this->plugin_extend_coursemodule_standard_elements();
741 * Plugins can extend the coursemodule settings form.
743 protected function plugin_extend_coursemodule_standard_elements() {
744 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
745 foreach ($callbacks as $type => $plugins) {
746 foreach ($plugins as $plugin => $pluginfunction) {
747 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
748 // directly.
749 $pluginfunction($this, $this->_form);
755 * Can be overridden to add custom completion rules if the module wishes
756 * them. If overriding this, you should also override completion_rule_enabled.
757 * <p>
758 * Just add elements to the form as needed and return the list of IDs. The
759 * system will call disabledIf and handle other behaviour for each returned
760 * ID.
761 * @return array Array of string IDs of added items, empty array if none
763 function add_completion_rules() {
764 return array();
768 * Called during validation. Override to indicate, based on the data, whether
769 * a custom completion rule is enabled (selected).
771 * @param array $data Input data (not yet validated)
772 * @return bool True if one or more rules is enabled, false if none are;
773 * default returns false
775 function completion_rule_enabled($data) {
776 return false;
779 function standard_hidden_coursemodule_elements(){
780 $mform =& $this->_form;
781 $mform->addElement('hidden', 'course', 0);
782 $mform->setType('course', PARAM_INT);
784 $mform->addElement('hidden', 'coursemodule', 0);
785 $mform->setType('coursemodule', PARAM_INT);
787 $mform->addElement('hidden', 'section', 0);
788 $mform->setType('section', PARAM_INT);
790 $mform->addElement('hidden', 'module', 0);
791 $mform->setType('module', PARAM_INT);
793 $mform->addElement('hidden', 'modulename', '');
794 $mform->setType('modulename', PARAM_PLUGIN);
796 $mform->addElement('hidden', 'instance', 0);
797 $mform->setType('instance', PARAM_INT);
799 $mform->addElement('hidden', 'add', 0);
800 $mform->setType('add', PARAM_ALPHA);
802 $mform->addElement('hidden', 'update', 0);
803 $mform->setType('update', PARAM_INT);
805 $mform->addElement('hidden', 'return', 0);
806 $mform->setType('return', PARAM_BOOL);
808 $mform->addElement('hidden', 'sr', 0);
809 $mform->setType('sr', PARAM_INT);
812 public function standard_grading_coursemodule_elements() {
813 global $COURSE, $CFG;
814 $mform =& $this->_form;
815 $isupdate = !empty($this->_cm);
816 $gradeoptions = array('isupdate' => $isupdate,
817 'currentgrade' => false,
818 'hasgrades' => false,
819 'canrescale' => $this->_features->canrescale,
820 'useratings' => $this->_features->rating);
822 if ($this->_features->hasgrades) {
824 if (!$this->_features->rating || $this->_features->gradecat) {
825 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
828 //if supports grades and grades arent being handled via ratings
829 if (!$this->_features->rating) {
831 if ($isupdate) {
832 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
833 'itemmodule' => $this->_cm->modname,
834 'iteminstance' => $this->_cm->instance,
835 'itemnumber' => 0,
836 'courseid' => $COURSE->id));
837 if ($gradeitem) {
838 $gradeoptions['currentgrade'] = $gradeitem->grademax;
839 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
840 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
841 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
844 $mform->addElement('modgrade', 'grade', get_string('grade'), $gradeoptions);
845 $mform->addHelpButton('grade', 'modgrade', 'grades');
846 $mform->setDefault('grade', $CFG->gradepointdefault);
849 if ($this->_features->advancedgrading
850 and !empty($this->current->_advancedgradingdata['methods'])
851 and !empty($this->current->_advancedgradingdata['areas'])) {
853 if (count($this->current->_advancedgradingdata['areas']) == 1) {
854 // if there is just one gradable area (most cases), display just the selector
855 // without its name to make UI simplier
856 $areadata = reset($this->current->_advancedgradingdata['areas']);
857 $areaname = key($this->current->_advancedgradingdata['areas']);
858 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
859 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
860 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
861 if (!$this->_features->rating) {
862 $mform->disabledIf('advancedgradingmethod_'.$areaname, 'grade[modgrade_type]', 'eq', 'none');
865 } else {
866 // the module defines multiple gradable areas, display a selector
867 // for each of them together with a name of the area
868 $areasgroup = array();
869 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
870 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
871 $areadata['title'], $this->current->_advancedgradingdata['methods']);
872 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
874 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
875 array(' ', '<br />'), false);
879 if ($this->_features->gradecat) {
880 $mform->addElement('select', 'gradecat',
881 get_string('gradecategoryonmodform', 'grades'),
882 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
883 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
884 if (!$this->_features->rating) {
885 $mform->disabledIf('gradecat', 'grade[modgrade_type]', 'eq', 'none');
889 // Grade to pass.
890 $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
891 $mform->addHelpButton('gradepass', 'gradepass', 'grades');
892 $mform->setDefault('gradepass', '');
893 $mform->setType('gradepass', PARAM_RAW);
894 if (!$this->_features->rating) {
895 $mform->disabledIf('gradepass', 'grade[modgrade_type]', 'eq', 'none');
896 } else {
897 $mform->disabledIf('gradepass', 'assessed', 'eq', '0');
903 * Add an editor for an activity's introduction field.
904 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
905 * @param null $required Override system default for requiremodintro
906 * @param null $customlabel Override default label for editor
907 * @throws coding_exception
909 protected function add_intro_editor($required=null, $customlabel=null) {
910 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
911 debugging($str, DEBUG_DEVELOPER);
913 $this->standard_intro_elements($customlabel);
918 * Add an editor for an activity's introduction field.
920 * @param null $customlabel Override default label for editor
921 * @throws coding_exception
923 protected function standard_intro_elements($customlabel=null) {
924 global $CFG;
926 $required = $CFG->requiremodintro;
928 $mform = $this->_form;
929 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
931 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
932 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
933 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
934 if ($required) {
935 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
938 // If the 'show description' feature is enabled, this checkbox appears below the intro.
939 // We want to hide that when using the singleactivity course format because it is confusing.
940 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
941 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
942 $mform->addHelpButton('showdescription', 'showdescription');
947 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
949 * @param bool $cancel show cancel button
950 * @param string $submitlabel null means default, false means none, string is label text
951 * @param string $submit2label null means default, false means none, string is label text
952 * @return void
954 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
955 if (is_null($submitlabel)) {
956 $submitlabel = get_string('savechangesanddisplay');
959 if (is_null($submit2label)) {
960 $submit2label = get_string('savechangesandreturntocourse');
963 $mform = $this->_form;
965 // elements in a row need a group
966 $buttonarray = array();
968 // Label for the submit button to return to the course.
969 // Ignore this button in single activity format because it is confusing.
970 if ($submit2label !== false && $this->courseformat->has_view_page()) {
971 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
974 if ($submitlabel !== false) {
975 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
978 if ($cancel) {
979 $buttonarray[] = &$mform->createElement('cancel');
982 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
983 $mform->setType('buttonar', PARAM_RAW);
984 $mform->closeHeaderBefore('buttonar');
988 * Get the list of admin settings for this module and apply any locked settings.
989 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
990 * in that function because set_data has not been called yet.
992 * @return void
994 protected function apply_admin_locked_flags() {
995 global $OUTPUT;
997 if (!$this->applyadminlockedflags) {
998 return;
1001 $settings = get_config($this->_modname);
1002 $mform = $this->_form;
1003 $lockedicon = html_writer::tag('span',
1004 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
1005 array('class' => 'action-icon'));
1006 $isupdate = !empty($this->_cm);
1008 foreach ($settings as $name => $value) {
1009 if (strpos('_', $name) !== false) {
1010 continue;
1012 if ($mform->elementExists($name)) {
1013 $element = $mform->getElement($name);
1014 $lockedsetting = $name . '_locked';
1015 if (!empty($settings->$lockedsetting)) {
1016 // Always lock locked settings for new modules,
1017 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1018 $value = $settings->$name;
1019 if ($isupdate && isset($this->current->$name)) {
1020 $value = $this->current->$name;
1022 if ($value == $settings->$name) {
1023 $mform->setConstant($name, $settings->$name);
1024 $element->setLabel($element->getLabel() . $lockedicon);
1025 // Do not use hardfreeze because we need the hidden input to check dependencies.
1026 $element->freeze();
1034 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
1036 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1037 * default date/time value should be relative to. If not passed, all
1038 * date/time fields are set relative to the users current midnight.
1039 * @return void
1041 public function apply_admin_defaults($datetimeoffsets = array()) {
1042 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1043 $this->applyadminlockedflags = true;
1045 $settings = get_config($this->_modname);
1046 $mform = $this->_form;
1047 $usermidnight = usergetmidnight(time());
1048 $isupdate = !empty($this->_cm);
1050 foreach ($settings as $name => $value) {
1051 if (strpos('_', $name) !== false) {
1052 continue;
1054 if ($mform->elementExists($name)) {
1055 $element = $mform->getElement($name);
1056 if (!$isupdate) {
1057 if ($element->getType() == 'date_time_selector') {
1058 $enabledsetting = $name . '_enabled';
1059 if (empty($settings->$enabledsetting)) {
1060 $mform->setDefault($name, 0);
1061 } else {
1062 $relativetime = $usermidnight;
1063 if (isset($datetimeoffsets[$name])) {
1064 $relativetime = $datetimeoffsets[$name];
1066 $mform->setDefault($name, $relativetime + $settings->$name);
1068 } else {
1069 $mform->setDefault($name, $settings->$name);
1072 $advancedsetting = $name . '_adv';
1073 if (!empty($settings->$advancedsetting)) {
1074 $mform->setAdvanced($name);
1081 * Allows modules to modify the data returned by form get_data().
1082 * This method is also called in the bulk activity completion form.
1084 * Only available on moodleform_mod.
1086 * @param stdClass $data passed by reference
1088 public function data_postprocessing($data) {
1092 * Return submitted data if properly submitted or returns NULL if validation fails or
1093 * if there is no submitted data.
1095 * Do not override this method, override data_postprocessing() instead.
1097 * @return object submitted data; NULL if not valid or not submitted or cancelled
1099 public function get_data() {
1100 $data = parent::get_data();
1101 if ($data) {
1102 // Convert the grade pass value - we may be using a language which uses commas,
1103 // rather than decimal points, in numbers. These need to be converted so that
1104 // they can be added to the DB.
1105 if (isset($data->gradepass)) {
1106 $data->gradepass = unformat_float($data->gradepass);
1109 $this->data_postprocessing($data);
1111 return $data;