Merge branch 'install_25_STABLE' of https://git.in.moodle.com/amosbot/moodle-install...
[moodle.git] / course / moodleform_mod.php
blobbdf765777c0dcd8a0ac166f34bec0dcb63839a38
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 function moodleform_mod($current, $section, $cm, $course) {
53 $this->current = $current;
54 $this->_instance = $current->instance;
55 $this->_section = $section;
56 $this->_cm = $cm;
57 if ($this->_cm) {
58 $this->context = context_module::instance($this->_cm->id);
59 } else {
60 $this->context = context_course::instance($course->id);
63 // Guess module name
64 $matches = array();
65 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
66 debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
67 print_error('unknownmodulename');
69 $this->_modname = $matches[1];
70 $this->init_features();
71 parent::moodleform('modedit.php');
74 protected function init_features() {
75 global $CFG;
77 $this->_features = new stdClass();
78 $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
79 $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
80 $this->_features->groupmembersonly = (!empty($CFG->enablegroupmembersonly) and plugin_supports('mod', $this->_modname, FEATURE_GROUPMEMBERSONLY, false));
81 $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
82 $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
83 $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
84 $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
85 $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
86 $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
87 $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
89 $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
90 $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
93 /**
94 * Only available on moodleform_mod.
96 * @param array $default_values passed by reference
98 function data_preprocessing(&$default_values){
99 if (empty($default_values['scale'])) {
100 $default_values['assessed'] = 0;
103 if (empty($default_values['assessed'])){
104 $default_values['ratingtime'] = 0;
105 } else {
106 $default_values['ratingtime']=
107 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
112 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
114 function definition_after_data() {
115 global $CFG, $COURSE;
116 $mform =& $this->_form;
118 if ($id = $mform->getElementValue('update')) {
119 $modulename = $mform->getElementValue('modulename');
120 $instance = $mform->getElementValue('instance');
122 if ($this->_features->gradecat) {
123 $gradecat = false;
124 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
125 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
126 if (!empty($outcomes)) {
127 $gradecat = true;
131 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
132 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
133 if (!empty($items)) {
134 foreach ($items as $item) {
135 if (!empty($item->outcomeid)) {
136 $elname = 'outcome_'.$item->outcomeid;
137 if ($mform->elementExists($elname)) {
138 $mform->hardFreeze($elname); // prevent removing of existing outcomes
143 foreach ($items as $item) {
144 if (is_bool($gradecat)) {
145 $gradecat = $item->categoryid;
146 continue;
148 if ($gradecat != $item->categoryid) {
149 //mixed categories
150 $gradecat = false;
151 break;
156 if ($gradecat === false) {
157 // items and outcomes in different categories - remove the option
158 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
159 if ($mform->elementExists('gradecat')) {
160 $mform->removeElement('gradecat');
161 if ($this->_features->rating) {
162 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
163 $mform->removeElement('modstandardgrade');
170 if ($COURSE->groupmodeforce) {
171 if ($mform->elementExists('groupmode')) {
172 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
176 // Don't disable/remove groupingid if it is currently set to something,
177 // otherwise you cannot turn it off at same time as turning off other
178 // option (MDL-30764)
179 if (empty($this->_cm) || !$this->_cm->groupingid) {
180 if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
181 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
183 } else if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
184 $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
186 } else if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
187 // groupings have no use without groupmode or groupmembersonly
188 if ($mform->elementExists('groupingid')) {
189 $mform->removeElement('groupingid');
194 // Completion: If necessary, freeze fields
195 $completion = new completion_info($COURSE);
196 if ($completion->is_enabled()) {
197 // If anybody has completed the activity, these options will be 'locked'
198 $completedcount = empty($this->_cm)
200 : $completion->count_user_data($this->_cm);
202 $freeze = false;
203 if (!$completedcount) {
204 if ($mform->elementExists('unlockcompletion')) {
205 $mform->removeElement('unlockcompletion');
207 // Automatically set to unlocked (note: this is necessary
208 // in order to make it recalculate completion once the option
209 // is changed, maybe someone has completed it now)
210 $mform->getElement('completionunlocked')->setValue(1);
211 } else {
212 // Has the element been unlocked, either by the button being pressed
213 // in this request, or the field already being set from a previous one?
214 if ($mform->exportValue('unlockcompletion') ||
215 $mform->exportValue('completionunlocked')) {
216 // Yes, add in warning text and set the hidden variable
217 $mform->insertElementBefore(
218 $mform->createElement('static', 'completedunlocked',
219 get_string('completedunlocked', 'completion'),
220 get_string('completedunlockedtext', 'completion')),
221 'unlockcompletion');
222 $mform->removeElement('unlockcompletion');
223 $mform->getElement('completionunlocked')->setValue(1);
224 } else {
225 // No, add in the warning text with the count (now we know
226 // it) before the unlock button
227 $mform->insertElementBefore(
228 $mform->createElement('static', 'completedwarning',
229 get_string('completedwarning', 'completion'),
230 get_string('completedwarningtext', 'completion', $completedcount)),
231 'unlockcompletion');
232 $freeze = true;
236 if ($freeze) {
237 $mform->freeze('completion');
238 if ($mform->elementExists('completionview')) {
239 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
241 if ($mform->elementExists('completionusegrade')) {
242 $mform->freeze('completionusegrade');
244 $mform->freeze($this->_customcompletionelements);
248 // Availability conditions
249 if (!empty($CFG->enableavailability) && $this->_cm) {
250 $ci = new condition_info($this->_cm);
251 $fullcm=$ci->get_full_course_module();
253 $num=0;
254 foreach($fullcm->conditionsgrade as $gradeitemid=>$minmax) {
255 $groupelements=$mform->getElement('conditiongradegroup['.$num.']')->getElements();
256 $groupelements[0]->setValue($gradeitemid);
257 $groupelements[2]->setValue(is_null($minmax->min) ? '' :
258 format_float($minmax->min, 5, true, true));
259 $groupelements[4]->setValue(is_null($minmax->max) ? '' :
260 format_float($minmax->max, 5, true, true));
261 $num++;
264 $num = 0;
265 foreach($fullcm->conditionsfield as $field => $details) {
266 $groupelements = $mform->getElement('conditionfieldgroup['.$num.']')->getElements();
267 $groupelements[0]->setValue($field);
268 $groupelements[1]->setValue(is_null($details->operator) ? '' : $details->operator);
269 $groupelements[2]->setValue(is_null($details->value) ? '' : $details->value);
270 $num++;
273 if ($completion->is_enabled()) {
274 $num=0;
275 foreach($fullcm->conditionscompletion as $othercmid=>$state) {
276 $groupelements=$mform->getElement('conditioncompletiongroup['.$num.']')->getElements();
277 $groupelements[0]->setValue($othercmid);
278 $groupelements[1]->setValue($state);
279 $num++;
285 // form verification
286 function validation($data, $files) {
287 global $COURSE, $DB;
288 $errors = parent::validation($data, $files);
290 $mform =& $this->_form;
292 $errors = array();
294 if ($mform->elementExists('name')) {
295 $name = trim($data['name']);
296 if ($name == '') {
297 $errors['name'] = get_string('required');
301 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
302 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
303 if ($data['coursemodule']) {
304 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
305 } else {
306 $cm = null;
309 if ($mform->elementExists('cmidnumber')) {
310 // verify the idnumber
311 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
312 $errors['cmidnumber'] = get_string('idnumbertaken');
316 // Completion: Don't let them choose automatic completion without turning
317 // on some conditions. Ignore this check when completion settings are
318 // locked, as the options are then disabled.
319 if (array_key_exists('completion', $data) &&
320 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
321 !empty($data['completionunlocked'])) {
322 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
323 !$this->completion_rule_enabled($data)) {
324 $errors['completion'] = get_string('badautocompletion', 'completion');
328 // Conditions: Don't let them set dates which make no sense
329 if (array_key_exists('availablefrom', $data) &&
330 $data['availablefrom'] && $data['availableuntil'] &&
331 $data['availablefrom'] >= $data['availableuntil']) {
332 $errors['availablefrom'] = get_string('badavailabledates', 'condition');
335 // Conditions: Verify that the grade conditions are numbers, and make sense.
336 if (array_key_exists('conditiongradegroup', $data)) {
337 foreach ($data['conditiongradegroup'] as $i => $gradedata) {
338 if ($gradedata['conditiongrademin'] !== '' &&
339 !is_numeric(unformat_float($gradedata['conditiongrademin']))) {
340 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
341 continue;
343 if ($gradedata['conditiongrademax'] !== '' &&
344 !is_numeric(unformat_float($gradedata['conditiongrademax']))) {
345 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
346 continue;
348 if ($gradedata['conditiongrademin'] !== '' && $gradedata['conditiongrademax'] !== '' &&
349 unformat_float($gradedata['conditiongrademax']) <= unformat_float($gradedata['conditiongrademin'])) {
350 $errors["conditiongradegroup[{$i}]"] = get_string('badgradelimits', 'condition');
351 continue;
353 if ($gradedata['conditiongrademin'] === '' && $gradedata['conditiongrademax'] === '' &&
354 $gradedata['conditiongradeitemid']) {
355 $errors["conditiongradegroup[{$i}]"] = get_string('gradeitembutnolimits', 'condition');
356 continue;
358 if (($gradedata['conditiongrademin'] !== '' || $gradedata['conditiongrademax'] !== '') &&
359 !$gradedata['conditiongradeitemid']) {
360 $errors["conditiongradegroup[{$i}]"] = get_string('gradelimitsbutnoitem', 'condition');
361 continue;
366 // Conditions: Verify that the user profile field has not been declared more than once
367 if (array_key_exists('conditionfieldgroup', $data)) {
368 // Array to store the existing fields
369 $arrcurrentfields = array();
370 // Error message displayed if any condition is declared more than once. We use lang string because
371 // this way we don't actually generate the string unless there is an error.
372 $stralreadydeclaredwarning = new lang_string('fielddeclaredmultipletimes', 'condition');
373 foreach ($data['conditionfieldgroup'] as $i => $fielddata) {
374 if ($fielddata['conditionfield'] == 0) { // Don't need to bother if none is selected
375 continue;
377 if (in_array($fielddata['conditionfield'], $arrcurrentfields)) {
378 $errors["conditionfieldgroup[{$i}]"] = $stralreadydeclaredwarning->out();
380 // Add the field to the array
381 $arrcurrentfields[] = $fielddata['conditionfield'];
385 return $errors;
389 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
390 * form definition (new entry form); this function is used to load in data where values
391 * already exist and data is being edited (edit entry form).
393 * @param mixed $default_values object or array of default values
395 function set_data($default_values) {
396 if (is_object($default_values)) {
397 $default_values = (array)$default_values;
400 $this->data_preprocessing($default_values);
401 parent::set_data($default_values);
405 * Adds all the standard elements to a form to edit the settings for an activity module.
407 function standard_coursemodule_elements(){
408 global $COURSE, $CFG, $DB;
409 $mform =& $this->_form;
411 $this->_outcomesused = false;
412 if ($this->_features->outcomes) {
413 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
414 $this->_outcomesused = true;
415 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
416 foreach($outcomes as $outcome) {
417 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
423 if ($this->_features->rating) {
424 require_once($CFG->dirroot.'/rating/lib.php');
425 $rm = new rating_manager();
427 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
429 $permission=CAP_ALLOW;
430 $rolenamestring = null;
431 if (!empty($this->_cm)) {
432 $context = context_module::instance($this->_cm->id);
434 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
435 $rolenamestring = implode(', ', $rolenames);
436 } else {
437 $rolenamestring = get_string('capabilitychecknotavailable','rating');
439 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
440 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
442 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
443 $mform->setDefault('assessed', 0);
444 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
446 $mform->addElement('modgrade', 'scale', get_string('scale'), false);
447 $mform->disabledIf('scale', 'assessed', 'eq', 0);
449 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
450 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
452 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
453 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
454 $mform->disabledIf('assesstimestart', 'ratingtime');
456 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
457 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
458 $mform->disabledIf('assesstimefinish', 'ratingtime');
461 //doing this here means splitting up the grade related settings on the lesson settings page
462 //$this->standard_grading_coursemodule_elements();
464 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
466 $mform->addElement('modvisible', 'visible', get_string('visible'));
467 if (!empty($this->_cm)) {
468 $context = context_module::instance($this->_cm->id);
469 if (!has_capability('moodle/course:activityvisibility', $context)) {
470 $mform->hardFreeze('visible');
474 if ($this->_features->idnumber) {
475 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
476 $mform->setType('cmidnumber', PARAM_RAW);
477 $mform->addHelpButton('cmidnumber', 'idnumbermod');
480 if ($this->_features->groups) {
481 $options = array(NOGROUPS => get_string('groupsnone'),
482 SEPARATEGROUPS => get_string('groupsseparate'),
483 VISIBLEGROUPS => get_string('groupsvisible'));
484 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
485 $mform->addHelpButton('groupmode', 'groupmode', 'group');
488 if ($this->_features->groupings or $this->_features->groupmembersonly) {
489 //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
490 $options = array();
491 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
492 foreach ($groupings as $grouping) {
493 $options[$grouping->id] = format_string($grouping->name);
496 collatorlib::asort($options);
497 $options = array(0 => get_string('none')) + $options;
498 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
499 $mform->addHelpButton('groupingid', 'grouping', 'group');
502 if ($this->_features->groupmembersonly) {
503 $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
504 $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
507 if (!empty($CFG->enableavailability)) {
508 // String used by conditions
509 $strnone = get_string('none','condition');
510 // Conditional availability
512 // Available from/to defaults to midnight because then the display
513 // will be nicer where it tells users when they can access it (it
514 // shows only the date and not time).
515 $date = usergetdate(time());
516 $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
518 // From/until controls
519 $mform->addElement('header', 'availabilityconditionsheader',
520 get_string('availabilityconditions', 'condition'));
521 $mform->addElement('date_time_selector', 'availablefrom',
522 get_string('availablefrom', 'condition'),
523 array('optional' => true, 'defaulttime' => $midnight));
524 $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
525 $mform->addElement('date_time_selector', 'availableuntil',
526 get_string('availableuntil', 'condition'),
527 array('optional' => true, 'defaulttime' => $midnight));
529 // Conditions based on grades
530 $gradeoptions = array();
531 $items = grade_item::fetch_all(array('courseid'=>$COURSE->id));
532 $items = $items ? $items : array();
533 foreach($items as $id=>$item) {
534 // Do not include grades for current item
535 if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance
536 && $this->_cm->modname == $item->itemmodule
537 && $item->itemtype == 'mod') {
538 continue;
540 $gradeoptions[$id] = $item->get_name();
542 asort($gradeoptions);
543 $gradeoptions = array(0 => $strnone) + $gradeoptions;
545 $grouparray = array();
546 $grouparray[] =& $mform->createElement('select','conditiongradeitemid','',$gradeoptions);
547 $grouparray[] =& $mform->createElement('static', '', '',' '.get_string('grade_atleast','condition').' ');
548 $grouparray[] =& $mform->createElement('text', 'conditiongrademin','',array('size'=>3));
549 $grouparray[] =& $mform->createElement('static', '', '','% '.get_string('grade_upto','condition').' ');
550 $grouparray[] =& $mform->createElement('text', 'conditiongrademax','',array('size'=>3));
551 $grouparray[] =& $mform->createElement('static', '', '','%');
552 $group = $mform->createElement('group','conditiongradegroup',
553 get_string('gradecondition', 'condition'),$grouparray);
555 // Get version with condition info and store it so we don't ask
556 // twice
557 if(!empty($this->_cm)) {
558 $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
559 $this->_cm = $ci->get_full_course_module();
560 $count = count($this->_cm->conditionsgrade)+1;
561 $fieldcount = count($this->_cm->conditionsfield) + 1;
562 } else {
563 $count = 1;
564 $fieldcount = 1;
567 $this->repeat_elements(array($group), $count, array(
568 'conditiongradegroup[conditiongrademin]' => array('type' => PARAM_RAW),
569 'conditiongradegroup[conditiongrademax]' => array('type' => PARAM_RAW)
570 ), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true);
571 $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
573 // Conditions based on user fields
574 $operators = condition_info::get_condition_user_field_operators();
575 $useroptions = condition_info::get_condition_user_fields(
576 array('context' => $this->context));
577 asort($useroptions);
579 $useroptions = array(0 => $strnone) + $useroptions;
580 $grouparray = array();
581 $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions);
582 $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators);
583 $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue');
584 $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray);
586 $this->repeat_elements(array($group), $fieldcount, array(
587 'conditionfieldgroup[conditionfieldvalue]' => array('type' => PARAM_RAW)),
588 'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true);
589 $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition');
591 // Conditions based on completion
592 $completion = new completion_info($COURSE);
593 if ($completion->is_enabled()) {
594 $completionoptions = array();
595 $modinfo = get_fast_modinfo($COURSE);
596 foreach($modinfo->cms as $id=>$cm) {
597 // Add each course-module if it:
598 // (a) has completion turned on
599 // (b) is not the same as current course-module
600 if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
601 $completionoptions[$id]=$cm->name;
604 asort($completionoptions);
605 $completionoptions = array(0 => $strnone) + $completionoptions;
607 $completionvalues=array(
608 COMPLETION_COMPLETE=>get_string('completion_complete','condition'),
609 COMPLETION_INCOMPLETE=>get_string('completion_incomplete','condition'),
610 COMPLETION_COMPLETE_PASS=>get_string('completion_pass','condition'),
611 COMPLETION_COMPLETE_FAIL=>get_string('completion_fail','condition'));
613 $grouparray = array();
614 $grouparray[] =& $mform->createElement('select','conditionsourcecmid','',$completionoptions);
615 $grouparray[] =& $mform->createElement('select','conditionrequiredcompletion','',$completionvalues);
616 $group = $mform->createElement('group','conditioncompletiongroup',
617 get_string('completioncondition', 'condition'),$grouparray);
619 $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion)+1;
620 $this->repeat_elements(array($group),$count,array(),
621 'conditioncompletionrepeats','conditioncompletionadds',2,
622 get_string('addcompletions','condition'),true);
623 $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
626 // Do we display availability info to students?
627 $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'),
628 array(CONDITION_STUDENTVIEW_SHOW=>get_string('showavailability_show', 'condition'),
629 CONDITION_STUDENTVIEW_HIDE=>get_string('showavailability_hide', 'condition')));
630 $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
633 // Conditional activities: completion tracking section
634 if(!isset($completion)) {
635 $completion = new completion_info($COURSE);
637 if ($completion->is_enabled()) {
638 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
640 // Unlock button for if people have completed it (will
641 // be removed in definition_after_data if they haven't)
642 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
643 $mform->registerNoSubmitButton('unlockcompletion');
644 $mform->addElement('hidden', 'completionunlocked', 0);
645 $mform->setType('completionunlocked', PARAM_INT);
647 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
648 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
649 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
650 $mform->setDefault('completion', $this->_features->defaultcompletion
651 ? COMPLETION_TRACKING_MANUAL
652 : COMPLETION_TRACKING_NONE);
653 $mform->addHelpButton('completion', 'completion', 'completion');
655 // Automatic completion once you view it
656 $gotcompletionoptions = false;
657 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
658 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
659 get_string('completionview_desc', 'completion'));
660 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
661 $gotcompletionoptions = true;
664 // Automatic completion once it's graded
665 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
666 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
667 get_string('completionusegrade_desc', 'completion'));
668 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
669 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
670 $gotcompletionoptions = true;
672 // If using the rating system, there is no grade unless ratings are enabled.
673 if ($this->_features->rating) {
674 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
678 // Automatic completion according to module-specific rules
679 $this->_customcompletionelements = $this->add_completion_rules();
680 foreach ($this->_customcompletionelements as $element) {
681 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
684 $gotcompletionoptions = $gotcompletionoptions ||
685 count($this->_customcompletionelements)>0;
687 // Automatic option only appears if possible
688 if ($gotcompletionoptions) {
689 $mform->getElement('completion')->addOption(
690 get_string('completion_automatic', 'completion'),
691 COMPLETION_TRACKING_AUTOMATIC);
694 // Completion expected at particular date? (For progress tracking)
695 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
696 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
697 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
700 $this->standard_hidden_coursemodule_elements();
704 * Can be overridden to add custom completion rules if the module wishes
705 * them. If overriding this, you should also override completion_rule_enabled.
706 * <p>
707 * Just add elements to the form as needed and return the list of IDs. The
708 * system will call disabledIf and handle other behaviour for each returned
709 * ID.
710 * @return array Array of string IDs of added items, empty array if none
712 function add_completion_rules() {
713 return array();
717 * Called during validation. Override to indicate, based on the data, whether
718 * a custom completion rule is enabled (selected).
720 * @param array $data Input data (not yet validated)
721 * @return bool True if one or more rules is enabled, false if none are;
722 * default returns false
724 function completion_rule_enabled($data) {
725 return false;
728 function standard_hidden_coursemodule_elements(){
729 $mform =& $this->_form;
730 $mform->addElement('hidden', 'course', 0);
731 $mform->setType('course', PARAM_INT);
733 $mform->addElement('hidden', 'coursemodule', 0);
734 $mform->setType('coursemodule', PARAM_INT);
736 $mform->addElement('hidden', 'section', 0);
737 $mform->setType('section', PARAM_INT);
739 $mform->addElement('hidden', 'module', 0);
740 $mform->setType('module', PARAM_INT);
742 $mform->addElement('hidden', 'modulename', '');
743 $mform->setType('modulename', PARAM_PLUGIN);
745 $mform->addElement('hidden', 'instance', 0);
746 $mform->setType('instance', PARAM_INT);
748 $mform->addElement('hidden', 'add', 0);
749 $mform->setType('add', PARAM_ALPHA);
751 $mform->addElement('hidden', 'update', 0);
752 $mform->setType('update', PARAM_INT);
754 $mform->addElement('hidden', 'return', 0);
755 $mform->setType('return', PARAM_BOOL);
757 $mform->addElement('hidden', 'sr', 0);
758 $mform->setType('sr', PARAM_INT);
761 public function standard_grading_coursemodule_elements() {
762 global $COURSE, $CFG;
763 $mform =& $this->_form;
765 if ($this->_features->hasgrades) {
767 if (!$this->_features->rating || $this->_features->gradecat) {
768 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
771 //if supports grades and grades arent being handled via ratings
772 if (!$this->_features->rating) {
773 $mform->addElement('modgrade', 'grade', get_string('grade'));
774 $mform->setDefault('grade', 100);
777 if ($this->_features->advancedgrading
778 and !empty($this->current->_advancedgradingdata['methods'])
779 and !empty($this->current->_advancedgradingdata['areas'])) {
781 if (count($this->current->_advancedgradingdata['areas']) == 1) {
782 // if there is just one gradable area (most cases), display just the selector
783 // without its name to make UI simplier
784 $areadata = reset($this->current->_advancedgradingdata['areas']);
785 $areaname = key($this->current->_advancedgradingdata['areas']);
786 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
787 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
788 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
790 } else {
791 // the module defines multiple gradable areas, display a selector
792 // for each of them together with a name of the area
793 $areasgroup = array();
794 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
795 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
796 $areadata['title'], $this->current->_advancedgradingdata['methods']);
797 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
799 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
800 array(' ', '<br />'), false);
804 if ($this->_features->gradecat) {
805 $mform->addElement('select', 'gradecat',
806 get_string('gradecategoryonmodform', 'grades'),
807 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
808 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
813 function add_intro_editor($required=false, $customlabel=null) {
814 if (!$this->_features->introeditor) {
815 // intro editor not supported in this module
816 return;
819 $mform = $this->_form;
820 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
822 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
823 'noclean' => true, 'context' => $this->context, 'collapsed' => true));
824 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
825 if ($required) {
826 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
829 // If the 'show description' feature is enabled, this checkbox appears
830 // below the intro.
831 if ($this->_features->showdescription) {
832 $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
833 $mform->addHelpButton('showdescription', 'showdescription');
838 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
840 * @param bool $cancel show cancel button
841 * @param string $submitlabel null means default, false means none, string is label text
842 * @param string $submit2label null means default, false means none, string is label text
843 * @return void
845 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
846 if (is_null($submitlabel)) {
847 $submitlabel = get_string('savechangesanddisplay');
850 if (is_null($submit2label)) {
851 $submit2label = get_string('savechangesandreturntocourse');
854 $mform = $this->_form;
856 // elements in a row need a group
857 $buttonarray = array();
859 if ($submit2label !== false) {
860 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
863 if ($submitlabel !== false) {
864 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
867 if ($cancel) {
868 $buttonarray[] = &$mform->createElement('cancel');
871 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
872 $mform->setType('buttonar', PARAM_RAW);
873 $mform->closeHeaderBefore('buttonar');