MDL-51267 mod_url: make the url and resource forms friendlier
[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     public function __construct($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::__construct('modedit.php');
87     }
89     /**
90      * Old syntax of class constructor. Deprecated in PHP7.
91      *
92      * @deprecated since Moodle 3.1
93      */
94     public function moodleform_mod($current, $section, $cm, $course) {
95         debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
96         self::__construct($current, $section, $cm, $course);
97     }
99     protected function init_features() {
100         global $CFG;
102         $this->_features = new stdClass();
103         $this->_features->groups            = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
104         $this->_features->groupings         = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
105         $this->_features->outcomes          = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
106         $this->_features->hasgrades         = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
107         $this->_features->idnumber          = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
108         $this->_features->introeditor       = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
109         $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
110         $this->_features->rating            = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
111         $this->_features->showdescription   = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
112         $this->_features->gradecat          = ($this->_features->outcomes or $this->_features->hasgrades);
113         $this->_features->advancedgrading   = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
114         $this->_features->canrescale = (component_callback_exists('mod_' . $this->_modname, 'rescale_activity_grades') !== false);
115     }
117     /**
118      * Only available on moodleform_mod.
119      *
120      * @param array $default_values passed by reference
121      */
122     function data_preprocessing(&$default_values){
123         if (empty($default_values['scale'])) {
124             $default_values['assessed'] = 0;
125         }
127         if (empty($default_values['assessed'])){
128             $default_values['ratingtime'] = 0;
129         } else {
130             $default_values['ratingtime']=
131                 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
132         }
133     }
135     /**
136      * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
137      */
138     function definition_after_data() {
139         global $CFG, $COURSE;
140         $mform =& $this->_form;
142         if ($id = $mform->getElementValue('update')) {
143             $modulename = $mform->getElementValue('modulename');
144             $instance   = $mform->getElementValue('instance');
146             if ($this->_features->gradecat) {
147                 $gradecat = false;
148                 if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
149                     $outcomes = grade_outcome::fetch_all_available($COURSE->id);
150                     if (!empty($outcomes)) {
151                         $gradecat = true;
152                     }
153                 }
155                 $hasgradeitems = false;
156                 $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
157                 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
158                 if (!empty($items)) {
159                     foreach ($items as $item) {
160                         if (!empty($item->outcomeid)) {
161                             $elname = 'outcome_'.$item->outcomeid;
162                             if ($mform->elementExists($elname)) {
163                                 $mform->hardFreeze($elname); // prevent removing of existing outcomes
164                             }
165                         } else {
166                             $hasgradeitems = true;
167                         }
168                     }
170                     foreach ($items as $item) {
171                         if (is_bool($gradecat)) {
172                             $gradecat = $item->categoryid;
173                             continue;
174                         }
175                         if ($gradecat != $item->categoryid) {
176                             //mixed categories
177                             $gradecat = false;
178                             break;
179                         }
180                     }
181                 }
183                 if (!$hasgradeitems && $mform->elementExists('gradepass')) {
184                     // Remove form element 'Grade to pass' since there are no grade items (when rating not selected).
185                     $mform->removeElement('gradepass');
186                 }
188                 if ($gradecat === false) {
189                     // items and outcomes in different categories - remove the option
190                     // TODO: add a "Mixed categories" text instead of removing elements with no explanation
191                     if ($mform->elementExists('gradecat')) {
192                         $mform->removeElement('gradecat');
193                         if ($this->_features->rating  && !$mform->elementExists('gradepass')) {
194                             //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
195                             $mform->removeElement('modstandardgrade');
196                         }
197                     }
198                 }
199             }
200         }
202         if ($COURSE->groupmodeforce) {
203             if ($mform->elementExists('groupmode')) {
204                 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
205             }
206         }
208         // Don't disable/remove groupingid if it is currently set to something,
209         // otherwise you cannot turn it off at same time as turning off other
210         // option (MDL-30764)
211         if (empty($this->_cm) || !$this->_cm->groupingid) {
212             if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
213                 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
215             } else if (!$mform->elementExists('groupmode')) {
216                 // Groupings have no use without groupmode.
217                 if ($mform->elementExists('groupingid')) {
218                     $mform->removeElement('groupingid');
219                 }
220             }
221         }
223         // Completion: If necessary, freeze fields
224         $completion = new completion_info($COURSE);
225         if ($completion->is_enabled()) {
226             // If anybody has completed the activity, these options will be 'locked'
227             $completedcount = empty($this->_cm)
228                 ? 0
229                 : $completion->count_user_data($this->_cm);
231             $freeze = false;
232             if (!$completedcount) {
233                 if ($mform->elementExists('unlockcompletion')) {
234                     $mform->removeElement('unlockcompletion');
235                 }
236                 // Automatically set to unlocked (note: this is necessary
237                 // in order to make it recalculate completion once the option
238                 // is changed, maybe someone has completed it now)
239                 $mform->getElement('completionunlocked')->setValue(1);
240             } else {
241                 // Has the element been unlocked, either by the button being pressed
242                 // in this request, or the field already being set from a previous one?
243                 if ($mform->exportValue('unlockcompletion') ||
244                         $mform->exportValue('completionunlocked')) {
245                     // Yes, add in warning text and set the hidden variable
246                     $mform->insertElementBefore(
247                         $mform->createElement('static', 'completedunlocked',
248                             get_string('completedunlocked', 'completion'),
249                             get_string('completedunlockedtext', 'completion')),
250                         'unlockcompletion');
251                     $mform->removeElement('unlockcompletion');
252                     $mform->getElement('completionunlocked')->setValue(1);
253                 } else {
254                     // No, add in the warning text with the count (now we know
255                     // it) before the unlock button
256                     $mform->insertElementBefore(
257                         $mform->createElement('static', 'completedwarning',
258                             get_string('completedwarning', 'completion'),
259                             get_string('completedwarningtext', 'completion', $completedcount)),
260                         'unlockcompletion');
261                     $freeze = true;
262                 }
263             }
265             if ($freeze) {
266                 $mform->freeze('completion');
267                 if ($mform->elementExists('completionview')) {
268                     $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
269                 }
270                 if ($mform->elementExists('completionusegrade')) {
271                     $mform->freeze('completionusegrade');
272                 }
273                 $mform->freeze($this->_customcompletionelements);
274             }
275         }
277         // Freeze admin defaults if required (and not different from default)
278         $this->apply_admin_locked_flags();
279     }
281     // form verification
282     function validation($data, $files) {
283         global $COURSE, $DB, $CFG;
284         $errors = parent::validation($data, $files);
286         $mform =& $this->_form;
288         $errors = array();
290         if ($mform->elementExists('name')) {
291             $name = trim($data['name']);
292             if ($name == '') {
293                 $errors['name'] = get_string('required');
294             }
295         }
297         $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
298                      'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
299         if ($data['coursemodule']) {
300             $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
301         } else {
302             $cm = null;
303         }
305         if ($mform->elementExists('cmidnumber')) {
306             // verify the idnumber
307             if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
308                 $errors['cmidnumber'] = get_string('idnumbertaken');
309             }
310         }
312         // Ratings: Don't let them select an aggregate type without selecting a scale.
313         // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
314         // invalid. If ratings have been selected then the user must select either a scale or max points.
315         // This matches (horrible) logic in data_preprocessing.
316         if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
317             $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
318         }
320         // Check that the grade pass is a valid number.
321         $gradepassvalid = false;
322         if (isset($data['gradepass'])) {
323             if (unformat_float($data['gradepass'], true) === false) {
324                 $errors['gradepass'] = get_string('err_numeric', 'form');
325             } else {
326                 $gradepassvalid = true;
327             }
328         }
330         // Grade to pass: ensure that the grade to pass is valid for points and scales.
331         // If we are working with a scale, convert into a positive number for validation.
332         if ($gradepassvalid && isset($data['gradepass']) && (!empty($data['grade']) || !empty($data['scale']))) {
333             $scale = !empty($data['grade']) ? $data['grade'] : $data['scale'];
334             if ($scale < 0) {
335                 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
336                 $grade = count(explode(',', $scalevalues->scale));
337             } else {
338                 $grade = $scale;
339             }
340             if ($data['gradepass'] > $grade) {
341                 $errors['gradepass'] = get_string('gradepassgreaterthangrade', 'grades', $grade);
342             }
343         }
345         // Completion: Don't let them choose automatic completion without turning
346         // on some conditions. Ignore this check when completion settings are
347         // locked, as the options are then disabled.
348         if (array_key_exists('completion', $data) &&
349                 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
350                 !empty($data['completionunlocked'])) {
351             if (empty($data['completionview']) && empty($data['completionusegrade']) &&
352                 !$this->completion_rule_enabled($data)) {
353                 $errors['completion'] = get_string('badautocompletion', 'completion');
354             }
355         }
357         // Availability: Check availability field does not have errors.
358         if (!empty($CFG->enableavailability)) {
359             \core_availability\frontend::report_validation_errors($data, $errors);
360         }
362         return $errors;
363     }
365     /**
366      * Load in existing data as form defaults. Usually new entry defaults are stored directly in
367      * form definition (new entry form); this function is used to load in data where values
368      * already exist and data is being edited (edit entry form).
369      *
370      * @param mixed $default_values object or array of default values
371      */
372     function set_data($default_values) {
373         if (is_object($default_values)) {
374             $default_values = (array)$default_values;
375         }
377         $this->data_preprocessing($default_values);
378         parent::set_data($default_values);
379     }
381     /**
382      * Adds all the standard elements to a form to edit the settings for an activity module.
383      */
384     function standard_coursemodule_elements(){
385         global $COURSE, $CFG, $DB;
386         $mform =& $this->_form;
388         $this->_outcomesused = false;
389         if ($this->_features->outcomes) {
390             if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
391                 $this->_outcomesused = true;
392                 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
393                 foreach($outcomes as $outcome) {
394                     $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
395                 }
396             }
397         }
400         if ($this->_features->rating) {
401             require_once($CFG->dirroot.'/rating/lib.php');
402             $rm = new rating_manager();
404             $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
406             $permission=CAP_ALLOW;
407             $rolenamestring = null;
408             $isupdate = false;
409             if (!empty($this->_cm)) {
410                 $isupdate = true;
411                 $context = context_module::instance($this->_cm->id);
413                 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
414                 $rolenamestring = implode(', ', $rolenames);
415             } else {
416                 $rolenamestring = get_string('capabilitychecknotavailable','rating');
417             }
418             $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
419             $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
421             $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
422             $mform->setDefault('assessed', 0);
423             $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
425             $gradeoptions = array('isupdate' => $isupdate,
426                                   'currentgrade' => false,
427                                   'hasgrades' => false,
428                                   'canrescale' => $this->_features->canrescale,
429                                   'useratings' => $this->_features->rating);
430             if ($isupdate) {
431                 $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
432                                                      'itemmodule' => $this->_cm->modname,
433                                                      'iteminstance' => $this->_cm->instance,
434                                                      'itemnumber' => 0,
435                                                      'courseid' => $COURSE->id));
436                 if ($gradeitem) {
437                     $gradeoptions['currentgrade'] = $gradeitem->grademax;
438                     $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
439                     $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
440                     $gradeoptions['hasgrades'] = $gradeitem->has_grades();
441                 }
442             }
443             $mform->addElement('modgrade', 'scale', get_string('scale'), $gradeoptions);
444             $mform->disabledIf('scale', 'assessed', 'eq', 0);
445             $mform->addHelpButton('scale', 'modgrade', 'grades');
446             $mform->setDefault('scale', $CFG->gradepointdefault);
448             $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
449             $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
451             $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
452             $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
453             $mform->disabledIf('assesstimestart', 'ratingtime');
455             $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
456             $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
457             $mform->disabledIf('assesstimefinish', 'ratingtime');
458         }
460         //doing this here means splitting up the grade related settings on the lesson settings page
461         //$this->standard_grading_coursemodule_elements();
463         $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
465         $mform->addElement('modvisible', 'visible', get_string('visible'));
466         if (!empty($this->_cm)) {
467             $context = context_module::instance($this->_cm->id);
468             if (!has_capability('moodle/course:activityvisibility', $context)) {
469                 $mform->hardFreeze('visible');
470             }
471         }
473         if ($this->_features->idnumber) {
474             $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
475             $mform->setType('cmidnumber', PARAM_RAW);
476             $mform->addHelpButton('cmidnumber', 'idnumbermod');
477         }
479         if ($this->_features->groups) {
480             $options = array(NOGROUPS       => get_string('groupsnone'),
481                              SEPARATEGROUPS => get_string('groupsseparate'),
482                              VISIBLEGROUPS  => get_string('groupsvisible'));
483             $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
484             $mform->addHelpButton('groupmode', 'groupmode', 'group');
485         }
487         if ($this->_features->groupings) {
488             // Groupings selector - used to select grouping for groups in activity.
489             $options = array();
490             if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
491                 foreach ($groupings as $grouping) {
492                     $options[$grouping->id] = format_string($grouping->name);
493                 }
494             }
495             core_collator::asort($options);
496             $options = array(0 => get_string('none')) + $options;
497             $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
498             $mform->addHelpButton('groupingid', 'grouping', 'group');
499         }
501         if (!empty($CFG->enableavailability)) {
502             // Add special button to end of previous section if groups/groupings
503             // are enabled.
504             if ($this->_features->groups || $this->_features->groupings) {
505                 $mform->addElement('static', 'restrictgroupbutton', '',
506                         html_writer::tag('button', get_string('restrictbygroup', 'availability'),
507                         array('id' => 'restrictbygroup', 'disabled' => 'disabled')));
508             }
510             // Availability field. This is just a textarea; the user interface
511             // interaction is all implemented in JavaScript.
512             $mform->addElement('header', 'availabilityconditionsheader',
513                     get_string('restrictaccess', 'availability'));
514             // Note: This field cannot be named 'availability' because that
515             // conflicts with fields in existing modules (such as assign).
516             // So it uses a long name that will not conflict.
517             $mform->addElement('textarea', 'availabilityconditionsjson',
518                     get_string('accessrestrictions', 'availability'));
519             // The _cm variable may not be a proper cm_info, so get one from modinfo.
520             if ($this->_cm) {
521                 $modinfo = get_fast_modinfo($COURSE);
522                 $cm = $modinfo->get_cm($this->_cm->id);
523             } else {
524                 $cm = null;
525             }
526             \core_availability\frontend::include_all_javascript($COURSE, $cm);
527         }
529         // Conditional activities: completion tracking section
530         if(!isset($completion)) {
531             $completion = new completion_info($COURSE);
532         }
533         if ($completion->is_enabled()) {
534             $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
536             // Unlock button for if people have completed it (will
537             // be removed in definition_after_data if they haven't)
538             $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
539             $mform->registerNoSubmitButton('unlockcompletion');
540             $mform->addElement('hidden', 'completionunlocked', 0);
541             $mform->setType('completionunlocked', PARAM_INT);
543             $trackingdefault = COMPLETION_TRACKING_NONE;
544             // If system and activity default is on, set it.
545             if ($CFG->completiondefault && $this->_features->defaultcompletion) {
546                 $trackingdefault = COMPLETION_TRACKING_MANUAL;
547             }
549             $mform->addElement('select', 'completion', get_string('completion', 'completion'),
550                 array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
551                 COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
552             $mform->setDefault('completion', $trackingdefault);
553             $mform->addHelpButton('completion', 'completion', 'completion');
555             // Automatic completion once you view it
556             $gotcompletionoptions = false;
557             if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
558                 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
559                     get_string('completionview_desc', 'completion'));
560                 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
561                 $gotcompletionoptions = true;
562             }
564             // Automatic completion once it's graded
565             if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
566                 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
567                     get_string('completionusegrade_desc', 'completion'));
568                 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
569                 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
570                 $gotcompletionoptions = true;
572                 // If using the rating system, there is no grade unless ratings are enabled.
573                 if ($this->_features->rating) {
574                     $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
575                 }
576             }
578             // Automatic completion according to module-specific rules
579             $this->_customcompletionelements = $this->add_completion_rules();
580             foreach ($this->_customcompletionelements as $element) {
581                 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
582             }
584             $gotcompletionoptions = $gotcompletionoptions ||
585                 count($this->_customcompletionelements)>0;
587             // Automatic option only appears if possible
588             if ($gotcompletionoptions) {
589                 $mform->getElement('completion')->addOption(
590                     get_string('completion_automatic', 'completion'),
591                     COMPLETION_TRACKING_AUTOMATIC);
592             }
594             // Completion expected at particular date? (For progress tracking)
595             $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
596             $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
597             $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
598         }
600         // Populate module tags.
601         if (core_tag_tag::is_enabled('core', 'course_modules')) {
602             $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
603             $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
604             if ($this->_cm) {
605                 $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
606                 $mform->setDefault('tags', $tags);
607             }
608         }
610         $this->standard_hidden_coursemodule_elements();
611     }
613     /**
614      * Can be overridden to add custom completion rules if the module wishes
615      * them. If overriding this, you should also override completion_rule_enabled.
616      * <p>
617      * Just add elements to the form as needed and return the list of IDs. The
618      * system will call disabledIf and handle other behaviour for each returned
619      * ID.
620      * @return array Array of string IDs of added items, empty array if none
621      */
622     function add_completion_rules() {
623         return array();
624     }
626     /**
627      * Called during validation. Override to indicate, based on the data, whether
628      * a custom completion rule is enabled (selected).
629      *
630      * @param array $data Input data (not yet validated)
631      * @return bool True if one or more rules is enabled, false if none are;
632      *   default returns false
633      */
634     function completion_rule_enabled($data) {
635         return false;
636     }
638     function standard_hidden_coursemodule_elements(){
639         $mform =& $this->_form;
640         $mform->addElement('hidden', 'course', 0);
641         $mform->setType('course', PARAM_INT);
643         $mform->addElement('hidden', 'coursemodule', 0);
644         $mform->setType('coursemodule', PARAM_INT);
646         $mform->addElement('hidden', 'section', 0);
647         $mform->setType('section', PARAM_INT);
649         $mform->addElement('hidden', 'module', 0);
650         $mform->setType('module', PARAM_INT);
652         $mform->addElement('hidden', 'modulename', '');
653         $mform->setType('modulename', PARAM_PLUGIN);
655         $mform->addElement('hidden', 'instance', 0);
656         $mform->setType('instance', PARAM_INT);
658         $mform->addElement('hidden', 'add', 0);
659         $mform->setType('add', PARAM_ALPHA);
661         $mform->addElement('hidden', 'update', 0);
662         $mform->setType('update', PARAM_INT);
664         $mform->addElement('hidden', 'return', 0);
665         $mform->setType('return', PARAM_BOOL);
667         $mform->addElement('hidden', 'sr', 0);
668         $mform->setType('sr', PARAM_INT);
669     }
671     public function standard_grading_coursemodule_elements() {
672         global $COURSE, $CFG;
673         $mform =& $this->_form;
674         $isupdate = !empty($this->_cm);
675         $gradeoptions = array('isupdate' => $isupdate,
676                               'currentgrade' => false,
677                               'hasgrades' => false,
678                               'canrescale' => $this->_features->canrescale,
679                               'useratings' => $this->_features->rating);
681         if ($this->_features->hasgrades) {
683             if (!$this->_features->rating || $this->_features->gradecat) {
684                 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
685             }
687             //if supports grades and grades arent being handled via ratings
688             if (!$this->_features->rating) {
690                 if ($isupdate) {
691                     $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
692                                                          'itemmodule' => $this->_cm->modname,
693                                                          'iteminstance' => $this->_cm->instance,
694                                                          'itemnumber' => 0,
695                                                          'courseid' => $COURSE->id));
696                     if ($gradeitem) {
697                         $gradeoptions['currentgrade'] = $gradeitem->grademax;
698                         $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
699                         $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
700                         $gradeoptions['hasgrades'] = $gradeitem->has_grades();
701                     }
702                 }
703                 $mform->addElement('modgrade', 'grade', get_string('grade'), $gradeoptions);
704                 $mform->addHelpButton('grade', 'modgrade', 'grades');
705                 $mform->setDefault('grade', $CFG->gradepointdefault);
706             }
708             if ($this->_features->advancedgrading
709                     and !empty($this->current->_advancedgradingdata['methods'])
710                     and !empty($this->current->_advancedgradingdata['areas'])) {
712                 if (count($this->current->_advancedgradingdata['areas']) == 1) {
713                     // if there is just one gradable area (most cases), display just the selector
714                     // without its name to make UI simplier
715                     $areadata = reset($this->current->_advancedgradingdata['areas']);
716                     $areaname = key($this->current->_advancedgradingdata['areas']);
717                     $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
718                         get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
719                     $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
720                     if (!$this->_features->rating) {
721                         $mform->disabledIf('advancedgradingmethod_'.$areaname, 'grade[modgrade_type]', 'eq', 'none');
722                     }
724                 } else {
725                     // the module defines multiple gradable areas, display a selector
726                     // for each of them together with a name of the area
727                     $areasgroup = array();
728                     foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
729                         $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
730                             $areadata['title'], $this->current->_advancedgradingdata['methods']);
731                         $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
732                     }
733                     $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
734                         array(' ', '<br />'), false);
735                 }
736             }
738             if ($this->_features->gradecat) {
739                 $mform->addElement('select', 'gradecat',
740                         get_string('gradecategoryonmodform', 'grades'),
741                         grade_get_categories_menu($COURSE->id, $this->_outcomesused));
742                 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
743                 if (!$this->_features->rating) {
744                     $mform->disabledIf('gradecat', 'grade[modgrade_type]', 'eq', 'none');
745                 }
746             }
748             // Grade to pass.
749             $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
750             $mform->addHelpButton('gradepass', 'gradepass', 'grades');
751             $mform->setDefault('gradepass', '');
752             $mform->setType('gradepass', PARAM_RAW);
753             if (!$this->_features->rating) {
754                 $mform->disabledIf('gradepass', 'grade[modgrade_type]', 'eq', 'none');
755             } else {
756                 $mform->disabledIf('gradepass', 'assessed', 'eq', '0');
757             }
758         }
759     }
761     /**
762      * Add an editor for an activity's introduction field.
763      * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
764      * @param null $required Override system default for requiremodintro
765      * @param null $customlabel Override default label for editor
766      * @throws coding_exception
767      */
768     protected function add_intro_editor($required=null, $customlabel=null) {
769         $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
770         debugging($str, DEBUG_DEVELOPER);
772         $this->standard_intro_elements($customlabel);
773     }
776     /**
777      * Add an editor for an activity's introduction field.
778      *
779      * @param null $customlabel Override default label for editor
780      * @param array $attributes add custom attributes for the editor, it sets rows size to 10 (default) to text editor.
781      * @throws coding_exception
782      */
783     protected function standard_intro_elements($customlabel=null, $attributes = array()) {
784         global $CFG;
786         $required = $CFG->requiremodintro;
788         $mform = $this->_form;
789         $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
791         $attributes['rows'] = !empty($attributes['rows']) ? $attributes['rows'] : 10;
793         $mform->addElement('editor', 'introeditor', $label, $attributes, array('maxfiles' => EDITOR_UNLIMITED_FILES,
794             'noclean' => true, 'context' => $this->context, 'subdirs' => true));
795         $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
796         if ($required) {
797             $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
798         }
800         // If the 'show description' feature is enabled, this checkbox appears below the intro.
801         // We want to hide that when using the singleactivity course format because it is confusing.
802         if ($this->_features->showdescription  && $this->courseformat->has_view_page()) {
803             $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
804             $mform->addHelpButton('showdescription', 'showdescription');
805         }
806     }
808     /**
809      * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
810      *
811      * @param bool $cancel show cancel button
812      * @param string $submitlabel null means default, false means none, string is label text
813      * @param string $submit2label  null means default, false means none, string is label text
814      * @return void
815      */
816     function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
817         if (is_null($submitlabel)) {
818             $submitlabel = get_string('savechangesanddisplay');
819         }
821         if (is_null($submit2label)) {
822             $submit2label = get_string('savechangesandreturntocourse');
823         }
825         $mform = $this->_form;
827         // elements in a row need a group
828         $buttonarray = array();
830         // Label for the submit button to return to the course.
831         // Ignore this button in single activity format because it is confusing.
832         if ($submit2label !== false && $this->courseformat->has_view_page()) {
833             $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
834         }
836         if ($submitlabel !== false) {
837             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
838         }
840         if ($cancel) {
841             $buttonarray[] = &$mform->createElement('cancel');
842         }
844         $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
845         $mform->setType('buttonar', PARAM_RAW);
846         $mform->closeHeaderBefore('buttonar');
847     }
849     /**
850      * Get the list of admin settings for this module and apply any locked settings.
851      * This cannot happen in apply_admin_defaults because we do not the current values of the settings
852      * in that function because set_data has not been called yet.
853      *
854      * @return void
855      */
856     protected function apply_admin_locked_flags() {
857         global $OUTPUT;
859         if (!$this->applyadminlockedflags) {
860             return;
861         }
863         $settings = get_config($this->_modname);
864         $mform = $this->_form;
865         $lockedicon = html_writer::tag('span',
866                                        $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
867                                        array('class' => 'action-icon'));
868         $isupdate = !empty($this->_cm);
870         foreach ($settings as $name => $value) {
871             if (strpos('_', $name) !== false) {
872                 continue;
873             }
874             if ($mform->elementExists($name)) {
875                 $element = $mform->getElement($name);
876                 $lockedsetting = $name . '_locked';
877                 if (!empty($settings->$lockedsetting)) {
878                     // Always lock locked settings for new modules,
879                     // for updates, only lock them if the current value is the same as the default (or there is no current value).
880                     $value = $settings->$name;
881                     if ($isupdate && isset($this->current->$name)) {
882                         $value = $this->current->$name;
883                     }
884                     if ($value == $settings->$name) {
885                         $mform->setConstant($name, $settings->$name);
886                         $element->setLabel($element->getLabel() . $lockedicon);
887                         // Do not use hardfreeze because we need the hidden input to check dependencies.
888                         $element->freeze();
889                     }
890                 }
891             }
892         }
893     }
895     /**
896      * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
897      *
898      * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
899      *                         default date/time value should be relative to. If not passed, all
900      *                         date/time fields are set relative to the users current midnight.
901      * @return void
902      */
903     public function apply_admin_defaults($datetimeoffsets = array()) {
904         // This flag triggers the settings to be locked in apply_admin_locked_flags().
905         $this->applyadminlockedflags = true;
907         $settings = get_config($this->_modname);
908         $mform = $this->_form;
909         $usermidnight = usergetmidnight(time());
910         $isupdate = !empty($this->_cm);
912         foreach ($settings as $name => $value) {
913             if (strpos('_', $name) !== false) {
914                 continue;
915             }
916             if ($mform->elementExists($name)) {
917                 $element = $mform->getElement($name);
918                 if (!$isupdate) {
919                     if ($element->getType() == 'date_time_selector') {
920                         $enabledsetting = $name . '_enabled';
921                         if (empty($settings->$enabledsetting)) {
922                             $mform->setDefault($name, 0);
923                         } else {
924                             $relativetime = $usermidnight;
925                             if (isset($datetimeoffsets[$name])) {
926                                 $relativetime = $datetimeoffsets[$name];
927                             }
928                             $mform->setDefault($name, $relativetime + $settings->$name);
929                         }
930                     } else {
931                         $mform->setDefault($name, $settings->$name);
932                     }
933                 }
934                 $advancedsetting = $name . '_adv';
935                 if (!empty($settings->$advancedsetting)) {
936                     $mform->setAdvanced($name);
937                 }
938             }
939         }
940     }