MDL-41252 Simple changes to main course page to improve accessibility - original...
[moodle.git] / course / moodleform_mod.php
blob5b489bfe7d43ba8eb137a90ed511e779bbfa3327
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;
34 /**
35 * List of modform features
37 protected $_features;
38 /**
39 * @var array Custom completion-rule elements, if enabled
41 protected $_customcompletionelements;
42 /**
43 * @var string name of module
45 protected $_modname;
46 /** current context, course or module depends if already exists*/
47 protected $context;
49 /** a flag indicating whether outcomes are being used*/
50 protected $_outcomesused;
52 /**
53 * @var bool A flag used to indicate that this module should lock settings
54 * based on admin settings flags in definition_after_data.
56 protected $applyadminlockedflags = false;
58 function moodleform_mod($current, $section, $cm, $course) {
59 $this->current = $current;
60 $this->_instance = $current->instance;
61 $this->_section = $section;
62 $this->_cm = $cm;
63 if ($this->_cm) {
64 $this->context = context_module::instance($this->_cm->id);
65 } else {
66 $this->context = context_course::instance($course->id);
69 // Guess module name
70 $matches = array();
71 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
72 debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
73 print_error('unknownmodulename');
75 $this->_modname = $matches[1];
76 $this->init_features();
77 parent::moodleform('modedit.php');
80 protected function init_features() {
81 global $CFG;
83 $this->_features = new stdClass();
84 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
85 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
86 $this->_features->groupmembersonly = (!empty($CFG->enablegroupmembersonly) and plugin_supports('mod', $this->_modname, FEATURE_GROUPMEMBERSONLY, false));
87 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
88 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
89 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
90 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
91 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
92 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
93 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
95 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
96 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
99 /**
100 * Only available on moodleform_mod.
102 * @param array $default_values passed by reference
104 function data_preprocessing(&$default_values){
105 if (empty($default_values['scale'])) {
106 $default_values['assessed'] = 0;
109 if (empty($default_values['assessed'])){
110 $default_values['ratingtime'] = 0;
111 } else {
112 $default_values['ratingtime']=
113 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
118 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
120 function definition_after_data() {
121 global $CFG, $COURSE;
122 $mform =& $this->_form;
124 if ($id = $mform->getElementValue('update')) {
125 $modulename = $mform->getElementValue('modulename');
126 $instance = $mform->getElementValue('instance');
128 if ($this->_features->gradecat) {
129 $gradecat = false;
130 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
131 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
132 if (!empty($outcomes)) {
133 $gradecat = true;
137 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
138 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
139 if (!empty($items)) {
140 foreach ($items as $item) {
141 if (!empty($item->outcomeid)) {
142 $elname = 'outcome_'.$item->outcomeid;
143 if ($mform->elementExists($elname)) {
144 $mform->hardFreeze($elname); // prevent removing of existing outcomes
149 foreach ($items as $item) {
150 if (is_bool($gradecat)) {
151 $gradecat = $item->categoryid;
152 continue;
154 if ($gradecat != $item->categoryid) {
155 //mixed categories
156 $gradecat = false;
157 break;
162 if ($gradecat === false) {
163 // items and outcomes in different categories - remove the option
164 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
165 if ($mform->elementExists('gradecat')) {
166 $mform->removeElement('gradecat');
167 if ($this->_features->rating) {
168 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
169 $mform->removeElement('modstandardgrade');
176 if ($COURSE->groupmodeforce) {
177 if ($mform->elementExists('groupmode')) {
178 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
182 // Don't disable/remove groupingid if it is currently set to something,
183 // otherwise you cannot turn it off at same time as turning off other
184 // option (MDL-30764)
185 if (empty($this->_cm) || !$this->_cm->groupingid) {
186 if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
187 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
189 } else if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
190 $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
192 } else if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
193 // groupings have no use without groupmode or groupmembersonly
194 if ($mform->elementExists('groupingid')) {
195 $mform->removeElement('groupingid');
200 // Completion: If necessary, freeze fields
201 $completion = new completion_info($COURSE);
202 if ($completion->is_enabled()) {
203 // If anybody has completed the activity, these options will be 'locked'
204 $completedcount = empty($this->_cm)
206 : $completion->count_user_data($this->_cm);
208 $freeze = false;
209 if (!$completedcount) {
210 if ($mform->elementExists('unlockcompletion')) {
211 $mform->removeElement('unlockcompletion');
213 // Automatically set to unlocked (note: this is necessary
214 // in order to make it recalculate completion once the option
215 // is changed, maybe someone has completed it now)
216 $mform->getElement('completionunlocked')->setValue(1);
217 } else {
218 // Has the element been unlocked?
219 if ($mform->exportValue('unlockcompletion')) {
220 // Yes, add in warning text and set the hidden variable
221 $mform->insertElementBefore(
222 $mform->createElement('static', 'completedunlocked',
223 get_string('completedunlocked', 'completion'),
224 get_string('completedunlockedtext', 'completion')),
225 'unlockcompletion');
226 $mform->removeElement('unlockcompletion');
227 $mform->getElement('completionunlocked')->setValue(1);
228 } else {
229 // No, add in the warning text with the count (now we know
230 // it) before the unlock button
231 $mform->insertElementBefore(
232 $mform->createElement('static', 'completedwarning',
233 get_string('completedwarning', 'completion'),
234 get_string('completedwarningtext', 'completion', $completedcount)),
235 'unlockcompletion');
236 $freeze = true;
240 if ($freeze) {
241 $mform->freeze('completion');
242 if ($mform->elementExists('completionview')) {
243 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
245 if ($mform->elementExists('completionusegrade')) {
246 $mform->freeze('completionusegrade');
248 $mform->freeze($this->_customcompletionelements);
252 // Availability conditions
253 if (!empty($CFG->enableavailability) && $this->_cm) {
254 $ci = new condition_info($this->_cm);
255 $fullcm=$ci->get_full_course_module();
257 $num=0;
258 foreach($fullcm->conditionsgrade as $gradeitemid=>$minmax) {
259 $groupelements=$mform->getElement('conditiongradegroup['.$num.']')->getElements();
260 $groupelements[0]->setValue($gradeitemid);
261 $groupelements[2]->setValue(is_null($minmax->min) ? '' :
262 format_float($minmax->min, 5, true, true));
263 $groupelements[4]->setValue(is_null($minmax->max) ? '' :
264 format_float($minmax->max, 5, true, true));
265 $num++;
268 $num = 0;
269 foreach($fullcm->conditionsfield as $field => $details) {
270 $groupelements = $mform->getElement('conditionfieldgroup['.$num.']')->getElements();
271 $groupelements[0]->setValue($field);
272 $groupelements[1]->setValue(is_null($details->operator) ? '' : $details->operator);
273 $groupelements[2]->setValue(is_null($details->value) ? '' : $details->value);
274 $num++;
277 if ($completion->is_enabled()) {
278 $num=0;
279 foreach($fullcm->conditionscompletion as $othercmid=>$state) {
280 $groupelements=$mform->getElement('conditioncompletiongroup['.$num.']')->getElements();
281 $groupelements[0]->setValue($othercmid);
282 $groupelements[1]->setValue($state);
283 $num++;
288 // Freeze admin defaults if required (and not different from default)
289 $this->apply_admin_locked_flags();
292 // form verification
293 function validation($data, $files) {
294 global $COURSE, $DB;
295 $errors = parent::validation($data, $files);
297 $mform =& $this->_form;
299 $errors = array();
301 if ($mform->elementExists('name')) {
302 $name = trim($data['name']);
303 if ($name == '') {
304 $errors['name'] = get_string('required');
308 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
309 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
310 if ($data['coursemodule']) {
311 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
312 } else {
313 $cm = null;
316 if ($mform->elementExists('cmidnumber')) {
317 // verify the idnumber
318 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
319 $errors['cmidnumber'] = get_string('idnumbertaken');
323 // Completion: Don't let them choose automatic completion without turning
324 // on some conditions. Ignore this check when completion settings are
325 // locked, as the options are then disabled.
326 if (array_key_exists('completion', $data) &&
327 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
328 !empty($data['completionunlocked'])) {
329 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
330 !$this->completion_rule_enabled($data)) {
331 $errors['completion'] = get_string('badautocompletion', 'completion');
335 // Conditions: Don't let them set dates which make no sense
336 if (array_key_exists('availablefrom', $data) &&
337 $data['availablefrom'] && $data['availableuntil'] &&
338 $data['availablefrom'] >= $data['availableuntil']) {
339 $errors['availablefrom'] = get_string('badavailabledates', 'condition');
342 // Conditions: Verify that the grade conditions are numbers, and make sense.
343 if (array_key_exists('conditiongradegroup', $data)) {
344 foreach ($data['conditiongradegroup'] as $i => $gradedata) {
345 if ($gradedata['conditiongrademin'] !== '' &&
346 !is_numeric(unformat_float($gradedata['conditiongrademin']))) {
347 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
348 continue;
350 if ($gradedata['conditiongrademax'] !== '' &&
351 !is_numeric(unformat_float($gradedata['conditiongrademax']))) {
352 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
353 continue;
355 if ($gradedata['conditiongrademin'] !== '' && $gradedata['conditiongrademax'] !== '' &&
356 unformat_float($gradedata['conditiongrademax']) <= unformat_float($gradedata['conditiongrademin'])) {
357 $errors["conditiongradegroup[{$i}]"] = get_string('badgradelimits', 'condition');
358 continue;
360 if ($gradedata['conditiongrademin'] === '' && $gradedata['conditiongrademax'] === '' &&
361 $gradedata['conditiongradeitemid']) {
362 $errors["conditiongradegroup[{$i}]"] = get_string('gradeitembutnolimits', 'condition');
363 continue;
365 if (($gradedata['conditiongrademin'] !== '' || $gradedata['conditiongrademax'] !== '') &&
366 !$gradedata['conditiongradeitemid']) {
367 $errors["conditiongradegroup[{$i}]"] = get_string('gradelimitsbutnoitem', 'condition');
368 continue;
373 // Conditions: Verify that the user profile field has not been declared more than once
374 if (array_key_exists('conditionfieldgroup', $data)) {
375 // Array to store the existing fields
376 $arrcurrentfields = array();
377 // Error message displayed if any condition is declared more than once. We use lang string because
378 // this way we don't actually generate the string unless there is an error.
379 $stralreadydeclaredwarning = new lang_string('fielddeclaredmultipletimes', 'condition');
380 foreach ($data['conditionfieldgroup'] as $i => $fielddata) {
381 if ($fielddata['conditionfield'] == 0) { // Don't need to bother if none is selected
382 continue;
384 if (in_array($fielddata['conditionfield'], $arrcurrentfields)) {
385 $errors["conditionfieldgroup[{$i}]"] = $stralreadydeclaredwarning->out();
387 // Add the field to the array
388 $arrcurrentfields[] = $fielddata['conditionfield'];
392 return $errors;
396 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
397 * form definition (new entry form); this function is used to load in data where values
398 * already exist and data is being edited (edit entry form).
400 * @param mixed $default_values object or array of default values
402 function set_data($default_values) {
403 if (is_object($default_values)) {
404 $default_values = (array)$default_values;
407 $this->data_preprocessing($default_values);
408 parent::set_data($default_values);
412 * Adds all the standard elements to a form to edit the settings for an activity module.
414 function standard_coursemodule_elements(){
415 global $COURSE, $CFG, $DB;
416 $mform =& $this->_form;
418 $this->_outcomesused = false;
419 if ($this->_features->outcomes) {
420 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
421 $this->_outcomesused = true;
422 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
423 foreach($outcomes as $outcome) {
424 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
430 if ($this->_features->rating) {
431 require_once($CFG->dirroot.'/rating/lib.php');
432 $rm = new rating_manager();
434 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
436 $permission=CAP_ALLOW;
437 $rolenamestring = null;
438 if (!empty($this->_cm)) {
439 $context = context_module::instance($this->_cm->id);
441 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
442 $rolenamestring = implode(', ', $rolenames);
443 } else {
444 $rolenamestring = get_string('capabilitychecknotavailable','rating');
446 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
447 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
449 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
450 $mform->setDefault('assessed', 0);
451 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
453 $mform->addElement('modgrade', 'scale', get_string('scale'), false);
454 $mform->disabledIf('scale', 'assessed', 'eq', 0);
456 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
457 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
459 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
460 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
461 $mform->disabledIf('assesstimestart', 'ratingtime');
463 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
464 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
465 $mform->disabledIf('assesstimefinish', 'ratingtime');
468 //doing this here means splitting up the grade related settings on the lesson settings page
469 //$this->standard_grading_coursemodule_elements();
471 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
473 $mform->addElement('modvisible', 'visible', get_string('visible'));
474 if (!empty($this->_cm)) {
475 $context = context_module::instance($this->_cm->id);
476 if (!has_capability('moodle/course:activityvisibility', $context)) {
477 $mform->hardFreeze('visible');
481 if ($this->_features->idnumber) {
482 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
483 $mform->setType('cmidnumber', PARAM_RAW);
484 $mform->addHelpButton('cmidnumber', 'idnumbermod');
487 if ($this->_features->groups) {
488 $options = array(NOGROUPS => get_string('groupsnone'),
489 SEPARATEGROUPS => get_string('groupsseparate'),
490 VISIBLEGROUPS => get_string('groupsvisible'));
491 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
492 $mform->addHelpButton('groupmode', 'groupmode', 'group');
495 if ($this->_features->groupings or $this->_features->groupmembersonly) {
496 //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
497 $options = array();
498 $options[0] = get_string('none');
499 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
500 foreach ($groupings as $grouping) {
501 $options[$grouping->id] = format_string($grouping->name);
504 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
505 $mform->addHelpButton('groupingid', 'grouping', 'group');
508 if ($this->_features->groupmembersonly) {
509 $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
510 $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
513 if (!empty($CFG->enableavailability)) {
514 // String used by conditions
515 $strnone = get_string('none','condition');
516 // Conditional availability
518 // Available from/to defaults to midnight because then the display
519 // will be nicer where it tells users when they can access it (it
520 // shows only the date and not time).
521 $date = usergetdate(time());
522 $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
524 // From/until controls
525 $mform->addElement('header', 'availabilityconditionsheader',
526 get_string('availabilityconditions', 'condition'));
527 $mform->addElement('date_time_selector', 'availablefrom',
528 get_string('availablefrom', 'condition'),
529 array('optional' => true, 'defaulttime' => $midnight));
530 $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
531 $mform->addElement('date_time_selector', 'availableuntil',
532 get_string('availableuntil', 'condition'),
533 array('optional' => true, 'defaulttime' => $midnight));
535 // Conditions based on grades
536 $gradeoptions = array();
537 $items = grade_item::fetch_all(array('courseid'=>$COURSE->id));
538 $items = $items ? $items : array();
539 foreach($items as $id=>$item) {
540 // Do not include grades for current item
541 if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance
542 && $this->_cm->modname == $item->itemmodule
543 && $item->itemtype == 'mod') {
544 continue;
546 $gradeoptions[$id] = $item->get_name();
548 asort($gradeoptions);
549 $gradeoptions = array(0 => $strnone) + $gradeoptions;
551 $grouparray = array();
552 $grouparray[] =& $mform->createElement('select','conditiongradeitemid','',$gradeoptions);
553 $grouparray[] =& $mform->createElement('static', '', '',' '.get_string('grade_atleast','condition').' ');
554 $grouparray[] =& $mform->createElement('text', 'conditiongrademin','',array('size'=>3));
555 $grouparray[] =& $mform->createElement('static', '', '','% '.get_string('grade_upto','condition').' ');
556 $grouparray[] =& $mform->createElement('text', 'conditiongrademax','',array('size'=>3));
557 $grouparray[] =& $mform->createElement('static', '', '','%');
558 $group = $mform->createElement('group','conditiongradegroup',
559 get_string('gradecondition', 'condition'),$grouparray);
561 // Get version with condition info and store it so we don't ask
562 // twice
563 if(!empty($this->_cm)) {
564 $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
565 $this->_cm = $ci->get_full_course_module();
566 $count = count($this->_cm->conditionsgrade)+1;
567 $fieldcount = count($this->_cm->conditionsfield) + 1;
568 } else {
569 $count = 1;
570 $fieldcount = 1;
573 $this->repeat_elements(array($group), $count, array(
574 'conditiongradegroup[conditiongrademin]' => array('type' => PARAM_RAW),
575 'conditiongradegroup[conditiongrademax]' => array('type' => PARAM_RAW)
576 ), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true);
577 $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
579 // Conditions based on user fields
580 $operators = condition_info::get_condition_user_field_operators();
581 $useroptions = condition_info::get_condition_user_fields(
582 array('context' => $this->context));
583 asort($useroptions);
585 $useroptions = array(0 => $strnone) + $useroptions;
586 $grouparray = array();
587 $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions);
588 $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators);
589 $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue');
590 $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray);
592 $this->repeat_elements(array($group), $fieldcount, array(
593 'conditionfieldgroup[conditionfieldvalue]' => array('type' => PARAM_RAW)),
594 'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true);
595 $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition');
597 // Conditions based on completion
598 $completion = new completion_info($COURSE);
599 if ($completion->is_enabled()) {
600 $completionoptions = array();
601 $modinfo = get_fast_modinfo($COURSE);
602 foreach($modinfo->cms as $id=>$cm) {
603 // Add each course-module if it:
604 // (a) has completion turned on
605 // (b) is not the same as current course-module
606 if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
607 $completionoptions[$id]=$cm->name;
610 asort($completionoptions);
611 $completionoptions = array(0 => $strnone) + $completionoptions;
613 $completionvalues=array(
614 COMPLETION_COMPLETE=>get_string('completion_complete','condition'),
615 COMPLETION_INCOMPLETE=>get_string('completion_incomplete','condition'),
616 COMPLETION_COMPLETE_PASS=>get_string('completion_pass','condition'),
617 COMPLETION_COMPLETE_FAIL=>get_string('completion_fail','condition'));
619 $grouparray = array();
620 $grouparray[] =& $mform->createElement('select','conditionsourcecmid','',$completionoptions);
621 $grouparray[] =& $mform->createElement('select','conditionrequiredcompletion','',$completionvalues);
622 $group = $mform->createElement('group','conditioncompletiongroup',
623 get_string('completioncondition', 'condition'),$grouparray);
625 $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion)+1;
626 $this->repeat_elements(array($group),$count,array(),
627 'conditioncompletionrepeats','conditioncompletionadds',2,
628 get_string('addcompletions','condition'),true);
629 $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
632 // Do we display availability info to students?
633 $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'),
634 array(CONDITION_STUDENTVIEW_SHOW=>get_string('showavailability_show', 'condition'),
635 CONDITION_STUDENTVIEW_HIDE=>get_string('showavailability_hide', 'condition')));
636 $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
639 // Conditional activities: completion tracking section
640 if(!isset($completion)) {
641 $completion = new completion_info($COURSE);
643 if ($completion->is_enabled()) {
644 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
646 // Unlock button for if people have completed it (will
647 // be removed in definition_after_data if they haven't)
648 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
649 $mform->registerNoSubmitButton('unlockcompletion');
650 $mform->addElement('hidden', 'completionunlocked', 0);
651 $mform->setType('completionunlocked', PARAM_INT);
653 $trackingdefault = COMPLETION_TRACKING_NONE;
654 // If system and activity default is on, set it.
655 if ($CFG->completiondefault && $this->_features->defaultcompletion) {
656 $trackingdefault = COMPLETION_TRACKING_MANUAL;
659 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
660 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
661 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
662 $mform->setDefault('completion', $trackingdefault);
663 $mform->addHelpButton('completion', 'completion', 'completion');
665 // Automatic completion once you view it
666 $gotcompletionoptions = false;
667 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
668 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
669 get_string('completionview_desc', 'completion'));
670 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
671 $gotcompletionoptions = true;
674 // Automatic completion once it's graded
675 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
676 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
677 get_string('completionusegrade_desc', 'completion'));
678 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
679 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
680 $gotcompletionoptions = true;
683 // Automatic completion according to module-specific rules
684 $this->_customcompletionelements = $this->add_completion_rules();
685 foreach ($this->_customcompletionelements as $element) {
686 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
689 $gotcompletionoptions = $gotcompletionoptions ||
690 count($this->_customcompletionelements)>0;
692 // Automatic option only appears if possible
693 if ($gotcompletionoptions) {
694 $mform->getElement('completion')->addOption(
695 get_string('completion_automatic', 'completion'),
696 COMPLETION_TRACKING_AUTOMATIC);
699 // Completion expected at particular date? (For progress tracking)
700 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
701 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
702 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
705 $this->standard_hidden_coursemodule_elements();
709 * Can be overridden to add custom completion rules if the module wishes
710 * them. If overriding this, you should also override completion_rule_enabled.
711 * <p>
712 * Just add elements to the form as needed and return the list of IDs. The
713 * system will call disabledIf and handle other behaviour for each returned
714 * ID.
715 * @return array Array of string IDs of added items, empty array if none
717 function add_completion_rules() {
718 return array();
722 * Called during validation. Override to indicate, based on the data, whether
723 * a custom completion rule is enabled (selected).
725 * @param array $data Input data (not yet validated)
726 * @return bool True if one or more rules is enabled, false if none are;
727 * default returns false
729 function completion_rule_enabled($data) {
730 return false;
733 function standard_hidden_coursemodule_elements(){
734 $mform =& $this->_form;
735 $mform->addElement('hidden', 'course', 0);
736 $mform->setType('course', PARAM_INT);
738 $mform->addElement('hidden', 'coursemodule', 0);
739 $mform->setType('coursemodule', PARAM_INT);
741 $mform->addElement('hidden', 'section', 0);
742 $mform->setType('section', PARAM_INT);
744 $mform->addElement('hidden', 'module', 0);
745 $mform->setType('module', PARAM_INT);
747 $mform->addElement('hidden', 'modulename', '');
748 $mform->setType('modulename', PARAM_PLUGIN);
750 $mform->addElement('hidden', 'instance', 0);
751 $mform->setType('instance', PARAM_INT);
753 $mform->addElement('hidden', 'add', 0);
754 $mform->setType('add', PARAM_ALPHA);
756 $mform->addElement('hidden', 'update', 0);
757 $mform->setType('update', PARAM_INT);
759 $mform->addElement('hidden', 'return', 0);
760 $mform->setType('return', PARAM_BOOL);
762 $mform->addElement('hidden', 'sr', 0);
763 $mform->setType('sr', PARAM_INT);
766 public function standard_grading_coursemodule_elements() {
767 global $COURSE, $CFG;
768 $mform =& $this->_form;
770 if ($this->_features->hasgrades) {
772 if (!$this->_features->rating || $this->_features->gradecat) {
773 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
776 //if supports grades and grades arent being handled via ratings
777 if (!$this->_features->rating) {
778 $mform->addElement('modgrade', 'grade', get_string('grade'));
779 $mform->setDefault('grade', 100);
782 if ($this->_features->advancedgrading
783 and !empty($this->current->_advancedgradingdata['methods'])
784 and !empty($this->current->_advancedgradingdata['areas'])) {
786 if (count($this->current->_advancedgradingdata['areas']) == 1) {
787 // if there is just one gradable area (most cases), display just the selector
788 // without its name to make UI simplier
789 $areadata = reset($this->current->_advancedgradingdata['areas']);
790 $areaname = key($this->current->_advancedgradingdata['areas']);
791 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
792 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
793 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
795 } else {
796 // the module defines multiple gradable areas, display a selector
797 // for each of them together with a name of the area
798 $areasgroup = array();
799 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
800 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
801 $areadata['title'], $this->current->_advancedgradingdata['methods']);
802 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
804 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
805 array(' ', '<br />'), false);
809 if ($this->_features->gradecat) {
810 $mform->addElement('select', 'gradecat',
811 get_string('gradecategoryonmodform', 'grades'),
812 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
813 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
818 function add_intro_editor($required=false, $customlabel=null) {
819 if (!$this->_features->introeditor) {
820 // intro editor not supported in this module
821 return;
824 $mform = $this->_form;
825 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
827 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
828 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
829 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
830 if ($required) {
831 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
834 // If the 'show description' feature is enabled, this checkbox appears
835 // below the intro.
836 if ($this->_features->showdescription) {
837 $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
838 $mform->addHelpButton('showdescription', 'showdescription');
843 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
845 * @param bool $cancel show cancel button
846 * @param string $submitlabel null means default, false means none, string is label text
847 * @param string $submit2label null means default, false means none, string is label text
848 * @return void
850 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
851 if (is_null($submitlabel)) {
852 $submitlabel = get_string('savechangesanddisplay');
855 if (is_null($submit2label)) {
856 $submit2label = get_string('savechangesandreturntocourse');
859 $mform = $this->_form;
861 // elements in a row need a group
862 $buttonarray = array();
864 if ($submit2label !== false) {
865 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
868 if ($submitlabel !== false) {
869 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
872 if ($cancel) {
873 $buttonarray[] = &$mform->createElement('cancel');
876 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
877 $mform->setType('buttonar', PARAM_RAW);
878 $mform->closeHeaderBefore('buttonar');
882 * Get the list of admin settings for this module and apply any locked settings.
883 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
884 * in that function because set_data has not been called yet.
886 * @return void
888 protected function apply_admin_locked_flags() {
889 global $OUTPUT;
891 if (!$this->applyadminlockedflags) {
892 return;
895 $settings = get_config($this->_modname);
896 $mform = $this->_form;
897 $lockedicon = html_writer::tag('span',
898 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
899 array('class' => 'action-icon'));
900 $isupdate = !empty($this->_cm);
902 foreach ($settings as $name => $value) {
903 if (strpos('_', $name) !== false) {
904 continue;
906 if ($mform->elementExists($name)) {
907 $element = $mform->getElement($name);
908 $lockedsetting = $name . '_locked';
909 if (!empty($settings->$lockedsetting)) {
910 // Always lock locked settings for new modules,
911 // for updates, only lock them if the current value is the same as the default (or there is no current value).
912 $value = $settings->$name;
913 if ($isupdate && isset($this->current->$name)) {
914 $value = $this->current->$name;
916 if ($value == $settings->$name) {
917 $mform->setConstant($name, $settings->$name);
918 $element->setLabel($element->getLabel() . $lockedicon);
919 // Do not use hardfreeze because we need the hidden input to check dependencies.
920 $element->freeze();
928 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
930 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
931 * default date/time value should be relative to. If not passed, all
932 * date/time fields are set relative to the users current midnight.
933 * @return void
935 public function apply_admin_defaults($datetimeoffsets = array()) {
936 // This flag triggers the settings to be locked in apply_admin_locked_flags().
937 $this->applyadminlockedflags = true;
939 $settings = get_config($this->_modname);
940 $mform = $this->_form;
941 $usermidnight = usergetmidnight(time());
942 $isupdate = !empty($this->_cm);
944 foreach ($settings as $name => $value) {
945 if (strpos('_', $name) !== false) {
946 continue;
948 if ($mform->elementExists($name)) {
949 $element = $mform->getElement($name);
950 if (!$isupdate) {
951 if ($element->getType() == 'date_time_selector') {
952 $enabledsetting = $name . '_enabled';
953 if (empty($settings->$enabledsetting)) {
954 $mform->setDefault($name, 0);
955 } else {
956 $relativetime = $usermidnight;
957 if (isset($datetimeoffsets[$name])) {
958 $relativetime = $datetimeoffsets[$name];
960 $mform->setDefault($name, $relativetime + $settings->$name);
962 } else {
963 $mform->setDefault($name, $settings->$name);
966 $advancedsetting = $name . '_adv';
967 if (!empty($settings->$advancedsetting)) {
968 $mform->setAdvanced($name);