468e66d806c9cf779b8d4b79e8f6c17c7d7a30c3
[moodle.git] / course / moodleform_mod.php
1 <?php
2 require_once ($CFG->libdir.'/formslib.php');
3 if (!empty($CFG->enablecompletion) or !empty($CFG->enableavailability)) {
4     require_once($CFG->libdir.'/completionlib.php');
5 }
7 /**
8  * This class adds extra methods to form wrapper specific to be used for module
9  * add / update forms mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html
10  */
11 abstract class moodleform_mod extends moodleform {
12     /** Current data */
13     protected $current;
14     /**
15      * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
16      * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
17      * update one.
18      *
19      * @var mixed
20      */
21     protected $_instance;
22     /**
23      * Section of course that module instance will be put in or is in.
24      * This is always the section number itself (column 'section' from 'course_sections' table).
25      *
26      * @var mixed
27      */
28     protected $_section;
29     /**
30      * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
31      * update one.
32       *
33      * @var mixed
34      */
35     protected $_cm;
36     /**
37      * List of modform features
38      */
39     protected $_features;
40     /**
41      * @var array Custom completion-rule elements, if enabled
42      */
43     protected $_customcompletionelements;
44     /**
45      * @var string name of module
46      */
47     protected $_modname;
48     /** current context, course or module depends if already exists*/
49     protected $context;
51     /** a flag indicating whether outcomes are being used*/
52     protected $_outcomesused;
54     function moodleform_mod($current, $section, $cm, $course) {
55         $this->current   = $current;
56         $this->_instance = $current->instance;
57         $this->_section  = $section;
58         $this->_cm       = $cm;
59         if ($this->_cm) {
60             $this->context = get_context_instance(CONTEXT_MODULE, $this->_cm->id);
61         } else {
62             $this->context = get_context_instance(CONTEXT_COURSE, $course->id);
63         }
65         // Guess module name
66         $matches = array();
67         if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
68             debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
69             print_error('unknownmodulename');
70         }
71         $this->_modname = $matches[1];
72         $this->init_features();
73         parent::moodleform('modedit.php');
74     }
76     protected function init_features() {
77         global $CFG;
79         $this->_features = new stdClass();
80         $this->_features->groups            = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
81         $this->_features->groupings         = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
82         $this->_features->groupmembersonly  = (!empty($CFG->enablegroupmembersonly) and plugin_supports('mod', $this->_modname, FEATURE_GROUPMEMBERSONLY, false));
83         $this->_features->outcomes          = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
84         $this->_features->hasgrades         = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
85         $this->_features->idnumber          = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
86         $this->_features->introeditor       = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
87         $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
88         $this->_features->rating            = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
90         $this->_features->gradecat          = ($this->_features->outcomes or $this->_features->hasgrades);
91     }
93     /**
94      * Only available on moodleform_mod.
95      *
96      * @param array $default_values passed by reference
97      */
98     function data_preprocessing(&$default_values){
99         if (empty($default_values['scale'])) {
100             $default_values['assessed'] = 0;
101         }
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;
108         }
109     }
111     /**
112      * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
113      */
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;
128                     }
129                 }
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
139                             }
140                         }
141                     }
143                     foreach ($items as $item) {
144                         if (is_bool($gradecat)) {
145                             $gradecat = $item->categoryid;
146                             continue;
147                         }
148                         if ($gradecat != $item->categoryid) {
149                             //mixed categories
150                             $gradecat = false;
151                             break;
152                         }
153                     }
154                 }
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');
164                         }
165                     }
166                 }
167             }
168         }
170         if ($COURSE->groupmodeforce) {
171             if ($mform->elementExists('groupmode')) {
172                 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
173             }
174         }
176         if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
177             $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
179         } else if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
180             $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
182         } else if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
183             // groupings have no use without groupmode or groupmembersonly
184             if ($mform->elementExists('groupingid')) {
185                 $mform->removeElement('groupingid');
186             }
187         }
189         // Completion: If necessary, freeze fields
190         $completion = new completion_info($COURSE);
191         if ($completion->is_enabled()) {
192             // If anybody has completed the activity, these options will be 'locked'
193             $completedcount = empty($this->_cm)
194                 ? 0
195                 : $completion->count_user_data($this->_cm);
197             $freeze = false;
198             if (!$completedcount) {
199                 if ($mform->elementExists('unlockcompletion')) {
200                     $mform->removeElement('unlockcompletion');
201                 }
202             } else {
203                 // Has the element been unlocked?
204                 if ($mform->exportValue('unlockcompletion')) {
205                     // Yes, add in warning text and set the hidden variable
206                     $mform->insertElementBefore(
207                         $mform->createElement('static', 'completedunlocked',
208                             get_string('completedunlocked', 'completion'),
209                             get_string('completedunlockedtext', 'completion')),
210                         'unlockcompletion');
211                     $mform->removeElement('unlockcompletion');
212                     $mform->getElement('completionunlocked')->setValue(1);
213                 } else {
214                     // No, add in the warning text with the count (now we know
215                     // it) before the unlock button
216                     $mform->insertElementBefore(
217                         $mform->createElement('static', 'completedwarning',
218                             get_string('completedwarning', 'completion'),
219                             get_string('completedwarningtext', 'completion', $completedcount)),
220                         'unlockcompletion');
221                     $freeze = true;
222                 }
223             }
225             if ($freeze) {
226                 $mform->freeze('completion');
227                 if ($mform->elementExists('completionview')) {
228                     $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
229                 }
230                 if ($mform->elementExists('completionusegrade')) {
231                     $mform->freeze('completionusegrade');
232                 }
233                 $mform->freeze($this->_customcompletionelements);
234             }
235         }
237         // Availability conditions
238         if (!empty($CFG->enableavailability) && $this->_cm) {
239             $ci = new condition_info($this->_cm);
240             $fullcm=$ci->get_full_course_module();
242             $num=0;
243             foreach($fullcm->conditionsgrade as $gradeitemid=>$minmax) {
244                 $groupelements=$mform->getElement('conditiongradegroup['.$num.']')->getElements();
245                 $groupelements[0]->setValue($gradeitemid);
246                 // These numbers are always in the format 0.00000 - the rtrims remove any final zeros and,
247                 // if it is a whole number, the decimal place.
248                 $groupelements[2]->setValue(is_null($minmax->min)?'':rtrim(rtrim($minmax->min,'0'),'.'));
249                 $groupelements[4]->setValue(is_null($minmax->max)?'':rtrim(rtrim($minmax->max,'0'),'.'));
250                 $num++;
251             }
253             if ($completion->is_enabled()) {
254                 $num=0;
255                 foreach($fullcm->conditionscompletion as $othercmid=>$state) {
256                     $groupelements=$mform->getElement('conditioncompletiongroup['.$num.']')->getElements();
257                     $groupelements[0]->setValue($othercmid);
258                     $groupelements[1]->setValue($state);
259                     $num++;
260                 }
261             }
262         }
263     }
265     // form verification
266     function validation($data, $files) {
267         global $COURSE, $DB;
268         $errors = parent::validation($data, $files);
270         $mform =& $this->_form;
272         $errors = array();
274         if ($mform->elementExists('name')) {
275             $name = trim($data['name']);
276             if ($name == '') {
277                 $errors['name'] = get_string('required');
278             }
279         }
281         $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
282                      'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
283         if ($data['coursemodule']) {
284             $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
285         } else {
286             $cm = null;
287         }
289         if ($mform->elementExists('cmidnumber')) {
290             // verify the idnumber
291             if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
292                 $errors['cmidnumber'] = get_string('idnumbertaken');
293             }
294         }
296         // Completion: Don't let them choose automatic completion without turning
297         // on some conditions
298         if (array_key_exists('completion', $data) && $data['completion']==COMPLETION_TRACKING_AUTOMATIC) {
299             if (empty($data['completionview']) && empty($data['completionusegrade']) &&
300                 !$this->completion_rule_enabled($data)) {
301                 $errors['completion'] = get_string('badautocompletion', 'completion');
302             }
303         }
305         // Conditions: Don't let them set dates which make no sense
306         if (array_key_exists('availablefrom', $data) &&
307             $data['availablefrom'] && $data['availableuntil'] &&
308             $data['availablefrom'] > $data['availableuntil']) {
309             $errors['availablefrom'] = get_string('badavailabledates', 'condition');
310         }
312         return $errors;
313     }
315     /**
316      * Load in existing data as form defaults. Usually new entry defaults are stored directly in
317      * form definition (new entry form); this function is used to load in data where values
318      * already exist and data is being edited (edit entry form).
319      *
320      * @param mixed $default_values object or array of default values
321      */
322     function set_data($default_values) {
323         if (is_object($default_values)) {
324             $default_values = (array)$default_values;
325         }
327         $this->data_preprocessing($default_values);
328         parent::set_data($default_values);
329     }
331     /**
332      * Adds all the standard elements to a form to edit the settings for an activity module.
333      */
334     function standard_coursemodule_elements(){
335         global $COURSE, $CFG, $DB;
336         $mform =& $this->_form;
338         $this->_outcomesused = false;
339         if ($this->_features->outcomes) {
340             if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
341                 $this->_outcomesused = true;
342                 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
343                 foreach($outcomes as $outcome) {
344                     $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
345                 }
346             }
347         }
350         if ($this->_features->rating) {
351             require_once($CFG->dirroot.'/rating/lib.php');
352             $rm = new rating_manager();
354             $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
356             $permission=CAP_ALLOW;
357             $rolenamestring = null;
358             if (!empty($this->_cm)) {
359                 $context = get_context_instance(CONTEXT_MODULE, $this->_cm->id);
361                 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
362                 $rolenamestring = implode(', ', $rolenames);
363             } else {
364                 $rolenamestring = get_string('capabilitychecknotavailable','rating');
365             }
366             $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
367             $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
369             $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
370             $mform->setDefault('assessed', 0);
371             $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
373             $mform->addElement('modgrade', 'scale', get_string('scale'), false);
374             $mform->disabledIf('scale', 'assessed', 'eq', 0);
376             $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
377             $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
379             $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
380             $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
381             $mform->disabledIf('assesstimestart', 'ratingtime');
383             $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
384             $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
385             $mform->disabledIf('assesstimefinish', 'ratingtime');
386         }
388         //doing this here means splitting up the grade related settings on the lesson settings page
389         //$this->standard_grading_coursemodule_elements();
391         $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
392         if ($this->_features->groups) {
393             $options = array(NOGROUPS       => get_string('groupsnone'),
394                              SEPARATEGROUPS => get_string('groupsseparate'),
395                              VISIBLEGROUPS  => get_string('groupsvisible'));
396             $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
397             $mform->addHelpButton('groupmode', 'groupmode', 'group');
398         }
400         if ($this->_features->groupings or $this->_features->groupmembersonly) {
401             //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
402             $options = array();
403             $options[0] = get_string('none');
404             if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
405                 foreach ($groupings as $grouping) {
406                     $options[$grouping->id] = format_string($grouping->name);
407                 }
408             }
409             $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
410             $mform->addHelpButton('groupingid', 'grouping', 'group');
411             $mform->setAdvanced('groupingid');
412         }
414         if ($this->_features->groupmembersonly) {
415             $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
416             $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
417             $mform->setAdvanced('groupmembersonly');
418         }
420         $mform->addElement('modvisible', 'visible', get_string('visible'));
422         if ($this->_features->idnumber) {
423             $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
424             $mform->addHelpButton('cmidnumber', 'idnumbermod');
425         }
427         if (!empty($CFG->enableavailability)) {
428             // Conditional availability
429             $mform->addElement('header', '', get_string('availabilityconditions', 'condition'));
430             $mform->addElement('date_selector', 'availablefrom', get_string('availablefrom', 'condition'), array('optional'=>true));
431             $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
432             $mform->addElement('date_selector', 'availableuntil', get_string('availableuntil', 'condition'), array('optional'=>true));
434             // Conditions based on grades
435             $gradeoptions = array();
436             $items = grade_item::fetch_all(array('courseid'=>$COURSE->id));
437             $items = $items ? $items : array();
438             foreach($items as $id=>$item) {
439                 // Do not include grades for current item
440                 if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance
441                     && $this->_cm->modname == $item->itemmodule
442                     && $item->itemtype == 'mod') {
443                     continue;
444                 }
445                 $gradeoptions[$id] = $item->get_name();
446             }
447             asort($gradeoptions);
448             $gradeoptions = array(0=>get_string('none','condition'))+$gradeoptions;
450             $grouparray = array();
451             $grouparray[] =& $mform->createElement('select','conditiongradeitemid','',$gradeoptions);
452             $grouparray[] =& $mform->createElement('static', '', '',' '.get_string('grade_atleast','condition').' ');
453             $grouparray[] =& $mform->createElement('text', 'conditiongrademin','',array('size'=>3));
454             $grouparray[] =& $mform->createElement('static', '', '','% '.get_string('grade_upto','condition').' ');
455             $grouparray[] =& $mform->createElement('text', 'conditiongrademax','',array('size'=>3));
456             $grouparray[] =& $mform->createElement('static', '', '','%');
457             $mform->setType('conditiongrademin',PARAM_FLOAT);
458             $mform->setType('conditiongrademax',PARAM_FLOAT);
459             $group = $mform->createElement('group','conditiongradegroup',
460                 get_string('gradecondition', 'condition'),$grouparray);
462             // Get version with condition info and store it so we don't ask
463             // twice
464             if(!empty($this->_cm)) {
465                 $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
466                 $this->_cm = $ci->get_full_course_module();
467                 $count = count($this->_cm->conditionsgrade)+1;
468             } else {
469                 $count = 1;
470             }
472             $this->repeat_elements(array($group), $count, array(), 'conditiongraderepeats', 'conditiongradeadds', 2,
473                                    get_string('addgrades', 'condition'), true);
474             $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
476             // Conditions based on completion
477             $completion = new completion_info($COURSE);
478             if ($completion->is_enabled()) {
479                 $completionoptions = array();
480                 $modinfo = get_fast_modinfo($COURSE);
481                 foreach($modinfo->cms as $id=>$cm) {
482                     // Add each course-module if it:
483                     // (a) has completion turned on
484                     // (b) is not the same as current course-module
485                     if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
486                         $completionoptions[$id]=$cm->name;
487                     }
488                 }
489                 asort($completionoptions);
490                 $completionoptions = array(0=>get_string('none','condition'))+$completionoptions;
492                 $completionvalues=array(
493                     COMPLETION_COMPLETE=>get_string('completion_complete','condition'),
494                     COMPLETION_INCOMPLETE=>get_string('completion_incomplete','condition'),
495                     COMPLETION_COMPLETE_PASS=>get_string('completion_pass','condition'),
496                     COMPLETION_COMPLETE_FAIL=>get_string('completion_fail','condition'));
498                 $grouparray = array();
499                 $grouparray[] =& $mform->createElement('select','conditionsourcecmid','',$completionoptions);
500                 $grouparray[] =& $mform->createElement('select','conditionrequiredcompletion','',$completionvalues);
501                 $group = $mform->createElement('group','conditioncompletiongroup',
502                     get_string('completioncondition', 'condition'),$grouparray);
504                 $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion)+1;
505                 $this->repeat_elements(array($group),$count,array(),
506                     'conditioncompletionrepeats','conditioncompletionadds',2,
507                     get_string('addcompletions','condition'),true);
508                 $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
509             }
511             // Do we display availability info to students?
512             $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'),
513                     array(CONDITION_STUDENTVIEW_SHOW=>get_string('showavailability_show', 'condition'),
514                     CONDITION_STUDENTVIEW_HIDE=>get_string('showavailability_hide', 'condition')));
515             $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
516         }
518         // Conditional activities: completion tracking section
519         if(!isset($completion)) {
520             $completion = new completion_info($COURSE);
521         }
522         if ($completion->is_enabled()) {
523             $mform->addElement('header', '', get_string('activitycompletion', 'completion'));
525             // Unlock button for if people have completed it (will
526             // be removed in definition_after_data if they haven't)
527             $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
528             $mform->registerNoSubmitButton('unlockcompletion');
529             $mform->addElement('hidden', 'completionunlocked', 0);
530             $mform->setType('completionunlocked', PARAM_INT);
532             $mform->addElement('select', 'completion', get_string('completion', 'completion'),
533                 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
534                 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
535             $mform->setDefault('completion', $this->_features->defaultcompletion
536                 ? COMPLETION_TRACKING_MANUAL
537                 : COMPLETION_TRACKING_NONE);
538             $mform->addHelpButton('completion', 'completion', 'completion');
540             // Automatic completion once you view it
541             $gotcompletionoptions = false;
542             if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
543                 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
544                     get_string('completionview_desc', 'completion'));
545                 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
546                 $gotcompletionoptions = true;
547             }
549             // Automatic completion once it's graded
550             if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
551                 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
552                     get_string('completionusegrade_desc', 'completion'));
553                 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
554                 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
555                 $gotcompletionoptions = true;
556             }
558             // Automatic completion according to module-specific rules
559             $this->_customcompletionelements = $this->add_completion_rules();
560             foreach ($this->_customcompletionelements as $element) {
561                 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
562             }
564             $gotcompletionoptions = $gotcompletionoptions ||
565                 count($this->_customcompletionelements)>0;
567             // Automatic option only appears if possible
568             if ($gotcompletionoptions) {
569                 $mform->getElement('completion')->addOption(
570                     get_string('completion_automatic', 'completion'),
571                     COMPLETION_TRACKING_AUTOMATIC);
572             }
574             // Completion expected at particular date? (For progress tracking)
575             $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
576             $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
577             $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
578         }
580         $this->standard_hidden_coursemodule_elements();
581     }
583     /**
584      * Can be overridden to add custom completion rules if the module wishes
585      * them. If overriding this, you should also override completion_rule_enabled.
586      * <p>
587      * Just add elements to the form as needed and return the list of IDs. The
588      * system will call disabledIf and handle other behaviour for each returned
589      * ID.
590      * @return array Array of string IDs of added items, empty array if none
591      */
592     function add_completion_rules() {
593         return array();
594     }
596     /**
597      * Called during validation. Override to indicate, based on the data, whether
598      * a custom completion rule is enabled (selected).
599      *
600      * @param array $data Input data (not yet validated)
601      * @return bool True if one or more rules is enabled, false if none are;
602      *   default returns false
603      */
604     function completion_rule_enabled(&$data) {
605         return false;
606     }
608     function standard_hidden_coursemodule_elements(){
609         $mform =& $this->_form;
610         $mform->addElement('hidden', 'course', 0);
611         $mform->setType('course', PARAM_INT);
613         $mform->addElement('hidden', 'coursemodule', 0);
614         $mform->setType('coursemodule', PARAM_INT);
616         $mform->addElement('hidden', 'section', 0);
617         $mform->setType('section', PARAM_INT);
619         $mform->addElement('hidden', 'module', 0);
620         $mform->setType('module', PARAM_INT);
622         $mform->addElement('hidden', 'modulename', '');
623         $mform->setType('modulename', PARAM_SAFEDIR);
625         $mform->addElement('hidden', 'instance', 0);
626         $mform->setType('instance', PARAM_INT);
628         $mform->addElement('hidden', 'add', 0);
629         $mform->setType('add', PARAM_ALPHA);
631         $mform->addElement('hidden', 'update', 0);
632         $mform->setType('update', PARAM_INT);
634         $mform->addElement('hidden', 'return', 0);
635         $mform->setType('return', PARAM_BOOL);
636     }
638     public function standard_grading_coursemodule_elements() {
639         global $COURSE, $CFG;
640         $mform =& $this->_form;
642         if ($this->_features->hasgrades) {
644             if (!$this->_features->rating || $this->_features->gradecat) {
645                 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
646             }
648             //if supports grades and grades arent being handled via ratings
649             if (!$this->_features->rating) {
650                 $mform->addElement('modgrade', 'grade', get_string('grade'));
651                 $mform->setDefault('grade', 100);
652             }
654             if ($this->_features->gradecat) {
655                 $categories = grade_get_categories_menu($COURSE->id, $this->_outcomesused);
656                 $mform->addElement('select', 'gradecat', get_string('gradecategory', 'grades'), $categories);
657             }
658         }
659     }
661     function add_intro_editor($required=false, $customlabel=null) {
662         if (!$this->_features->introeditor) {
663             // intro editor not supported in this module
664             return;
665         }
667         $mform = $this->_form;
668         $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
670         $mform->addElement('editor', 'introeditor', $label, null, array('maxfiles'=>EDITOR_UNLIMITED_FILES, 'noclean'=>true, 'context'=>$this->context));
671         $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
672         if ($required) {
673             $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
674         }
675     }
677     /**
678      * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
679      *
680      * @param bool $cancel show cancel button
681      * @param string $submitlabel null means default, false means none, string is label text
682      * @param string $submit2label  null means default, false means none, string is label text
683      * @return void
684      */
685     function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
686         if (is_null($submitlabel)) {
687             $submitlabel = get_string('savechangesanddisplay');
688         }
690         if (is_null($submit2label)) {
691             $submit2label = get_string('savechangesandreturntocourse');
692         }
694         $mform = $this->_form;
696         // elements in a row need a group
697         $buttonarray = array();
699         if ($submit2label !== false) {
700             $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
701         }
703         if ($submitlabel !== false) {
704             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
705         }
707         if ($cancel) {
708             $buttonarray[] = &$mform->createElement('cancel');
709         }
711         $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
712         $mform->setType('buttonar', PARAM_RAW);
713         $mform->closeHeaderBefore('buttonar');
714     }