MDL-32442 questionupgrade: error in SQL from postgres systems
[moodle.git] / course / moodleform_mod.php
blobdd324192967677a8b02550ed4f122c6d72ade95f
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 = get_context_instance(CONTEXT_MODULE, $this->_cm->id);
59 } else {
60 $this->context = get_context_instance(CONTEXT_COURSE, $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?
213 if ($mform->exportValue('unlockcompletion')) {
214 // Yes, add in warning text and set the hidden variable
215 $mform->insertElementBefore(
216 $mform->createElement('static', 'completedunlocked',
217 get_string('completedunlocked', 'completion'),
218 get_string('completedunlockedtext', 'completion')),
219 'unlockcompletion');
220 $mform->removeElement('unlockcompletion');
221 $mform->getElement('completionunlocked')->setValue(1);
222 } else {
223 // No, add in the warning text with the count (now we know
224 // it) before the unlock button
225 $mform->insertElementBefore(
226 $mform->createElement('static', 'completedwarning',
227 get_string('completedwarning', 'completion'),
228 get_string('completedwarningtext', 'completion', $completedcount)),
229 'unlockcompletion');
230 $freeze = true;
234 if ($freeze) {
235 $mform->freeze('completion');
236 if ($mform->elementExists('completionview')) {
237 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
239 if ($mform->elementExists('completionusegrade')) {
240 $mform->freeze('completionusegrade');
242 $mform->freeze($this->_customcompletionelements);
246 // Availability conditions
247 if (!empty($CFG->enableavailability) && $this->_cm) {
248 $ci = new condition_info($this->_cm);
249 $fullcm=$ci->get_full_course_module();
251 $num=0;
252 foreach($fullcm->conditionsgrade as $gradeitemid=>$minmax) {
253 $groupelements=$mform->getElement('conditiongradegroup['.$num.']')->getElements();
254 $groupelements[0]->setValue($gradeitemid);
255 // These numbers are always in the format 0.00000 - the rtrims remove any final zeros and,
256 // if it is a whole number, the decimal place.
257 $groupelements[2]->setValue(is_null($minmax->min)?'':rtrim(rtrim($minmax->min,'0'),'.'));
258 $groupelements[4]->setValue(is_null($minmax->max)?'':rtrim(rtrim($minmax->max,'0'),'.'));
259 $num++;
262 if ($completion->is_enabled()) {
263 $num=0;
264 foreach($fullcm->conditionscompletion as $othercmid=>$state) {
265 $groupelements=$mform->getElement('conditioncompletiongroup['.$num.']')->getElements();
266 $groupelements[0]->setValue($othercmid);
267 $groupelements[1]->setValue($state);
268 $num++;
274 // form verification
275 function validation($data, $files) {
276 global $COURSE, $DB;
277 $errors = parent::validation($data, $files);
279 $mform =& $this->_form;
281 $errors = array();
283 if ($mform->elementExists('name')) {
284 $name = trim($data['name']);
285 if ($name == '') {
286 $errors['name'] = get_string('required');
290 $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
291 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
292 if ($data['coursemodule']) {
293 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
294 } else {
295 $cm = null;
298 if ($mform->elementExists('cmidnumber')) {
299 // verify the idnumber
300 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
301 $errors['cmidnumber'] = get_string('idnumbertaken');
305 // Completion: Don't let them choose automatic completion without turning
306 // on some conditions
307 if (array_key_exists('completion', $data) && $data['completion']==COMPLETION_TRACKING_AUTOMATIC) {
308 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
309 !$this->completion_rule_enabled($data)) {
310 $errors['completion'] = get_string('badautocompletion', 'completion');
314 // Conditions: Don't let them set dates which make no sense
315 if (array_key_exists('availablefrom', $data) &&
316 $data['availablefrom'] && $data['availableuntil'] &&
317 $data['availablefrom'] >= $data['availableuntil']) {
318 $errors['availablefrom'] = get_string('badavailabledates', 'condition');
321 // Conditions: Verify that the grade conditions are numbers, and make sense.
322 if (array_key_exists('conditiongradegroup', $data)) {
323 foreach ($data['conditiongradegroup'] as $i => $gradedata) {
324 if ($gradedata['conditiongrademin'] !== '' && !is_numeric($gradedata['conditiongrademin'])) {
325 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
326 continue;
328 if ($gradedata['conditiongrademax'] !== '' && !is_numeric($gradedata['conditiongrademax'])) {
329 $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
330 continue;
332 if ($gradedata['conditiongrademin'] !== '' && $gradedata['conditiongrademax'] !== '' &&
333 $gradedata['conditiongrademax'] < $gradedata['conditiongrademin']) {
334 $errors["conditiongradegroup[{$i}]"] = get_string('badgradelimits', 'condition');
335 continue;
337 if ($gradedata['conditiongrademin'] === '' && $gradedata['conditiongrademax'] === '' &&
338 $gradedata['conditiongradeitemid']) {
339 $errors["conditiongradegroup[{$i}]"] = get_string('gradeitembutnolimits', 'condition');
340 continue;
342 if (($gradedata['conditiongrademin'] !== '' || $gradedata['conditiongrademax'] !== '') &&
343 !$gradedata['conditiongradeitemid']) {
344 $errors["conditiongradegroup[{$i}]"] = get_string('gradelimitsbutnoitem', 'condition');
345 continue;
350 return $errors;
354 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
355 * form definition (new entry form); this function is used to load in data where values
356 * already exist and data is being edited (edit entry form).
358 * @param mixed $default_values object or array of default values
360 function set_data($default_values) {
361 if (is_object($default_values)) {
362 $default_values = (array)$default_values;
365 $this->data_preprocessing($default_values);
366 parent::set_data($default_values);
370 * Adds all the standard elements to a form to edit the settings for an activity module.
372 function standard_coursemodule_elements(){
373 global $COURSE, $CFG, $DB;
374 $mform =& $this->_form;
376 $this->_outcomesused = false;
377 if ($this->_features->outcomes) {
378 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
379 $this->_outcomesused = true;
380 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
381 foreach($outcomes as $outcome) {
382 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
388 if ($this->_features->rating) {
389 require_once($CFG->dirroot.'/rating/lib.php');
390 $rm = new rating_manager();
392 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
394 $permission=CAP_ALLOW;
395 $rolenamestring = null;
396 if (!empty($this->_cm)) {
397 $context = get_context_instance(CONTEXT_MODULE, $this->_cm->id);
399 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
400 $rolenamestring = implode(', ', $rolenames);
401 } else {
402 $rolenamestring = get_string('capabilitychecknotavailable','rating');
404 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
405 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
407 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
408 $mform->setDefault('assessed', 0);
409 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
411 $mform->addElement('modgrade', 'scale', get_string('scale'), false);
412 $mform->disabledIf('scale', 'assessed', 'eq', 0);
414 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
415 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
417 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
418 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
419 $mform->disabledIf('assesstimestart', 'ratingtime');
421 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
422 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
423 $mform->disabledIf('assesstimefinish', 'ratingtime');
426 //doing this here means splitting up the grade related settings on the lesson settings page
427 //$this->standard_grading_coursemodule_elements();
429 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
430 if ($this->_features->groups) {
431 $options = array(NOGROUPS => get_string('groupsnone'),
432 SEPARATEGROUPS => get_string('groupsseparate'),
433 VISIBLEGROUPS => get_string('groupsvisible'));
434 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
435 $mform->addHelpButton('groupmode', 'groupmode', 'group');
438 if ($this->_features->groupings or $this->_features->groupmembersonly) {
439 //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
440 $options = array();
441 $options[0] = get_string('none');
442 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
443 foreach ($groupings as $grouping) {
444 $options[$grouping->id] = format_string($grouping->name);
447 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
448 $mform->addHelpButton('groupingid', 'grouping', 'group');
449 $mform->setAdvanced('groupingid');
452 if ($this->_features->groupmembersonly) {
453 $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
454 $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
455 $mform->setAdvanced('groupmembersonly');
458 $mform->addElement('modvisible', 'visible', get_string('visible'));
459 if (!empty($this->_cm)) {
460 $context = get_context_instance(CONTEXT_MODULE, $this->_cm->id);
461 if (!has_capability('moodle/course:activityvisibility', $context)) {
462 $mform->hardFreeze('visible');
466 if ($this->_features->idnumber) {
467 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
468 $mform->addHelpButton('cmidnumber', 'idnumbermod');
471 if (!empty($CFG->enableavailability)) {
472 // Conditional availability
474 // Available from/to defaults to midnight because then the display
475 // will be nicer where it tells users when they can access it (it
476 // shows only the date and not time).
477 $date = usergetdate(time());
478 $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
480 // From/until controls
481 $mform->addElement('header', 'availabilityconditionsheader',
482 get_string('availabilityconditions', 'condition'));
483 $mform->addElement('date_time_selector', 'availablefrom',
484 get_string('availablefrom', 'condition'),
485 array('optional' => true, 'defaulttime' => $midnight));
486 $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
487 $mform->addElement('date_time_selector', 'availableuntil',
488 get_string('availableuntil', 'condition'),
489 array('optional' => true, 'defaulttime' => $midnight));
491 // Conditions based on grades
492 $gradeoptions = array();
493 $items = grade_item::fetch_all(array('courseid'=>$COURSE->id));
494 $items = $items ? $items : array();
495 foreach($items as $id=>$item) {
496 // Do not include grades for current item
497 if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance
498 && $this->_cm->modname == $item->itemmodule
499 && $item->itemtype == 'mod') {
500 continue;
502 $gradeoptions[$id] = $item->get_name();
504 asort($gradeoptions);
505 $gradeoptions = array(0=>get_string('none','condition'))+$gradeoptions;
507 $grouparray = array();
508 $grouparray[] =& $mform->createElement('select','conditiongradeitemid','',$gradeoptions);
509 $grouparray[] =& $mform->createElement('static', '', '',' '.get_string('grade_atleast','condition').' ');
510 $grouparray[] =& $mform->createElement('text', 'conditiongrademin','',array('size'=>3));
511 $grouparray[] =& $mform->createElement('static', '', '','% '.get_string('grade_upto','condition').' ');
512 $grouparray[] =& $mform->createElement('text', 'conditiongrademax','',array('size'=>3));
513 $grouparray[] =& $mform->createElement('static', '', '','%');
514 $group = $mform->createElement('group','conditiongradegroup',
515 get_string('gradecondition', 'condition'),$grouparray);
517 // Get version with condition info and store it so we don't ask
518 // twice
519 if(!empty($this->_cm)) {
520 $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
521 $this->_cm = $ci->get_full_course_module();
522 $count = count($this->_cm->conditionsgrade)+1;
523 } else {
524 $count = 1;
527 $this->repeat_elements(array($group), $count, array(), 'conditiongraderepeats', 'conditiongradeadds', 2,
528 get_string('addgrades', 'condition'), true);
529 $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
531 // Conditions based on completion
532 $completion = new completion_info($COURSE);
533 if ($completion->is_enabled()) {
534 $completionoptions = array();
535 $modinfo = get_fast_modinfo($COURSE);
536 foreach($modinfo->cms as $id=>$cm) {
537 // Add each course-module if it:
538 // (a) has completion turned on
539 // (b) is not the same as current course-module
540 if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
541 $completionoptions[$id]=$cm->name;
544 asort($completionoptions);
545 $completionoptions = array(0=>get_string('none','condition'))+$completionoptions;
547 $completionvalues=array(
548 COMPLETION_COMPLETE=>get_string('completion_complete','condition'),
549 COMPLETION_INCOMPLETE=>get_string('completion_incomplete','condition'),
550 COMPLETION_COMPLETE_PASS=>get_string('completion_pass','condition'),
551 COMPLETION_COMPLETE_FAIL=>get_string('completion_fail','condition'));
553 $grouparray = array();
554 $grouparray[] =& $mform->createElement('select','conditionsourcecmid','',$completionoptions);
555 $grouparray[] =& $mform->createElement('select','conditionrequiredcompletion','',$completionvalues);
556 $group = $mform->createElement('group','conditioncompletiongroup',
557 get_string('completioncondition', 'condition'),$grouparray);
559 $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion)+1;
560 $this->repeat_elements(array($group),$count,array(),
561 'conditioncompletionrepeats','conditioncompletionadds',2,
562 get_string('addcompletions','condition'),true);
563 $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
566 // Do we display availability info to students?
567 $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'),
568 array(CONDITION_STUDENTVIEW_SHOW=>get_string('showavailability_show', 'condition'),
569 CONDITION_STUDENTVIEW_HIDE=>get_string('showavailability_hide', 'condition')));
570 $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
573 // Conditional activities: completion tracking section
574 if(!isset($completion)) {
575 $completion = new completion_info($COURSE);
577 if ($completion->is_enabled()) {
578 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
580 // Unlock button for if people have completed it (will
581 // be removed in definition_after_data if they haven't)
582 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
583 $mform->registerNoSubmitButton('unlockcompletion');
584 $mform->addElement('hidden', 'completionunlocked', 0);
585 $mform->setType('completionunlocked', PARAM_INT);
587 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
588 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
589 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
590 $mform->setDefault('completion', $this->_features->defaultcompletion
591 ? COMPLETION_TRACKING_MANUAL
592 : COMPLETION_TRACKING_NONE);
593 $mform->addHelpButton('completion', 'completion', 'completion');
595 // Automatic completion once you view it
596 $gotcompletionoptions = false;
597 if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
598 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
599 get_string('completionview_desc', 'completion'));
600 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
601 $gotcompletionoptions = true;
604 // Automatic completion once it's graded
605 if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
606 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
607 get_string('completionusegrade_desc', 'completion'));
608 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
609 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
610 $gotcompletionoptions = true;
613 // Automatic completion according to module-specific rules
614 $this->_customcompletionelements = $this->add_completion_rules();
615 foreach ($this->_customcompletionelements as $element) {
616 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
619 $gotcompletionoptions = $gotcompletionoptions ||
620 count($this->_customcompletionelements)>0;
622 // Automatic option only appears if possible
623 if ($gotcompletionoptions) {
624 $mform->getElement('completion')->addOption(
625 get_string('completion_automatic', 'completion'),
626 COMPLETION_TRACKING_AUTOMATIC);
629 // Completion expected at particular date? (For progress tracking)
630 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
631 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
632 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
635 $this->standard_hidden_coursemodule_elements();
639 * Can be overridden to add custom completion rules if the module wishes
640 * them. If overriding this, you should also override completion_rule_enabled.
641 * <p>
642 * Just add elements to the form as needed and return the list of IDs. The
643 * system will call disabledIf and handle other behaviour for each returned
644 * ID.
645 * @return array Array of string IDs of added items, empty array if none
647 function add_completion_rules() {
648 return array();
652 * Called during validation. Override to indicate, based on the data, whether
653 * a custom completion rule is enabled (selected).
655 * @param array $data Input data (not yet validated)
656 * @return bool True if one or more rules is enabled, false if none are;
657 * default returns false
659 function completion_rule_enabled($data) {
660 return false;
663 function standard_hidden_coursemodule_elements(){
664 $mform =& $this->_form;
665 $mform->addElement('hidden', 'course', 0);
666 $mform->setType('course', PARAM_INT);
668 $mform->addElement('hidden', 'coursemodule', 0);
669 $mform->setType('coursemodule', PARAM_INT);
671 $mform->addElement('hidden', 'section', 0);
672 $mform->setType('section', PARAM_INT);
674 $mform->addElement('hidden', 'module', 0);
675 $mform->setType('module', PARAM_INT);
677 $mform->addElement('hidden', 'modulename', '');
678 $mform->setType('modulename', PARAM_PLUGIN);
680 $mform->addElement('hidden', 'instance', 0);
681 $mform->setType('instance', PARAM_INT);
683 $mform->addElement('hidden', 'add', 0);
684 $mform->setType('add', PARAM_ALPHA);
686 $mform->addElement('hidden', 'update', 0);
687 $mform->setType('update', PARAM_INT);
689 $mform->addElement('hidden', 'return', 0);
690 $mform->setType('return', PARAM_BOOL);
693 public function standard_grading_coursemodule_elements() {
694 global $COURSE, $CFG;
695 $mform =& $this->_form;
697 if ($this->_features->hasgrades) {
699 if (!$this->_features->rating || $this->_features->gradecat) {
700 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
703 //if supports grades and grades arent being handled via ratings
704 if (!$this->_features->rating) {
705 $mform->addElement('modgrade', 'grade', get_string('grade'));
706 $mform->setDefault('grade', 100);
709 if ($this->_features->advancedgrading
710 and !empty($this->current->_advancedgradingdata['methods'])
711 and !empty($this->current->_advancedgradingdata['areas'])) {
713 if (count($this->current->_advancedgradingdata['areas']) == 1) {
714 // if there is just one gradable area (most cases), display just the selector
715 // without its name to make UI simplier
716 $areadata = reset($this->current->_advancedgradingdata['areas']);
717 $areaname = key($this->current->_advancedgradingdata['areas']);
718 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
719 get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
720 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
722 } else {
723 // the module defines multiple gradable areas, display a selector
724 // for each of them together with a name of the area
725 $areasgroup = array();
726 foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
727 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
728 $areadata['title'], $this->current->_advancedgradingdata['methods']);
729 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
731 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
732 array(' ', '<br />'), false);
736 if ($this->_features->gradecat) {
737 $mform->addElement('select', 'gradecat',
738 get_string('gradecategoryonmodform', 'grades'),
739 grade_get_categories_menu($COURSE->id, $this->_outcomesused));
740 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
745 function add_intro_editor($required=false, $customlabel=null) {
746 if (!$this->_features->introeditor) {
747 // intro editor not supported in this module
748 return;
751 $mform = $this->_form;
752 $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
754 $mform->addElement('editor', 'introeditor', $label, null, array('maxfiles'=>EDITOR_UNLIMITED_FILES, 'noclean'=>true, 'context'=>$this->context));
755 $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
756 if ($required) {
757 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
760 // If the 'show description' feature is enabled, this checkbox appears
761 // below the intro.
762 if ($this->_features->showdescription) {
763 $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
764 $mform->addHelpButton('showdescription', 'showdescription');
769 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
771 * @param bool $cancel show cancel button
772 * @param string $submitlabel null means default, false means none, string is label text
773 * @param string $submit2label null means default, false means none, string is label text
774 * @return void
776 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
777 if (is_null($submitlabel)) {
778 $submitlabel = get_string('savechangesanddisplay');
781 if (is_null($submit2label)) {
782 $submit2label = get_string('savechangesandreturntocourse');
785 $mform = $this->_form;
787 // elements in a row need a group
788 $buttonarray = array();
790 if ($submit2label !== false) {
791 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
794 if ($submitlabel !== false) {
795 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
798 if ($cancel) {
799 $buttonarray[] = &$mform->createElement('cancel');
802 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
803 $mform->setType('buttonar', PARAM_RAW);
804 $mform->closeHeaderBefore('buttonar');