7dc44367101ee4c9ff5015dd29565e9370e1c071
[moodle.git] / course / moodleform_mod.php
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.
16      *
17      * @var mixed
18      */
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).
23      *
24      * @var mixed
25      */
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.
30       *
31      * @var mixed
32      */
33     protected $_cm;
34     /**
35      * List of modform features
36      */
37     protected $_features;
38     /**
39      * @var array Custom completion-rule elements, if enabled
40      */
41     protected $_customcompletionelements;
42     /**
43      * @var string name of module
44      */
45     protected $_modname;
46     /** current context, course or module depends if already exists*/
47     protected $context;
49     /** a flag indicating whether outcomes are being used*/
50     protected $_outcomesused;
52     /**
53      * @var bool A flag used to indicate that this module should lock settings
54      *           based on admin settings flags in definition_after_data.
55      */
56     protected $applyadminlockedflags = false;
58     /** @var object The course format of the current course. */
59     protected $courseformat;
61     function moodleform_mod($current, $section, $cm, $course) {
62         global $CFG;
64         $this->current   = $current;
65         $this->_instance = $current->instance;
66         $this->_section  = $section;
67         $this->_cm       = $cm;
68         if ($this->_cm) {
69             $this->context = context_module::instance($this->_cm->id);
70         } else {
71             $this->context = context_course::instance($course->id);
72         }
74         // Set the course format.
75         require_once($CFG->dirroot . '/course/format/lib.php');
76         $this->courseformat = course_get_format($course);
78         // Guess module name
79         $matches = array();
80         if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
81             debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
82             print_error('unknownmodulename');
83         }
84         $this->_modname = $matches[1];
85         $this->init_features();
86         parent::moodleform('modedit.php');
87     }
89     protected function init_features() {
90         global $CFG;
92         $this->_features = new stdClass();
93         $this->_features->groups            = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
94         $this->_features->groupings         = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
95         $this->_features->groupmembersonly  = (!empty($CFG->enablegroupmembersonly) and plugin_supports('mod', $this->_modname, FEATURE_GROUPMEMBERSONLY, false));
96         $this->_features->outcomes          = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
97         $this->_features->hasgrades         = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
98         $this->_features->idnumber          = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
99         $this->_features->introeditor       = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
100         $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
101         $this->_features->rating            = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
102         $this->_features->showdescription   = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
104         $this->_features->gradecat          = ($this->_features->outcomes or $this->_features->hasgrades);
105         $this->_features->advancedgrading   = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
106     }
108     /**
109      * Only available on moodleform_mod.
110      *
111      * @param array $default_values passed by reference
112      */
113     function data_preprocessing(&$default_values){
114         if (empty($default_values['scale'])) {
115             $default_values['assessed'] = 0;
116         }
118         if (empty($default_values['assessed'])){
119             $default_values['ratingtime'] = 0;
120         } else {
121             $default_values['ratingtime']=
122                 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
123         }
124     }
126     /**
127      * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
128      */
129     function definition_after_data() {
130         global $CFG, $COURSE;
131         $mform =& $this->_form;
133         if ($id = $mform->getElementValue('update')) {
134             $modulename = $mform->getElementValue('modulename');
135             $instance   = $mform->getElementValue('instance');
137             if ($this->_features->gradecat) {
138                 $gradecat = false;
139                 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
140                     $outcomes = grade_outcome::fetch_all_available($COURSE->id);
141                     if (!empty($outcomes)) {
142                         $gradecat = true;
143                     }
144                 }
146                 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
147                 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
148                 if (!empty($items)) {
149                     foreach ($items as $item) {
150                         if (!empty($item->outcomeid)) {
151                             $elname = 'outcome_'.$item->outcomeid;
152                             if ($mform->elementExists($elname)) {
153                                 $mform->hardFreeze($elname); // prevent removing of existing outcomes
154                             }
155                         }
156                     }
158                     foreach ($items as $item) {
159                         if (is_bool($gradecat)) {
160                             $gradecat = $item->categoryid;
161                             continue;
162                         }
163                         if ($gradecat != $item->categoryid) {
164                             //mixed categories
165                             $gradecat = false;
166                             break;
167                         }
168                     }
169                 }
171                 if ($gradecat === false) {
172                     // items and outcomes in different categories - remove the option
173                     // TODO: add a "Mixed categories" text instead of removing elements with no explanation
174                     if ($mform->elementExists('gradecat')) {
175                         $mform->removeElement('gradecat');
176                         if ($this->_features->rating) {
177                             //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
178                             $mform->removeElement('modstandardgrade');
179                         }
180                     }
181                 }
182             }
183         }
185         if ($COURSE->groupmodeforce) {
186             if ($mform->elementExists('groupmode')) {
187                 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
188             }
189         }
191         // Don't disable/remove groupingid if it is currently set to something,
192         // otherwise you cannot turn it off at same time as turning off other
193         // option (MDL-30764)
194         if (empty($this->_cm) || !$this->_cm->groupingid) {
195             if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
196                 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
198             } else if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
199                 $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
201             } else if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
202                 // groupings have no use without groupmode or groupmembersonly
203                 if ($mform->elementExists('groupingid')) {
204                     $mform->removeElement('groupingid');
205                 }
206             }
207         }
209         // Completion: If necessary, freeze fields
210         $completion = new completion_info($COURSE);
211         if ($completion->is_enabled()) {
212             // If anybody has completed the activity, these options will be 'locked'
213             $completedcount = empty($this->_cm)
214                 ? 0
215                 : $completion->count_user_data($this->_cm);
217             $freeze = false;
218             if (!$completedcount) {
219                 if ($mform->elementExists('unlockcompletion')) {
220                     $mform->removeElement('unlockcompletion');
221                 }
222                 // Automatically set to unlocked (note: this is necessary
223                 // in order to make it recalculate completion once the option
224                 // is changed, maybe someone has completed it now)
225                 $mform->getElement('completionunlocked')->setValue(1);
226             } else {
227                 // Has the element been unlocked?
228                 if ($mform->exportValue('unlockcompletion')) {
229                     // Yes, add in warning text and set the hidden variable
230                     $mform->insertElementBefore(
231                         $mform->createElement('static', 'completedunlocked',
232                             get_string('completedunlocked', 'completion'),
233                             get_string('completedunlockedtext', 'completion')),
234                         'unlockcompletion');
235                     $mform->removeElement('unlockcompletion');
236                     $mform->getElement('completionunlocked')->setValue(1);
237                 } else {
238                     // No, add in the warning text with the count (now we know
239                     // it) before the unlock button
240                     $mform->insertElementBefore(
241                         $mform->createElement('static', 'completedwarning',
242                             get_string('completedwarning', 'completion'),
243                             get_string('completedwarningtext', 'completion', $completedcount)),
244                         'unlockcompletion');
245                     $freeze = true;
246                 }
247             }
249             if ($freeze) {
250                 $mform->freeze('completion');
251                 if ($mform->elementExists('completionview')) {
252                     $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
253                 }
254                 if ($mform->elementExists('completionusegrade')) {
255                     $mform->freeze('completionusegrade');
256                 }
257                 $mform->freeze($this->_customcompletionelements);
258             }
259         }
261         // Freeze admin defaults if required (and not different from default)
262         $this->apply_admin_locked_flags();
263     }
265     // form verification
266     function validation($data, $files) {
267         global $COURSE, $DB, $CFG;
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. Ignore this check when completion settings are
298         // locked, as the options are then disabled.
299         if (array_key_exists('completion', $data) &&
300                 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
301                 !empty($data['completionunlocked'])) {
302             if (empty($data['completionview']) && empty($data['completionusegrade']) &&
303                 !$this->completion_rule_enabled($data)) {
304                 $errors['completion'] = get_string('badautocompletion', 'completion');
305             }
306         }
308         // Availability: Check availability field does not have errors.
309         if (!empty($CFG->enableavailability)) {
310             \core_availability\frontend::report_validation_errors($data, $errors);
311         }
313         return $errors;
314     }
316     /**
317      * Load in existing data as form defaults. Usually new entry defaults are stored directly in
318      * form definition (new entry form); this function is used to load in data where values
319      * already exist and data is being edited (edit entry form).
320      *
321      * @param mixed $default_values object or array of default values
322      */
323     function set_data($default_values) {
324         if (is_object($default_values)) {
325             $default_values = (array)$default_values;
326         }
328         $this->data_preprocessing($default_values);
329         parent::set_data($default_values);
330     }
332     /**
333      * Adds all the standard elements to a form to edit the settings for an activity module.
334      */
335     function standard_coursemodule_elements(){
336         global $COURSE, $CFG, $DB;
337         $mform =& $this->_form;
339         $this->_outcomesused = false;
340         if ($this->_features->outcomes) {
341             if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
342                 $this->_outcomesused = true;
343                 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
344                 foreach($outcomes as $outcome) {
345                     $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
346                 }
347             }
348         }
351         if ($this->_features->rating) {
352             require_once($CFG->dirroot.'/rating/lib.php');
353             $rm = new rating_manager();
355             $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
357             $permission=CAP_ALLOW;
358             $rolenamestring = null;
359             if (!empty($this->_cm)) {
360                 $context = context_module::instance($this->_cm->id);
362                 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
363                 $rolenamestring = implode(', ', $rolenames);
364             } else {
365                 $rolenamestring = get_string('capabilitychecknotavailable','rating');
366             }
367             $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
368             $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
370             $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
371             $mform->setDefault('assessed', 0);
372             $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
374             $mform->addElement('modgrade', 'scale', get_string('scale'), false);
375             $mform->disabledIf('scale', 'assessed', 'eq', 0);
376             $mform->addHelpButton('scale', 'modgrade', 'grades');
377             $mform->setDefault('scale', $CFG->gradepointdefault);
379             $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
380             $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
382             $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
383             $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
384             $mform->disabledIf('assesstimestart', 'ratingtime');
386             $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
387             $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
388             $mform->disabledIf('assesstimefinish', 'ratingtime');
389         }
391         //doing this here means splitting up the grade related settings on the lesson settings page
392         //$this->standard_grading_coursemodule_elements();
394         $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
396         $mform->addElement('modvisible', 'visible', get_string('visible'));
397         if (!empty($this->_cm)) {
398             $context = context_module::instance($this->_cm->id);
399             if (!has_capability('moodle/course:activityvisibility', $context)) {
400                 $mform->hardFreeze('visible');
401             }
402         }
404         if ($this->_features->idnumber) {
405             $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
406             $mform->setType('cmidnumber', PARAM_RAW);
407             $mform->addHelpButton('cmidnumber', 'idnumbermod');
408         }
410         if ($this->_features->groups) {
411             $options = array(NOGROUPS       => get_string('groupsnone'),
412                              SEPARATEGROUPS => get_string('groupsseparate'),
413                              VISIBLEGROUPS  => get_string('groupsvisible'));
414             $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
415             $mform->addHelpButton('groupmode', 'groupmode', 'group');
416         }
418         if ($this->_features->groupings or $this->_features->groupmembersonly) {
419             //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
420             $options = array();
421             if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
422                 foreach ($groupings as $grouping) {
423                     $options[$grouping->id] = format_string($grouping->name);
424                 }
425             }
426             core_collator::asort($options);
427             $options = array(0 => get_string('none')) + $options;
428             $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
429             $mform->addHelpButton('groupingid', 'grouping', 'group');
430         }
432         if ($this->_features->groupmembersonly) {
433             $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
434             $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
435         }
437         if (!empty($CFG->enableavailability)) {
438             // Availability field. This is just a textarea; the user interface
439             // interaction is all implemented in JavaScript.
440             $mform->addElement('header', 'availabilityconditionsheader',
441                     get_string('restrictaccess', 'availability'));
442             // Note: This field cannot be named 'availability' because that
443             // conflicts with fields in existing modules (such as assign).
444             // So it uses a long name that will not conflict.
445             $mform->addElement('textarea', 'availabilityconditionsjson',
446                     get_string('accessrestrictions', 'availability'));
447             // The _cm variable may not be a proper cm_info, so get one from modinfo.
448             if ($this->_cm) {
449                 $modinfo = get_fast_modinfo($COURSE);
450                 $cm = $modinfo->get_cm($this->_cm->id);
451             } else {
452                 $cm = null;
453             }
454             \core_availability\frontend::include_all_javascript($COURSE, $cm);
455         }
457         // Conditional activities: completion tracking section
458         if(!isset($completion)) {
459             $completion = new completion_info($COURSE);
460         }
461         if ($completion->is_enabled()) {
462             $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
464             // Unlock button for if people have completed it (will
465             // be removed in definition_after_data if they haven't)
466             $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
467             $mform->registerNoSubmitButton('unlockcompletion');
468             $mform->addElement('hidden', 'completionunlocked', 0);
469             $mform->setType('completionunlocked', PARAM_INT);
471             $trackingdefault = COMPLETION_TRACKING_NONE;
472             // If system and activity default is on, set it.
473             if ($CFG->completiondefault && $this->_features->defaultcompletion) {
474                 $trackingdefault = COMPLETION_TRACKING_MANUAL;
475             }
477             $mform->addElement('select', 'completion', get_string('completion', 'completion'),
478                 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
479                 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
480             $mform->setDefault('completion', $trackingdefault);
481             $mform->addHelpButton('completion', 'completion', 'completion');
483             // Automatic completion once you view it
484             $gotcompletionoptions = false;
485             if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
486                 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
487                     get_string('completionview_desc', 'completion'));
488                 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
489                 $gotcompletionoptions = true;
490             }
492             // Automatic completion once it's graded
493             if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
494                 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
495                     get_string('completionusegrade_desc', 'completion'));
496                 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
497                 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
498                 $gotcompletionoptions = true;
499             }
501             // Automatic completion according to module-specific rules
502             $this->_customcompletionelements = $this->add_completion_rules();
503             foreach ($this->_customcompletionelements as $element) {
504                 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
505             }
507             $gotcompletionoptions = $gotcompletionoptions ||
508                 count($this->_customcompletionelements)>0;
510             // Automatic option only appears if possible
511             if ($gotcompletionoptions) {
512                 $mform->getElement('completion')->addOption(
513                     get_string('completion_automatic', 'completion'),
514                     COMPLETION_TRACKING_AUTOMATIC);
515             }
517             // Completion expected at particular date? (For progress tracking)
518             $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
519             $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
520             $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
521         }
523         $this->standard_hidden_coursemodule_elements();
524     }
526     /**
527      * Can be overridden to add custom completion rules if the module wishes
528      * them. If overriding this, you should also override completion_rule_enabled.
529      * <p>
530      * Just add elements to the form as needed and return the list of IDs. The
531      * system will call disabledIf and handle other behaviour for each returned
532      * ID.
533      * @return array Array of string IDs of added items, empty array if none
534      */
535     function add_completion_rules() {
536         return array();
537     }
539     /**
540      * Called during validation. Override to indicate, based on the data, whether
541      * a custom completion rule is enabled (selected).
542      *
543      * @param array $data Input data (not yet validated)
544      * @return bool True if one or more rules is enabled, false if none are;
545      *   default returns false
546      */
547     function completion_rule_enabled($data) {
548         return false;
549     }
551     function standard_hidden_coursemodule_elements(){
552         $mform =& $this->_form;
553         $mform->addElement('hidden', 'course', 0);
554         $mform->setType('course', PARAM_INT);
556         $mform->addElement('hidden', 'coursemodule', 0);
557         $mform->setType('coursemodule', PARAM_INT);
559         $mform->addElement('hidden', 'section', 0);
560         $mform->setType('section', PARAM_INT);
562         $mform->addElement('hidden', 'module', 0);
563         $mform->setType('module', PARAM_INT);
565         $mform->addElement('hidden', 'modulename', '');
566         $mform->setType('modulename', PARAM_PLUGIN);
568         $mform->addElement('hidden', 'instance', 0);
569         $mform->setType('instance', PARAM_INT);
571         $mform->addElement('hidden', 'add', 0);
572         $mform->setType('add', PARAM_ALPHA);
574         $mform->addElement('hidden', 'update', 0);
575         $mform->setType('update', PARAM_INT);
577         $mform->addElement('hidden', 'return', 0);
578         $mform->setType('return', PARAM_BOOL);
580         $mform->addElement('hidden', 'sr', 0);
581         $mform->setType('sr', PARAM_INT);
582     }
584     public function standard_grading_coursemodule_elements() {
585         global $COURSE, $CFG;
586         $mform =& $this->_form;
588         if ($this->_features->hasgrades) {
590             if (!$this->_features->rating || $this->_features->gradecat) {
591                 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
592             }
594             //if supports grades and grades arent being handled via ratings
595             if (!$this->_features->rating) {
596                 $mform->addElement('modgrade', 'grade', get_string('grade'));
597                 $mform->addHelpButton('grade', 'modgrade', 'grades');
598                 $mform->setDefault('grade', $CFG->gradepointdefault);
599             }
601             if ($this->_features->advancedgrading
602                     and !empty($this->current->_advancedgradingdata['methods'])
603                     and !empty($this->current->_advancedgradingdata['areas'])) {
605                 if (count($this->current->_advancedgradingdata['areas']) == 1) {
606                     // if there is just one gradable area (most cases), display just the selector
607                     // without its name to make UI simplier
608                     $areadata = reset($this->current->_advancedgradingdata['areas']);
609                     $areaname = key($this->current->_advancedgradingdata['areas']);
610                     $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
611                         get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
612                     $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
614                 } else {
615                     // the module defines multiple gradable areas, display a selector
616                     // for each of them together with a name of the area
617                     $areasgroup = array();
618                     foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
619                         $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
620                             $areadata['title'], $this->current->_advancedgradingdata['methods']);
621                         $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
622                     }
623                     $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
624                         array(' ', '<br />'), false);
625                 }
626             }
628             if ($this->_features->gradecat) {
629                 $mform->addElement('select', 'gradecat',
630                         get_string('gradecategoryonmodform', 'grades'),
631                         grade_get_categories_menu($COURSE->id, $this->_outcomesused));
632                 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
633             }
634         }
635     }
637     function add_intro_editor($required=false, $customlabel=null) {
638         if (!$this->_features->introeditor) {
639             // intro editor not supported in this module
640             return;
641         }
643         $mform = $this->_form;
644         $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
646         $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
647             'noclean' => true, 'context' => $this->context, 'subdirs' => true));
648         $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
649         if ($required) {
650             $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
651         }
653         // If the 'show description' feature is enabled, this checkbox appears below the intro.
654         // We want to hide that when using the singleactivity course format because it is confusing.
655         if ($this->_features->showdescription  && $this->courseformat->has_view_page()) {
656             $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
657             $mform->addHelpButton('showdescription', 'showdescription');
658         }
659     }
661     /**
662      * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
663      *
664      * @param bool $cancel show cancel button
665      * @param string $submitlabel null means default, false means none, string is label text
666      * @param string $submit2label  null means default, false means none, string is label text
667      * @return void
668      */
669     function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
670         if (is_null($submitlabel)) {
671             $submitlabel = get_string('savechangesanddisplay');
672         }
674         if (is_null($submit2label)) {
675             $submit2label = get_string('savechangesandreturntocourse');
676         }
678         $mform = $this->_form;
680         // elements in a row need a group
681         $buttonarray = array();
683         // Label for the submit button to return to the course.
684         // Ignore this button in single activity format because it is confusing.
685         if ($submit2label !== false && $this->courseformat->has_view_page()) {
686             $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
687         }
689         if ($submitlabel !== false) {
690             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
691         }
693         if ($cancel) {
694             $buttonarray[] = &$mform->createElement('cancel');
695         }
697         $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
698         $mform->setType('buttonar', PARAM_RAW);
699         $mform->closeHeaderBefore('buttonar');
700     }
702     /**
703      * Get the list of admin settings for this module and apply any locked settings.
704      * This cannot happen in apply_admin_defaults because we do not the current values of the settings
705      * in that function because set_data has not been called yet.
706      *
707      * @return void
708      */
709     protected function apply_admin_locked_flags() {
710         global $OUTPUT;
712         if (!$this->applyadminlockedflags) {
713             return;
714         }
716         $settings = get_config($this->_modname);
717         $mform = $this->_form;
718         $lockedicon = html_writer::tag('span',
719                                        $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
720                                        array('class' => 'action-icon'));
721         $isupdate = !empty($this->_cm);
723         foreach ($settings as $name => $value) {
724             if (strpos('_', $name) !== false) {
725                 continue;
726             }
727             if ($mform->elementExists($name)) {
728                 $element = $mform->getElement($name);
729                 $lockedsetting = $name . '_locked';
730                 if (!empty($settings->$lockedsetting)) {
731                     // Always lock locked settings for new modules,
732                     // for updates, only lock them if the current value is the same as the default (or there is no current value).
733                     $value = $settings->$name;
734                     if ($isupdate && isset($this->current->$name)) {
735                         $value = $this->current->$name;
736                     }
737                     if ($value == $settings->$name) {
738                         $mform->setConstant($name, $settings->$name);
739                         $element->setLabel($element->getLabel() . $lockedicon);
740                         // Do not use hardfreeze because we need the hidden input to check dependencies.
741                         $element->freeze();
742                     }
743                 }
744             }
745         }
746     }
748     /**
749      * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
750      *
751      * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
752      *                         default date/time value should be relative to. If not passed, all
753      *                         date/time fields are set relative to the users current midnight.
754      * @return void
755      */
756     public function apply_admin_defaults($datetimeoffsets = array()) {
757         // This flag triggers the settings to be locked in apply_admin_locked_flags().
758         $this->applyadminlockedflags = true;
760         $settings = get_config($this->_modname);
761         $mform = $this->_form;
762         $usermidnight = usergetmidnight(time());
763         $isupdate = !empty($this->_cm);
765         foreach ($settings as $name => $value) {
766             if (strpos('_', $name) !== false) {
767                 continue;
768             }
769             if ($mform->elementExists($name)) {
770                 $element = $mform->getElement($name);
771                 if (!$isupdate) {
772                     if ($element->getType() == 'date_time_selector') {
773                         $enabledsetting = $name . '_enabled';
774                         if (empty($settings->$enabledsetting)) {
775                             $mform->setDefault($name, 0);
776                         } else {
777                             $relativetime = $usermidnight;
778                             if (isset($datetimeoffsets[$name])) {
779                                 $relativetime = $datetimeoffsets[$name];
780                             }
781                             $mform->setDefault($name, $relativetime + $settings->$name);
782                         }
783                     } else {
784                         $mform->setDefault($name, $settings->$name);
785                     }
786                 }
787                 $advancedsetting = $name . '_adv';
788                 if (!empty($settings->$advancedsetting)) {
789                     $mform->setAdvanced($name);
790                 }
791             }
792         }
793     }