2 require_once ($CFG->libdir
.'/formslib.php');
3 require_once($CFG->libdir
.'/completionlib.php');
4 require_once($CFG->libdir
.'/gradelib.php');
5 require_once($CFG->libdir
.'/plagiarismlib.php');
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
11 abstract class moodleform_mod
extends moodleform
{
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
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).
30 * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
45 * List of modform features
49 * @var array Custom completion-rule elements, if enabled
51 protected $_customcompletionelements;
53 * @var string name of module
56 /** current context, course or module depends if already exists*/
59 /** a flag indicating whether outcomes are being used*/
60 protected $_outcomesused;
63 * @var bool A flag used to indicate that this module should lock settings
64 * based on admin settings flags in definition_after_data.
66 protected $applyadminlockedflags = false;
68 /** @var object The course format of the current course. */
69 protected $courseformat;
71 public function __construct($current, $section, $cm, $course) {
74 $this->current
= $current;
75 $this->_instance
= $current->instance
;
76 $this->_section
= $section;
78 $this->_course
= $course;
80 $this->context
= context_module
::instance($this->_cm
->id
);
82 $this->context
= context_course
::instance($course->id
);
85 // Set the course format.
86 require_once($CFG->dirroot
. '/course/format/lib.php');
87 $this->courseformat
= course_get_format($course);
91 if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
92 debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
93 print_error('unknownmodulename');
95 $this->_modname
= $matches[1];
96 $this->init_features();
97 parent
::__construct('modedit.php');
101 * Old syntax of class constructor. Deprecated in PHP7.
103 * @deprecated since Moodle 3.1
105 public function moodleform_mod($current, $section, $cm, $course) {
106 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
107 self
::__construct($current, $section, $cm, $course);
111 * Get the current data for the form.
112 * @return stdClass|null
114 public function get_current() {
115 return $this->current
;
119 * Get the DB record for the current instance.
120 * @return stdClass|null
122 public function get_instance() {
123 return $this->_instance
;
127 * Get the course section number (relative).
130 public function get_section() {
131 return $this->_section
;
138 public function get_course() {
139 return $this->_course
;
143 * Get the course module object.
144 * @return stdClass|null
146 public function get_coursemodule() {
151 * Return the course context for new modules, or the module context for existing modules.
154 public function get_context() {
155 return $this->context
;
159 * Return the features this module supports.
162 public function get_features() {
163 return $this->_features
;
167 protected function init_features() {
170 $this->_features
= new stdClass();
171 $this->_features
->groups
= plugin_supports('mod', $this->_modname
, FEATURE_GROUPS
, true);
172 $this->_features
->groupings
= plugin_supports('mod', $this->_modname
, FEATURE_GROUPINGS
, false);
173 $this->_features
->outcomes
= (!empty($CFG->enableoutcomes
) and plugin_supports('mod', $this->_modname
, FEATURE_GRADE_OUTCOMES
, true));
174 $this->_features
->hasgrades
= plugin_supports('mod', $this->_modname
, FEATURE_GRADE_HAS_GRADE
, false);
175 $this->_features
->idnumber
= plugin_supports('mod', $this->_modname
, FEATURE_IDNUMBER
, true);
176 $this->_features
->introeditor
= plugin_supports('mod', $this->_modname
, FEATURE_MOD_INTRO
, true);
177 $this->_features
->defaultcompletion
= plugin_supports('mod', $this->_modname
, FEATURE_MODEDIT_DEFAULT_COMPLETION
, true);
178 $this->_features
->rating
= plugin_supports('mod', $this->_modname
, FEATURE_RATE
, false);
179 $this->_features
->showdescription
= plugin_supports('mod', $this->_modname
, FEATURE_SHOW_DESCRIPTION
, false);
180 $this->_features
->gradecat
= ($this->_features
->outcomes
or $this->_features
->hasgrades
);
181 $this->_features
->advancedgrading
= plugin_supports('mod', $this->_modname
, FEATURE_ADVANCED_GRADING
, false);
182 $this->_features
->canrescale
= (component_callback_exists('mod_' . $this->_modname
, 'rescale_activity_grades') !== false);
186 * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
187 * This method is also called in the bulk activity completion form.
189 * Only available on moodleform_mod.
191 * @param array $default_values passed by reference
193 function data_preprocessing(&$default_values){
194 if (empty($default_values['scale'])) {
195 $default_values['assessed'] = 0;
198 if (empty($default_values['assessed'])){
199 $default_values['ratingtime'] = 0;
201 $default_values['ratingtime']=
202 ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ?
1 : 0;
207 * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
209 function definition_after_data() {
210 global $CFG, $COURSE;
211 $mform =& $this->_form
;
213 if ($id = $mform->getElementValue('update')) {
214 $modulename = $mform->getElementValue('modulename');
215 $instance = $mform->getElementValue('instance');
217 if ($this->_features
->gradecat
) {
219 if (!empty($CFG->enableoutcomes
) and $this->_features
->outcomes
) {
220 $outcomes = grade_outcome
::fetch_all_available($COURSE->id
);
221 if (!empty($outcomes)) {
226 $hasgradeitems = false;
227 $items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id
));
228 //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
229 if (!empty($items)) {
230 foreach ($items as $item) {
231 if (!empty($item->outcomeid
)) {
232 $elname = 'outcome_'.$item->outcomeid
;
233 if ($mform->elementExists($elname)) {
234 $mform->hardFreeze($elname); // prevent removing of existing outcomes
237 $hasgradeitems = true;
241 foreach ($items as $item) {
242 if (is_bool($gradecat)) {
243 $gradecat = $item->categoryid
;
246 if ($gradecat != $item->categoryid
) {
254 if (!$hasgradeitems && $mform->elementExists('gradepass')) {
255 // Remove form element 'Grade to pass' since there are no grade items (when rating not selected).
256 $mform->removeElement('gradepass');
259 if ($gradecat === false) {
260 // items and outcomes in different categories - remove the option
261 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
262 if ($mform->elementExists('gradecat')) {
263 $mform->removeElement('gradecat');
264 if ($this->_features
->rating
&& !$mform->elementExists('gradepass')) {
265 //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
266 $mform->removeElement('modstandardgrade');
273 if ($COURSE->groupmodeforce
) {
274 if ($mform->elementExists('groupmode')) {
275 $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
279 // Don't disable/remove groupingid if it is currently set to something,
280 // otherwise you cannot turn it off at same time as turning off other
281 // option (MDL-30764)
282 if (empty($this->_cm
) ||
!$this->_cm
->groupingid
) {
283 if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce
)) {
284 $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS
);
286 } else if (!$mform->elementExists('groupmode')) {
287 // Groupings have no use without groupmode.
288 if ($mform->elementExists('groupingid')) {
289 $mform->removeElement('groupingid');
294 // Completion: If necessary, freeze fields
295 $completion = new completion_info($COURSE);
296 if ($completion->is_enabled()) {
297 // If anybody has completed the activity, these options will be 'locked'
298 $completedcount = empty($this->_cm
)
300 : $completion->count_user_data($this->_cm
);
303 if (!$completedcount) {
304 if ($mform->elementExists('unlockcompletion')) {
305 $mform->removeElement('unlockcompletion');
307 // Automatically set to unlocked (note: this is necessary
308 // in order to make it recalculate completion once the option
309 // is changed, maybe someone has completed it now)
310 $mform->getElement('completionunlocked')->setValue(1);
312 // Has the element been unlocked, either by the button being pressed
313 // in this request, or the field already being set from a previous one?
314 if ($mform->exportValue('unlockcompletion') ||
315 $mform->exportValue('completionunlocked')) {
316 // Yes, add in warning text and set the hidden variable
317 $mform->insertElementBefore(
318 $mform->createElement('static', 'completedunlocked',
319 get_string('completedunlocked', 'completion'),
320 get_string('completedunlockedtext', 'completion')),
322 $mform->removeElement('unlockcompletion');
323 $mform->getElement('completionunlocked')->setValue(1);
325 // No, add in the warning text with the count (now we know
326 // it) before the unlock button
327 $mform->insertElementBefore(
328 $mform->createElement('static', 'completedwarning',
329 get_string('completedwarning', 'completion'),
330 get_string('completedwarningtext', 'completion', $completedcount)),
337 $mform->freeze('completion');
338 if ($mform->elementExists('completionview')) {
339 $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
341 if ($mform->elementExists('completionusegrade')) {
342 $mform->freeze('completionusegrade');
344 $mform->freeze($this->_customcompletionelements
);
348 // Freeze admin defaults if required (and not different from default)
349 $this->apply_admin_locked_flags();
353 function validation($data, $files) {
354 global $COURSE, $DB, $CFG;
355 $errors = parent
::validation($data, $files);
357 $mform =& $this->_form
;
361 if ($mform->elementExists('name')) {
362 $name = trim($data['name']);
364 $errors['name'] = get_string('required');
368 $grade_item = grade_item
::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
369 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id
));
370 if ($data['coursemodule']) {
371 $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
376 if ($mform->elementExists('cmidnumber')) {
377 // verify the idnumber
378 if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id
, $grade_item, $cm)) {
379 $errors['cmidnumber'] = get_string('idnumbertaken');
383 // Ratings: Don't let them select an aggregate type without selecting a scale.
384 // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
385 // invalid. If ratings have been selected then the user must select either a scale or max points.
386 // This matches (horrible) logic in data_preprocessing.
387 if (isset($data['assessed']) && $data['assessed'] > 0 && empty($data['scale'])) {
388 $errors['assessed'] = get_string('scaleselectionrequired', 'rating');
391 // Check that the grade pass is a valid number.
392 $gradepassvalid = false;
393 if (isset($data['gradepass'])) {
394 if (unformat_float($data['gradepass'], true) === false) {
395 $errors['gradepass'] = get_string('err_numeric', 'form');
397 $gradepassvalid = true;
401 // Grade to pass: ensure that the grade to pass is valid for points and scales.
402 // If we are working with a scale, convert into a positive number for validation.
403 if ($gradepassvalid && isset($data['gradepass']) && (!empty($data['grade']) ||
!empty($data['scale']))) {
404 $scale = !empty($data['grade']) ?
$data['grade'] : $data['scale'];
406 $scalevalues = $DB->get_record('scale', array('id' => -$scale));
407 $grade = count(explode(',', $scalevalues->scale
));
411 if ($data['gradepass'] > $grade) {
412 $errors['gradepass'] = get_string('gradepassgreaterthangrade', 'grades', $grade);
416 // Completion: Don't let them choose automatic completion without turning
417 // on some conditions. Ignore this check when completion settings are
418 // locked, as the options are then disabled.
419 if (array_key_exists('completion', $data) &&
420 $data['completion'] == COMPLETION_TRACKING_AUTOMATIC
&&
421 !empty($data['completionunlocked'])) {
422 if (empty($data['completionview']) && empty($data['completionusegrade']) &&
423 !$this->completion_rule_enabled($data)) {
424 $errors['completion'] = get_string('badautocompletion', 'completion');
428 // Availability: Check availability field does not have errors.
429 if (!empty($CFG->enableavailability
)) {
430 \core_availability\frontend
::report_validation_errors($data, $errors);
433 $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
434 if (!empty($pluginerrors)) {
435 $errors = array_merge($errors, $pluginerrors);
442 * Extend the validation function from any other plugin.
444 * @param stdClass $data The form data.
445 * @return array $errors The list of errors keyed by element name.
447 protected function plugin_extend_coursemodule_validation($data) {
450 $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
451 foreach ($callbacks as $type => $plugins) {
452 foreach ($plugins as $plugin => $pluginfunction) {
453 // We have exposed all the important properties with public getters - the errors array should be pass by reference.
454 $pluginerrors = $pluginfunction($this, $data);
455 if (!empty($pluginerrors)) {
456 $errors = array_merge($errors, $pluginerrors);
464 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
465 * form definition (new entry form); this function is used to load in data where values
466 * already exist and data is being edited (edit entry form).
468 * @param mixed $default_values object or array of default values
470 function set_data($default_values) {
471 if (is_object($default_values)) {
472 $default_values = (array)$default_values;
475 $this->data_preprocessing($default_values);
476 parent
::set_data($default_values);
480 * Adds all the standard elements to a form to edit the settings for an activity module.
482 function standard_coursemodule_elements(){
483 global $COURSE, $CFG, $DB;
484 $mform =& $this->_form
;
486 $this->_outcomesused
= false;
487 if ($this->_features
->outcomes
) {
488 if ($outcomes = grade_outcome
::fetch_all_available($COURSE->id
)) {
489 $this->_outcomesused
= true;
490 $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
491 foreach($outcomes as $outcome) {
492 $mform->addElement('advcheckbox', 'outcome_'.$outcome->id
, $outcome->get_name());
498 if ($this->_features
->rating
) {
499 require_once($CFG->dirroot
.'/rating/lib.php');
500 $rm = new rating_manager();
502 $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
504 $permission=CAP_ALLOW
;
505 $rolenamestring = null;
507 if (!empty($this->_cm
)) {
509 $context = context_module
::instance($this->_cm
->id
);
511 $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm
->modname
.':rate'));
512 $rolenamestring = implode(', ', $rolenames);
514 $rolenamestring = get_string('capabilitychecknotavailable','rating');
516 $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
517 $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
519 $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
520 $mform->setDefault('assessed', 0);
521 $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
523 $gradeoptions = array('isupdate' => $isupdate,
524 'currentgrade' => false,
525 'hasgrades' => false,
526 'canrescale' => $this->_features
->canrescale
,
527 'useratings' => $this->_features
->rating
);
529 $gradeitem = grade_item
::fetch(array('itemtype' => 'mod',
530 'itemmodule' => $this->_cm
->modname
,
531 'iteminstance' => $this->_cm
->instance
,
533 'courseid' => $COURSE->id
));
535 $gradeoptions['currentgrade'] = $gradeitem->grademax
;
536 $gradeoptions['currentgradetype'] = $gradeitem->gradetype
;
537 $gradeoptions['currentscaleid'] = $gradeitem->scaleid
;
538 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
541 $mform->addElement('modgrade', 'scale', get_string('scale'), $gradeoptions);
542 $mform->disabledIf('scale', 'assessed', 'eq', 0);
543 $mform->addHelpButton('scale', 'modgrade', 'grades');
544 $mform->setDefault('scale', $CFG->gradepointdefault
);
546 $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
547 $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
549 $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
550 $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
551 $mform->disabledIf('assesstimestart', 'ratingtime');
553 $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
554 $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
555 $mform->disabledIf('assesstimefinish', 'ratingtime');
558 //doing this here means splitting up the grade related settings on the lesson settings page
559 //$this->standard_grading_coursemodule_elements();
561 $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
563 $section = get_fast_modinfo($COURSE)->get_section_info($this->_section
);
564 $allowstealth = !empty($CFG->allowstealth
) && $this->courseformat
->allow_stealth_module_visibility($this->_cm
, $section);
565 if ($allowstealth && $section->visible
) {
566 $modvisiblelabel = 'modvisiblewithstealth';
567 } else if ($section->visible
) {
568 $modvisiblelabel = 'modvisible';
570 $modvisiblelabel = 'modvisiblehiddensection';
572 $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
573 array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible
, 'cm' => $this->_cm
));
574 $mform->addHelpButton('visible', $modvisiblelabel);
575 if (!empty($this->_cm
)) {
576 $context = context_module
::instance($this->_cm
->id
);
577 if (!has_capability('moodle/course:activityvisibility', $context)) {
578 $mform->hardFreeze('visible');
582 if ($this->_features
->idnumber
) {
583 $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
584 $mform->setType('cmidnumber', PARAM_RAW
);
585 $mform->addHelpButton('cmidnumber', 'idnumbermod');
588 if ($this->_features
->groups
) {
589 $options = array(NOGROUPS
=> get_string('groupsnone'),
590 SEPARATEGROUPS
=> get_string('groupsseparate'),
591 VISIBLEGROUPS
=> get_string('groupsvisible'));
592 $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS
);
593 $mform->addHelpButton('groupmode', 'groupmode', 'group');
596 if ($this->_features
->groupings
) {
597 // Groupings selector - used to select grouping for groups in activity.
599 if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id
))) {
600 foreach ($groupings as $grouping) {
601 $options[$grouping->id
] = format_string($grouping->name
);
604 core_collator
::asort($options);
605 $options = array(0 => get_string('none')) +
$options;
606 $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
607 $mform->addHelpButton('groupingid', 'grouping', 'group');
610 if (!empty($CFG->enableavailability
)) {
611 // Add special button to end of previous section if groups/groupings
613 if ($this->_features
->groups ||
$this->_features
->groupings
) {
614 $mform->addElement('static', 'restrictgroupbutton', '',
615 html_writer
::tag('button', get_string('restrictbygroup', 'availability'),
616 array('id' => 'restrictbygroup', 'disabled' => 'disabled', 'class' => 'btn btn-secondary')));
619 // Availability field. This is just a textarea; the user interface
620 // interaction is all implemented in JavaScript.
621 $mform->addElement('header', 'availabilityconditionsheader',
622 get_string('restrictaccess', 'availability'));
623 // Note: This field cannot be named 'availability' because that
624 // conflicts with fields in existing modules (such as assign).
625 // So it uses a long name that will not conflict.
626 $mform->addElement('textarea', 'availabilityconditionsjson',
627 get_string('accessrestrictions', 'availability'));
628 // The _cm variable may not be a proper cm_info, so get one from modinfo.
630 $modinfo = get_fast_modinfo($COURSE);
631 $cm = $modinfo->get_cm($this->_cm
->id
);
635 \core_availability\frontend
::include_all_javascript($COURSE, $cm);
638 // Conditional activities: completion tracking section
639 if(!isset($completion)) {
640 $completion = new completion_info($COURSE);
642 if ($completion->is_enabled()) {
643 $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
644 // Unlock button for if people have completed it (will
645 // be removed in definition_after_data if they haven't)
646 $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
647 $mform->registerNoSubmitButton('unlockcompletion');
648 $mform->addElement('hidden', 'completionunlocked', 0);
649 $mform->setType('completionunlocked', PARAM_INT
);
651 $trackingdefault = COMPLETION_TRACKING_NONE
;
652 // If system and activity default is on, set it.
653 if ($CFG->completiondefault
&& $this->_features
->defaultcompletion
) {
654 $hasrules = plugin_supports('mod', $this->_modname
, FEATURE_COMPLETION_HAS_RULES
, true);
655 $tracksviews = plugin_supports('mod', $this->_modname
, FEATURE_COMPLETION_TRACKS_VIEWS
, true);
656 if ($hasrules ||
$tracksviews) {
657 $trackingdefault = COMPLETION_TRACKING_AUTOMATIC
;
659 $trackingdefault = COMPLETION_TRACKING_MANUAL
;
663 $mform->addElement('select', 'completion', get_string('completion', 'completion'),
664 array(COMPLETION_TRACKING_NONE
=>get_string('completion_none', 'completion'),
665 COMPLETION_TRACKING_MANUAL
=>get_string('completion_manual', 'completion')));
666 $mform->setDefault('completion', $trackingdefault);
667 $mform->addHelpButton('completion', 'completion', 'completion');
669 // Automatic completion once you view it
670 $gotcompletionoptions = false;
671 if (plugin_supports('mod', $this->_modname
, FEATURE_COMPLETION_TRACKS_VIEWS
, false)) {
672 $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
673 get_string('completionview_desc', 'completion'));
674 $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC
);
675 // Check by default if automatic completion tracking is set.
676 if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC
) {
677 $mform->setDefault('completionview', 1);
679 $gotcompletionoptions = true;
682 // Automatic completion once it's graded
683 if (plugin_supports('mod', $this->_modname
, FEATURE_GRADE_HAS_GRADE
, false)) {
684 $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
685 get_string('completionusegrade_desc', 'completion'));
686 $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC
);
687 $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
688 $gotcompletionoptions = true;
690 // If using the rating system, there is no grade unless ratings are enabled.
691 if ($this->_features
->rating
) {
692 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
696 // Automatic completion according to module-specific rules
697 $this->_customcompletionelements
= $this->add_completion_rules();
698 foreach ($this->_customcompletionelements
as $element) {
699 $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC
);
702 $gotcompletionoptions = $gotcompletionoptions ||
703 count($this->_customcompletionelements
)>0;
705 // Automatic option only appears if possible
706 if ($gotcompletionoptions) {
707 $mform->getElement('completion')->addOption(
708 get_string('completion_automatic', 'completion'),
709 COMPLETION_TRACKING_AUTOMATIC
);
712 // Completion expected at particular date? (For progress tracking)
713 $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
714 $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
715 $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE
);
718 // Populate module tags.
719 if (core_tag_tag
::is_enabled('core', 'course_modules')) {
720 $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
721 $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
723 $tags = core_tag_tag
::get_item_tags_array('core', 'course_modules', $this->_cm
->id
);
724 $mform->setDefault('tags', $tags);
728 $this->standard_hidden_coursemodule_elements();
730 $this->plugin_extend_coursemodule_standard_elements();
734 * Plugins can extend the coursemodule settings form.
736 protected function plugin_extend_coursemodule_standard_elements() {
737 $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
738 foreach ($callbacks as $type => $plugins) {
739 foreach ($plugins as $plugin => $pluginfunction) {
740 // We have exposed all the important properties with public getters - and the callback can manipulate the mform
742 $pluginfunction($this, $this->_form
);
748 * Can be overridden to add custom completion rules if the module wishes
749 * them. If overriding this, you should also override completion_rule_enabled.
751 * Just add elements to the form as needed and return the list of IDs. The
752 * system will call disabledIf and handle other behaviour for each returned
754 * @return array Array of string IDs of added items, empty array if none
756 function add_completion_rules() {
761 * Called during validation. Override to indicate, based on the data, whether
762 * a custom completion rule is enabled (selected).
764 * @param array $data Input data (not yet validated)
765 * @return bool True if one or more rules is enabled, false if none are;
766 * default returns false
768 function completion_rule_enabled($data) {
772 function standard_hidden_coursemodule_elements(){
773 $mform =& $this->_form
;
774 $mform->addElement('hidden', 'course', 0);
775 $mform->setType('course', PARAM_INT
);
777 $mform->addElement('hidden', 'coursemodule', 0);
778 $mform->setType('coursemodule', PARAM_INT
);
780 $mform->addElement('hidden', 'section', 0);
781 $mform->setType('section', PARAM_INT
);
783 $mform->addElement('hidden', 'module', 0);
784 $mform->setType('module', PARAM_INT
);
786 $mform->addElement('hidden', 'modulename', '');
787 $mform->setType('modulename', PARAM_PLUGIN
);
789 $mform->addElement('hidden', 'instance', 0);
790 $mform->setType('instance', PARAM_INT
);
792 $mform->addElement('hidden', 'add', 0);
793 $mform->setType('add', PARAM_ALPHA
);
795 $mform->addElement('hidden', 'update', 0);
796 $mform->setType('update', PARAM_INT
);
798 $mform->addElement('hidden', 'return', 0);
799 $mform->setType('return', PARAM_BOOL
);
801 $mform->addElement('hidden', 'sr', 0);
802 $mform->setType('sr', PARAM_INT
);
805 public function standard_grading_coursemodule_elements() {
806 global $COURSE, $CFG;
807 $mform =& $this->_form
;
808 $isupdate = !empty($this->_cm
);
809 $gradeoptions = array('isupdate' => $isupdate,
810 'currentgrade' => false,
811 'hasgrades' => false,
812 'canrescale' => $this->_features
->canrescale
,
813 'useratings' => $this->_features
->rating
);
815 if ($this->_features
->hasgrades
) {
817 if (!$this->_features
->rating ||
$this->_features
->gradecat
) {
818 $mform->addElement('header', 'modstandardgrade', get_string('grade'));
821 //if supports grades and grades arent being handled via ratings
822 if (!$this->_features
->rating
) {
825 $gradeitem = grade_item
::fetch(array('itemtype' => 'mod',
826 'itemmodule' => $this->_cm
->modname
,
827 'iteminstance' => $this->_cm
->instance
,
829 'courseid' => $COURSE->id
));
831 $gradeoptions['currentgrade'] = $gradeitem->grademax
;
832 $gradeoptions['currentgradetype'] = $gradeitem->gradetype
;
833 $gradeoptions['currentscaleid'] = $gradeitem->scaleid
;
834 $gradeoptions['hasgrades'] = $gradeitem->has_grades();
837 $mform->addElement('modgrade', 'grade', get_string('grade'), $gradeoptions);
838 $mform->addHelpButton('grade', 'modgrade', 'grades');
839 $mform->setDefault('grade', $CFG->gradepointdefault
);
842 if ($this->_features
->advancedgrading
843 and !empty($this->current
->_advancedgradingdata
['methods'])
844 and !empty($this->current
->_advancedgradingdata
['areas'])) {
846 if (count($this->current
->_advancedgradingdata
['areas']) == 1) {
847 // if there is just one gradable area (most cases), display just the selector
848 // without its name to make UI simplier
849 $areadata = reset($this->current
->_advancedgradingdata
['areas']);
850 $areaname = key($this->current
->_advancedgradingdata
['areas']);
851 $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
852 get_string('gradingmethod', 'core_grading'), $this->current
->_advancedgradingdata
['methods']);
853 $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
854 if (!$this->_features
->rating
) {
855 $mform->disabledIf('advancedgradingmethod_'.$areaname, 'grade[modgrade_type]', 'eq', 'none');
859 // the module defines multiple gradable areas, display a selector
860 // for each of them together with a name of the area
861 $areasgroup = array();
862 foreach ($this->current
->_advancedgradingdata
['areas'] as $areaname => $areadata) {
863 $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
864 $areadata['title'], $this->current
->_advancedgradingdata
['methods']);
865 $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
867 $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
868 array(' ', '<br />'), false);
872 if ($this->_features
->gradecat
) {
873 $mform->addElement('select', 'gradecat',
874 get_string('gradecategoryonmodform', 'grades'),
875 grade_get_categories_menu($COURSE->id
, $this->_outcomesused
));
876 $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
877 if (!$this->_features
->rating
) {
878 $mform->disabledIf('gradecat', 'grade[modgrade_type]', 'eq', 'none');
883 $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
884 $mform->addHelpButton('gradepass', 'gradepass', 'grades');
885 $mform->setDefault('gradepass', '');
886 $mform->setType('gradepass', PARAM_RAW
);
887 if (!$this->_features
->rating
) {
888 $mform->disabledIf('gradepass', 'grade[modgrade_type]', 'eq', 'none');
890 $mform->disabledIf('gradepass', 'assessed', 'eq', '0');
896 * Add an editor for an activity's introduction field.
897 * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
898 * @param null $required Override system default for requiremodintro
899 * @param null $customlabel Override default label for editor
900 * @throws coding_exception
902 protected function add_intro_editor($required=null, $customlabel=null) {
903 $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
904 debugging($str, DEBUG_DEVELOPER
);
906 $this->standard_intro_elements($customlabel);
911 * Add an editor for an activity's introduction field.
913 * @param null $customlabel Override default label for editor
914 * @throws coding_exception
916 protected function standard_intro_elements($customlabel=null) {
919 $required = $CFG->requiremodintro
;
921 $mform = $this->_form
;
922 $label = is_null($customlabel) ?
get_string('moduleintro') : $customlabel;
924 $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES
,
925 'noclean' => true, 'context' => $this->context
, 'subdirs' => true));
926 $mform->setType('introeditor', PARAM_RAW
); // no XSS prevention here, users must be trusted
928 $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
931 // If the 'show description' feature is enabled, this checkbox appears below the intro.
932 // We want to hide that when using the singleactivity course format because it is confusing.
933 if ($this->_features
->showdescription
&& $this->courseformat
->has_view_page()) {
934 $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
935 $mform->addHelpButton('showdescription', 'showdescription');
940 * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
942 * @param bool $cancel show cancel button
943 * @param string $submitlabel null means default, false means none, string is label text
944 * @param string $submit2label null means default, false means none, string is label text
947 function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
948 if (is_null($submitlabel)) {
949 $submitlabel = get_string('savechangesanddisplay');
952 if (is_null($submit2label)) {
953 $submit2label = get_string('savechangesandreturntocourse');
956 $mform = $this->_form
;
958 // elements in a row need a group
959 $buttonarray = array();
961 // Label for the submit button to return to the course.
962 // Ignore this button in single activity format because it is confusing.
963 if ($submit2label !== false && $this->courseformat
->has_view_page()) {
964 $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
967 if ($submitlabel !== false) {
968 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
972 $buttonarray[] = &$mform->createElement('cancel');
975 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
976 $mform->setType('buttonar', PARAM_RAW
);
977 $mform->closeHeaderBefore('buttonar');
981 * Get the list of admin settings for this module and apply any locked settings.
982 * This cannot happen in apply_admin_defaults because we do not the current values of the settings
983 * in that function because set_data has not been called yet.
987 protected function apply_admin_locked_flags() {
990 if (!$this->applyadminlockedflags
) {
994 $settings = get_config($this->_modname
);
995 $mform = $this->_form
;
996 $lockedicon = html_writer
::tag('span',
997 $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
998 array('class' => 'action-icon'));
999 $isupdate = !empty($this->_cm
);
1001 foreach ($settings as $name => $value) {
1002 if (strpos('_', $name) !== false) {
1005 if ($mform->elementExists($name)) {
1006 $element = $mform->getElement($name);
1007 $lockedsetting = $name . '_locked';
1008 if (!empty($settings->$lockedsetting)) {
1009 // Always lock locked settings for new modules,
1010 // for updates, only lock them if the current value is the same as the default (or there is no current value).
1011 $value = $settings->$name;
1012 if ($isupdate && isset($this->current
->$name)) {
1013 $value = $this->current
->$name;
1015 if ($value == $settings->$name) {
1016 $mform->setConstant($name, $settings->$name);
1017 $element->setLabel($element->getLabel() . $lockedicon);
1018 // Do not use hardfreeze because we need the hidden input to check dependencies.
1027 * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
1029 * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
1030 * default date/time value should be relative to. If not passed, all
1031 * date/time fields are set relative to the users current midnight.
1034 public function apply_admin_defaults($datetimeoffsets = array()) {
1035 // This flag triggers the settings to be locked in apply_admin_locked_flags().
1036 $this->applyadminlockedflags
= true;
1038 $settings = get_config($this->_modname
);
1039 $mform = $this->_form
;
1040 $usermidnight = usergetmidnight(time());
1041 $isupdate = !empty($this->_cm
);
1043 foreach ($settings as $name => $value) {
1044 if (strpos('_', $name) !== false) {
1047 if ($mform->elementExists($name)) {
1048 $element = $mform->getElement($name);
1050 if ($element->getType() == 'date_time_selector') {
1051 $enabledsetting = $name . '_enabled';
1052 if (empty($settings->$enabledsetting)) {
1053 $mform->setDefault($name, 0);
1055 $relativetime = $usermidnight;
1056 if (isset($datetimeoffsets[$name])) {
1057 $relativetime = $datetimeoffsets[$name];
1059 $mform->setDefault($name, $relativetime +
$settings->$name);
1062 $mform->setDefault($name, $settings->$name);
1065 $advancedsetting = $name . '_adv';
1066 if (!empty($settings->$advancedsetting)) {
1067 $mform->setAdvanced($name);
1074 * Allows modules to modify the data returned by form get_data().
1075 * This method is also called in the bulk activity completion form.
1077 * Only available on moodleform_mod.
1079 * @param stdClass $data passed by reference
1081 public function data_postprocessing($data) {
1085 * Return submitted data if properly submitted or returns NULL if validation fails or
1086 * if there is no submitted data.
1088 * Do not override this method, override data_postprocessing() instead.
1090 * @return object submitted data; NULL if not valid or not submitted or cancelled
1092 public function get_data() {
1093 $data = parent
::get_data();
1095 // Convert the grade pass value - we may be using a language which uses commas,
1096 // rather than decimal points, in numbers. These need to be converted so that
1097 // they can be added to the DB.
1098 if (isset($data->gradepass
)) {
1099 $data->gradepass
= unformat_float($data->gradepass
);
1102 $this->data_postprocessing($data);