Merge branch 'MDL-52777-master-bug' of github.com:andrewnicols/moodle
[moodle.git] / course / moodleform_mod.php
blobe467a9e77f836de93a401b73341a49ef72a37376
1 <?php
2 require_once ($CFG->libdir.'/formslib.php');
3 require_once($CFG->libdir.'/completionlib.php');
5 /**
6 * This class adds extra methods to form wrapper specific to be used for module
7 * add / update forms mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html
8 */
9 abstract class moodleform_mod extends moodleform {
10 /** Current data */
11 protected $current;
12 /**
13 * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
14 * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
15 * update one.
17 * @var mixed
19 protected $_instance;
20 /**
21 * Section of course that module instance will be put in or is in.
22 * This is always the section number itself (column 'section' from 'course_sections' table).
24 * @var mixed
26 protected $_section;
27 /**
28 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
29 * update one.
31 * @var mixed
33 protected $_cm;
35 /**
36 * Current course.
38 * @var mixed
40 protected $_course;
42 /**
43 * List of modform features
45 protected $_features;
46 /**
47 * @var array Custom completion-rule elements, if enabled
49 protected $_customcompletionelements;
50 /**
51 * @var string name of module
53 protected $_modname;
54 /** current context, course or module depends if already exists*/
55 protected $context;
57 /** a flag indicating whether outcomes are being used*/
58 protected $_outcomesused;
60 /**
61 * @var bool A flag used to indicate that this module should lock settings
62 * based on admin settings flags in definition_after_data.
64 protected $applyadminlockedflags = false;
66 /** @var object The course format of the current course. */
67 protected $courseformat;
69 public function __construct($current, $section, $cm, $course) {
70 global $CFG;
72 $this->current = $current;
73 $this->_instance = $current->instance;
74 $this->_section = $section;
75 $this->_cm = $cm;
76 $this->_course = $course;
77 if ($this->_cm) {
78 $this->context = context_module::instance($this->_cm->id);
79 } else {
80 $this->context = context_course::instance($course->id);
83 // Set the course format.
84 require_once($CFG->dirroot . '/course/format/lib.php');
85 $this->courseformat = course_get_format($course);
87 // Guess module name
88 $matches = array();
89 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
90 debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
91 print_error('unknownmodulename');
93 $this->_modname = $matches[1];
94 $this->init_features();
95 parent::__construct('modedit.php');
98 /**
99 * Old syntax of class constructor. Deprecated in PHP7.
101 * @deprecated since Moodle 3.1
103 public function moodleform_mod($current, $section, $cm, $course) {
104 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
105 self::__construct($current, $section, $cm, $course);
109 * Get the current data for the form.
110 * @return stdClass|null
112 public function get_current() {
113 return $this->current;
117 * Get the DB record for the current instance.
118 * @return stdClass|null
120 public function get_instance() {
121 return $this->_instance;
125 * Get the course section number (relative).
126 * @return int
128 public function get_section() {
129 return $this->_section;
133 * Get the course id.
134 * @return int
136 public function get_course() {
137 return $this->_course;
141 * Get the course module object.
142 * @return stdClass|null
144 public function get_coursemodule() {
145 return $this->_cm;
149 * Return the course context for new modules, or the module context for existing modules.
150 * @return context
152 public function get_context() {
153 return $this->context;
157 * Return the features this module supports.
158 * @return stdClass
160 public function get_features() {
161 return $this->_features;
165 protected function init_features() {
166 global $CFG;
168 $this->_features = new stdClass();
169 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
170 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
171 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
172 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
173 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
174 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
175 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
176 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
177 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
178 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
179 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
180 $this->_features->canrescale = (component_callback_exists('mod_' . $this->_modname, 'rescale_activity_grades') !== false);
184 * Only available on moodleform_mod.
186 * @param array $default_values passed by reference
188 function data_preprocessing(&$default_values){
189 if (empty($default_values['scale'])) {
190 $default_values['assessed'] = 0;
193 if (empty($default_values['assessed'])){
194 $default_values['ratingtime'] = 0;
195 } else {
196 $default_values['ratingtime']=
197 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
202 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
204 function definition_after_data() {
205 global $CFG, $COURSE;
206 $mform =& $this->_form;
208 if ($id = $mform->getElementValue('update')) {
209 $modulename = $mform->getElementValue('modulename');
210 $instance = $mform->getElementValue('instance');
212 if ($this->_features->gradecat) {
213 $gradecat = false;
214 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
215 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
216 if (!empty($outcomes)) {
217 $gradecat = true;
221 $hasgradeitems = false;
222 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
223 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
224 if (!empty($items)) {
225 foreach ($items as $item) {
226 if (!empty($item->outcomeid)) {
227 $elname = 'outcome_'.$item->outcomeid;
228 if ($mform->elementExists($elname)) {
229 $mform->hardFreeze($elname); // prevent removing of existing outcomes
231 } else {
232 $hasgradeitems = true;
236 foreach ($items as $item) {
237 if (is_bool($gradecat)) {
238 $gradecat = $item->categoryid;
239 continue;
241 if ($gradecat != $item->categoryid) {
242 //mixed categories
243 $gradecat = false;
244 break;
249 if (!$hasgradeitems && $mform->elementExists('gradepass')) {
250 // Remove form element 'Grade to pass' since there are no grade items (when rating not selected).
251 $mform->removeElement('gradepass');
254 if ($gradecat === false) {
255 // items and outcomes in different categories - remove the option
256 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
257 if ($mform->elementExists('gradecat')) {
258 $mform->removeElement('gradecat');
259 if ($this->_features->rating && !$mform->elementExists('gradepass')) {
260 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
261 $mform->removeElement('modstandardgrade');
268 if ($COURSE->groupmodeforce) {
269 if ($mform->elementExists('groupmode')) {
270 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
274 // Don't disable/remove groupingid if it is currently set to something,
275 // otherwise you cannot turn it off at same time as turning off other
276 // option (MDL-30764)
277 if (empty($this->_cm) || !$this->_cm->groupingid) {
278 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
279 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
281 } else if (!$mform->elementExists('groupmode')) {
282 // Groupings have no use without groupmode.
283 if ($mform->elementExists('groupingid')) {
284 $mform->removeElement('groupingid');
289 // Completion: If necessary, freeze fields
290 $completion = new completion_info($COURSE);
291 if ($completion->is_enabled()) {
292 // If anybody has completed the activity, these options will be 'locked'
293 $completedcount = empty($this->_cm)
295 : $completion->count_user_data($this->_cm);
297 $freeze = false;
298 if (!$completedcount) {
299 if ($mform->elementExists('unlockcompletion')) {
300 $mform->removeElement('unlockcompletion');
302 // Automatically set to unlocked (note: this is necessary
303 // in order to make it recalculate completion once the option
304 // is changed, maybe someone has completed it now)
305 $mform->getElement('completionunlocked')->setValue(1);
306 } else {
307 // Has the element been unlocked, either by the button being pressed
308 // in this request, or the field already being set from a previous one?
309 if ($mform->exportValue('unlockcompletion') ||
310 $mform->exportValue('completionunlocked')) {
311 // Yes, add in warning text and set the hidden variable
312 $mform->insertElementBefore(
313 $mform->createElement('static', 'completedunlocked',
314 get_string('completedunlocked', 'completion'),
315 get_string('completedunlockedtext', 'completion')),
316 'unlockcompletion');
317 $mform->removeElement('unlockcompletion');
318 $mform->getElement('completionunlocked')->setValue(1);
319 } else {
320 // No, add in the warning text with the count (now we know
321 // it) before the unlock button
322 $mform->insertElementBefore(
323 $mform->createElement('static', 'completedwarning',
324 get_string('completedwarning', 'completion'),
325 get_string('completedwarningtext', 'completion', $completedcount)),
326 'unlockcompletion');
327 $freeze = true;
331 if ($freeze) {
332 $mform->freeze('completion');
333 if ($mform->elementExists('completionview')) {
334 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
336 if ($mform->elementExists('completionusegrade')) {
337 $mform->freeze('completionusegrade');
339 $mform->freeze($this->_customcompletionelements);
343 // Freeze admin defaults if required (and not different from default)
344 $this->apply_admin_locked_flags();
347 // form verification
348 function validation($data, $files) {
349 global $COURSE, $DB, $CFG;
350 $errors = parent::validation($data, $files);
352 $mform =& $this->_form;
354 $errors = array();
356 if ($mform->elementExists('name')) {
357 $name = trim($data['name']);
358 if ($name == '') {
359 $errors['name'] = get_string('required');
363 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
364 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
365 if ($data['coursemodule']) {
366 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
367 } else {
368 $cm = null;
371 if ($mform->elementExists('cmidnumber')) {
372 // verify the idnumber
373 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
374 $errors['cmidnumber'] = get_string('idnumbertaken');
378 // Ratings: Don't let them select an aggregate type without selecting a scale.
379 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
380 // invalid. If ratings have been selected then the user must select either a scale or max points.
381 // This matches (horrible) logic in data_preprocessing.
382 if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
383 $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
386 // Check that the grade pass is a valid number.
387 $gradepassvalid = false;
388 if (isset($data['gradepass'])) {
389 if (unformat_float($data['gradepass'], true) === false) {
390 $errors['gradepass'] = get_string('err_numeric', 'form');
391 } else {
392 $gradepassvalid = true;
396 // Grade to pass: ensure that the grade to pass is valid for points and scales.
397 // If we are working with a scale, convert into a positive number for validation.
398 if ($gradepassvalid && isset($data['gradepass']) && (!empty($data['grade']) || !empty($data['scale']))) {
399 $scale = !empty($data['grade']) ? $data['grade'] : $data['scale'];
400 if ($scale < 0) {
401 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
402 $grade = count(explode(',', $scalevalues->scale));
403 } else {
404 $grade = $scale;
406 if ($data['gradepass'] > $grade) {
407 $errors['gradepass'] = get_string('gradepassgreaterthangrade', 'grades', $grade);
411 // Completion: Don't let them choose automatic completion without turning
412 // on some conditions. Ignore this check when completion settings are
413 // locked, as the options are then disabled.
414 if (array_key_exists('completion', $data) &&
415 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
416 !empty($data['completionunlocked'])) {
417 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
418 !$this->completion_rule_enabled($data)) {
419 $errors['completion'] = get_string('badautocompletion', 'completion');
423 // Availability: Check availability field does not have errors.
424 if (!empty($CFG->enableavailability)) {
425 \core_availability\frontend::report_validation_errors($data, $errors);
428 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
429 if (!empty($pluginerrors)) {
430 $errors = array_merge($errors, $pluginerrors);
433 return $errors;
437 * Extend the validation function from any other plugin.
439 * @param stdClass $data The form data.
440 * @return array $errors The list of errors keyed by element name.
442 protected function plugin_extend_coursemodule_validation($data) {
443 $errors = array();
445 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
446 foreach ($callbacks as $type => $plugins) {
447 foreach ($plugins as $plugin => $pluginfunction) {
448 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
449 $pluginerrors = $pluginfunction($this, $data);
450 if (!empty($pluginerrors)) {
451 $errors = array_merge($errors, $pluginerrors);
455 return $errors;
459 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
460 * form definition (new entry form); this function is used to load in data where values
461 * already exist and data is being edited (edit entry form).
463 * @param mixed $default_values object or array of default values
465 function set_data($default_values) {
466 if (is_object($default_values)) {
467 $default_values = (array)$default_values;
470 $this->data_preprocessing($default_values);
471 parent::set_data($default_values);
475 * Adds all the standard elements to a form to edit the settings for an activity module.
477 function standard_coursemodule_elements(){
478 global $COURSE, $CFG, $DB;
479 $mform =& $this->_form;
481 $this->_outcomesused = false;
482 if ($this->_features->outcomes) {
483 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
484 $this->_outcomesused = true;
485 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
486 foreach($outcomes as $outcome) {
487 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
493 if ($this->_features->rating) {
494 require_once($CFG->dirroot.'/rating/lib.php');
495 $rm = new rating_manager();
497 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
499 $permission=CAP_ALLOW;
500 $rolenamestring = null;
501 $isupdate = false;
502 if (!empty($this->_cm)) {
503 $isupdate = true;
504 $context = context_module::instance($this->_cm->id);
506 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
507 $rolenamestring = implode(', ', $rolenames);
508 } else {
509 $rolenamestring = get_string('capabilitychecknotavailable','rating');
511 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
512 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
514 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
515 $mform->setDefault('assessed', 0);
516 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
518 $gradeoptions = array('isupdate' => $isupdate,
519 'currentgrade' => false,
520 'hasgrades' => false,
521 'canrescale' => $this->_features->canrescale,
522 'useratings' => $this->_features->rating);
523 if ($isupdate) {
524 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
525 'itemmodule' => $this->_cm->modname,
526 'iteminstance' => $this->_cm->instance,
527 'itemnumber' => 0,
528 'courseid' => $COURSE->id));
529 if ($gradeitem) {
530 $gradeoptions['currentgrade'] = $gradeitem->grademax;
531 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
532 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
533 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
536 $mform->addElement('modgrade', 'scale', get_string('scale'), $gradeoptions);
537 $mform->disabledIf('scale', 'assessed', 'eq', 0);
538 $mform->addHelpButton('scale', 'modgrade', 'grades');
539 $mform->setDefault('scale', $CFG->gradepointdefault);
541 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
542 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
544 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
545 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
546 $mform->disabledIf('assesstimestart', 'ratingtime');
548 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
549 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
550 $mform->disabledIf('assesstimefinish', 'ratingtime');
553 //doing this here means splitting up the grade related settings on the lesson settings page
554 //$this->standard_grading_coursemodule_elements();
556 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
558 $mform->addElement('modvisible', 'visible', get_string('visible'));
559 if (!empty($this->_cm)) {
560 $context = context_module::instance($this->_cm->id);
561 if (!has_capability('moodle/course:activityvisibility', $context)) {
562 $mform->hardFreeze('visible');
566 if ($this->_features->idnumber) {
567 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
568 $mform->setType('cmidnumber', PARAM_RAW);
569 $mform->addHelpButton('cmidnumber', 'idnumbermod');
572 if ($this->_features->groups) {
573 $options = array(NOGROUPS => get_string('groupsnone'),
574 SEPARATEGROUPS => get_string('groupsseparate'),
575 VISIBLEGROUPS => get_string('groupsvisible'));
576 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
577 $mform->addHelpButton('groupmode', 'groupmode', 'group');
580 if ($this->_features->groupings) {
581 // Groupings selector - used to select grouping for groups in activity.
582 $options = array();
583 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
584 foreach ($groupings as $grouping) {
585 $options[$grouping->id] = format_string($grouping->name);
588 core_collator::asort($options);
589 $options = array(0 => get_string('none')) + $options;
590 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
591 $mform->addHelpButton('groupingid', 'grouping', 'group');
594 if (!empty($CFG->enableavailability)) {
595 // Add special button to end of previous section if groups/groupings
596 // are enabled.
597 if ($this->_features->groups || $this->_features->groupings) {
598 $mform->addElement('static', 'restrictgroupbutton', '',
599 html_writer::tag('button', get_string('restrictbygroup', 'availability'),
600 array('id' => 'restrictbygroup', 'disabled' => 'disabled')));
603 // Availability field. This is just a textarea; the user interface
604 // interaction is all implemented in JavaScript.
605 $mform->addElement('header', 'availabilityconditionsheader',
606 get_string('restrictaccess', 'availability'));
607 // Note: This field cannot be named 'availability' because that
608 // conflicts with fields in existing modules (such as assign).
609 // So it uses a long name that will not conflict.
610 $mform->addElement('textarea', 'availabilityconditionsjson',
611 get_string('accessrestrictions', 'availability'));
612 // The _cm variable may not be a proper cm_info, so get one from modinfo.
613 if ($this->_cm) {
614 $modinfo = get_fast_modinfo($COURSE);
615 $cm = $modinfo->get_cm($this->_cm->id);
616 } else {
617 $cm = null;
619 \core_availability\frontend::include_all_javascript($COURSE, $cm);
622 // Conditional activities: completion tracking section
623 if(!isset($completion)) {
624 $completion = new completion_info($COURSE);
626 if ($completion->is_enabled()) {
627 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
629 // Unlock button for if people have completed it (will
630 // be removed in definition_after_data if they haven't)
631 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
632 $mform->registerNoSubmitButton('unlockcompletion');
633 $mform->addElement('hidden', 'completionunlocked', 0);
634 $mform->setType('completionunlocked', PARAM_INT);
636 $trackingdefault = COMPLETION_TRACKING_NONE;
637 // If system and activity default is on, set it.
638 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
639 $trackingdefault = COMPLETION_TRACKING_MANUAL;
642 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
643 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
644 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
645 $mform->setDefault('completion', $trackingdefault);
646 $mform->addHelpButton('completion', 'completion', 'completion');
648 // Automatic completion once you view it
649 $gotcompletionoptions = false;
650 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
651 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
652 get_string('completionview_desc', 'completion'));
653 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
654 $gotcompletionoptions = true;
657 // Automatic completion once it's graded
658 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
659 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
660 get_string('completionusegrade_desc', 'completion'));
661 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
662 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
663 $gotcompletionoptions = true;
665 // If using the rating system, there is no grade unless ratings are enabled.
666 if ($this->_features->rating) {
667 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
671 // Automatic completion according to module-specific rules
672 $this->_customcompletionelements = $this->add_completion_rules();
673 foreach ($this->_customcompletionelements as $element) {
674 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
677 $gotcompletionoptions = $gotcompletionoptions ||
678 count($this->_customcompletionelements)>0;
680 // Automatic option only appears if possible
681 if ($gotcompletionoptions) {
682 $mform->getElement('completion')->addOption(
683 get_string('completion_automatic', 'completion'),
684 COMPLETION_TRACKING_AUTOMATIC);
687 // Completion expected at particular date? (For progress tracking)
688 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
689 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
690 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
693 // Populate module tags.
694 if (core_tag_tag::is_enabled('core', 'course_modules')) {
695 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
696 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
697 if ($this->_cm) {
698 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
699 $mform->setDefault('tags', $tags);
703 $this->standard_hidden_coursemodule_elements();
705 $this->plugin_extend_coursemodule_standard_elements();
709 * Plugins can extend the coursemodule settings form.
711 protected function plugin_extend_coursemodule_standard_elements() {
712 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
713 foreach ($callbacks as $type => $plugins) {
714 foreach ($plugins as $plugin => $pluginfunction) {
715 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
716 // directly.
717 $pluginfunction($this, $this->_form);
723 * Can be overridden to add custom completion rules if the module wishes
724 * them. If overriding this, you should also override completion_rule_enabled.
725 * <p>
726 * Just add elements to the form as needed and return the list of IDs. The
727 * system will call disabledIf and handle other behaviour for each returned
728 * ID.
729 * @return array Array of string IDs of added items, empty array if none
731 function add_completion_rules() {
732 return array();
736 * Called during validation. Override to indicate, based on the data, whether
737 * a custom completion rule is enabled (selected).
739 * @param array $data Input data (not yet validated)
740 * @return bool True if one or more rules is enabled, false if none are;
741 * default returns false
743 function completion_rule_enabled($data) {
744 return false;
747 function standard_hidden_coursemodule_elements(){
748 $mform =& $this->_form;
749 $mform->addElement('hidden', 'course', 0);
750 $mform->setType('course', PARAM_INT);
752 $mform->addElement('hidden', 'coursemodule', 0);
753 $mform->setType('coursemodule', PARAM_INT);
755 $mform->addElement('hidden', 'section', 0);
756 $mform->setType('section', PARAM_INT);
758 $mform->addElement('hidden', 'module', 0);
759 $mform->setType('module', PARAM_INT);
761 $mform->addElement('hidden', 'modulename', '');
762 $mform->setType('modulename', PARAM_PLUGIN);
764 $mform->addElement('hidden', 'instance', 0);
765 $mform->setType('instance', PARAM_INT);
767 $mform->addElement('hidden', 'add', 0);
768 $mform->setType('add', PARAM_ALPHA);
770 $mform->addElement('hidden', 'update', 0);
771 $mform->setType('update', PARAM_INT);
773 $mform->addElement('hidden', 'return', 0);
774 $mform->setType('return', PARAM_BOOL);
776 $mform->addElement('hidden', 'sr', 0);
777 $mform->setType('sr', PARAM_INT);
780 public function standard_grading_coursemodule_elements() {
781 global $COURSE, $CFG;
782 $mform =& $this->_form;
783 $isupdate = !empty($this->_cm);
784 $gradeoptions = array('isupdate' => $isupdate,
785 'currentgrade' => false,
786 'hasgrades' => false,
787 'canrescale' => $this->_features->canrescale,
788 'useratings' => $this->_features->rating);
790 if ($this->_features->hasgrades) {
792 if (!$this->_features->rating || $this->_features->gradecat) {
793 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
796 //if supports grades and grades arent being handled via ratings
797 if (!$this->_features->rating) {
799 if ($isupdate) {
800 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
801 'itemmodule' => $this->_cm->modname,
802 'iteminstance' => $this->_cm->instance,
803 'itemnumber' => 0,
804 'courseid' => $COURSE->id));
805 if ($gradeitem) {
806 $gradeoptions['currentgrade'] = $gradeitem->grademax;
807 $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
808 $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
809 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
812 $mform->addElement('modgrade', 'grade', get_string('grade'), $gradeoptions);
813 $mform->addHelpButton('grade', 'modgrade', 'grades');
814 $mform->setDefault('grade', $CFG->gradepointdefault);
817 if ($this->_features->advancedgrading
818 and !empty($this->current->_advancedgradingdata['methods'])
819 and !empty($this->current->_advancedgradingdata['areas'])) {
821 if (count($this->current->_advancedgradingdata['areas']) == 1) {
822 // if there is just one gradable area (most cases), display just the selector
823 // without its name to make UI simplier
824 $areadata = reset($this->current->_advancedgradingdata['areas']);
825 $areaname = key($this->current->_advancedgradingdata['areas']);
826 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
827 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
828 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
829 if (!$this->_features->rating) {
830 $mform->disabledIf('advancedgradingmethod_'.$areaname, 'grade[modgrade_type]', 'eq', 'none');
833 } else {
834 // the module defines multiple gradable areas, display a selector
835 // for each of them together with a name of the area
836 $areasgroup = array();
837 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
838 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
839 $areadata['title'], $this->current->_advancedgradingdata['methods']);
840 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
842 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
843 array(' ', '<br />'), false);
847 if ($this->_features->gradecat) {
848 $mform->addElement('select', 'gradecat',
849 get_string('gradecategoryonmodform', 'grades'),
850 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
851 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
852 if (!$this->_features->rating) {
853 $mform->disabledIf('gradecat', 'grade[modgrade_type]', 'eq', 'none');
857 // Grade to pass.
858 $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
859 $mform->addHelpButton('gradepass', 'gradepass', 'grades');
860 $mform->setDefault('gradepass', '');
861 $mform->setType('gradepass', PARAM_RAW);
862 if (!$this->_features->rating) {
863 $mform->disabledIf('gradepass', 'grade[modgrade_type]', 'eq', 'none');
864 } else {
865 $mform->disabledIf('gradepass', 'assessed', 'eq', '0');
871 * Add an editor for an activity's introduction field.
872 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
873 * @param null $required Override system default for requiremodintro
874 * @param null $customlabel Override default label for editor
875 * @throws coding_exception
877 protected function add_intro_editor($required=null, $customlabel=null) {
878 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
879 debugging($str, DEBUG_DEVELOPER);
881 $this->standard_intro_elements($customlabel);
886 * Add an editor for an activity's introduction field.
888 * @param null $customlabel Override default label for editor
889 * @throws coding_exception
891 protected function standard_intro_elements($customlabel=null) {
892 global $CFG;
894 $required = $CFG->requiremodintro;
896 $mform = $this->_form;
897 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
899 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
900 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
901 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
902 if ($required) {
903 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
906 // If the 'show description' feature is enabled, this checkbox appears below the intro.
907 // We want to hide that when using the singleactivity course format because it is confusing.
908 if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
909 $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
910 $mform->addHelpButton('showdescription', 'showdescription');
915 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
917 * @param bool $cancel show cancel button
918 * @param string $submitlabel null means default, false means none, string is label text
919 * @param string $submit2label null means default, false means none, string is label text
920 * @return void
922 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
923 if (is_null($submitlabel)) {
924 $submitlabel = get_string('savechangesanddisplay');
927 if (is_null($submit2label)) {
928 $submit2label = get_string('savechangesandreturntocourse');
931 $mform = $this->_form;
933 // elements in a row need a group
934 $buttonarray = array();
936 // Label for the submit button to return to the course.
937 // Ignore this button in single activity format because it is confusing.
938 if ($submit2label !== false && $this->courseformat->has_view_page()) {
939 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
942 if ($submitlabel !== false) {
943 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
946 if ($cancel) {
947 $buttonarray[] = &$mform->createElement('cancel');
950 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
951 $mform->setType('buttonar', PARAM_RAW);
952 $mform->closeHeaderBefore('buttonar');
956 * Get the list of admin settings for this module and apply any locked settings.
957 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
958 * in that function because set_data has not been called yet.
960 * @return void
962 protected function apply_admin_locked_flags() {
963 global $OUTPUT;
965 if (!$this->applyadminlockedflags) {
966 return;
969 $settings = get_config($this->_modname);
970 $mform = $this->_form;
971 $lockedicon = html_writer::tag('span',
972 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
973 array('class' => 'action-icon'));
974 $isupdate = !empty($this->_cm);
976 foreach ($settings as $name => $value) {
977 if (strpos('_', $name) !== false) {
978 continue;
980 if ($mform->elementExists($name)) {
981 $element = $mform->getElement($name);
982 $lockedsetting = $name . '_locked';
983 if (!empty($settings->$lockedsetting)) {
984 // Always lock locked settings for new modules,
985 // for updates, only lock them if the current value is the same as the default (or there is no current value).
986 $value = $settings->$name;
987 if ($isupdate && isset($this->current->$name)) {
988 $value = $this->current->$name;
990 if ($value == $settings->$name) {
991 $mform->setConstant($name, $settings->$name);
992 $element->setLabel($element->getLabel() . $lockedicon);
993 // Do not use hardfreeze because we need the hidden input to check dependencies.
994 $element->freeze();
1002 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
1004 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1005 * default date/time value should be relative to. If not passed, all
1006 * date/time fields are set relative to the users current midnight.
1007 * @return void
1009 public function apply_admin_defaults($datetimeoffsets = array()) {
1010 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1011 $this->applyadminlockedflags = true;
1013 $settings = get_config($this->_modname);
1014 $mform = $this->_form;
1015 $usermidnight = usergetmidnight(time());
1016 $isupdate = !empty($this->_cm);
1018 foreach ($settings as $name => $value) {
1019 if (strpos('_', $name) !== false) {
1020 continue;
1022 if ($mform->elementExists($name)) {
1023 $element = $mform->getElement($name);
1024 if (!$isupdate) {
1025 if ($element->getType() == 'date_time_selector') {
1026 $enabledsetting = $name . '_enabled';
1027 if (empty($settings->$enabledsetting)) {
1028 $mform->setDefault($name, 0);
1029 } else {
1030 $relativetime = $usermidnight;
1031 if (isset($datetimeoffsets[$name])) {
1032 $relativetime = $datetimeoffsets[$name];
1034 $mform->setDefault($name, $relativetime + $settings->$name);
1036 } else {
1037 $mform->setDefault($name, $settings->$name);
1040 $advancedsetting = $name . '_adv';
1041 if (!empty($settings->$advancedsetting)) {
1042 $mform->setAdvanced($name);