PageRenderTime 72ms CodeModel.GetById 14ms app.highlight 49ms RepoModel.GetById 1ms app.codeStats 1ms

/course/moodleform_mod.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 994 lines | 686 code | 131 blank | 177 comment | 141 complexity | 2baa6569fd19a90fa328da6e82eaa7ee MD5 | raw file
  1<?php
  2require_once ($CFG->libdir.'/formslib.php');
  3require_once($CFG->libdir.'/completionlib.php');
  4
  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 */
  9abstract 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;
 48
 49    /** a flag indicating whether outcomes are being used*/
 50    protected $_outcomesused;
 51
 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;
 57
 58    /** @var object The course format of the current course. */
 59    protected $courseformat;
 60
 61    function moodleform_mod($current, $section, $cm, $course) {
 62        global $CFG;
 63
 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        }
 73
 74        // Set the course format.
 75        require_once($CFG->dirroot . '/course/format/lib.php');
 76        $this->courseformat = course_get_format($course);
 77
 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    }
 88
 89    protected function init_features() {
 90        global $CFG;
 91
 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);
103
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    }
107
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        }
117
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    }
125
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;
132
133        if ($id = $mform->getElementValue('update')) {
134            $modulename = $mform->getElementValue('modulename');
135            $instance   = $mform->getElementValue('instance');
136
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                }
145
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                    }
157
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                }
170
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        }
184
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        }
190
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);
197
198            } else if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
199                $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
200
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        }
208
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);
216
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, either by the button being pressed
228                // in this request, or the field already being set from a previous one?
229                if ($mform->exportValue('unlockcompletion') ||
230                        $mform->exportValue('completionunlocked')) {
231                    // Yes, add in warning text and set the hidden variable
232                    $mform->insertElementBefore(
233                        $mform->createElement('static', 'completedunlocked',
234                            get_string('completedunlocked', 'completion'),
235                            get_string('completedunlockedtext', 'completion')),
236                        'unlockcompletion');
237                    $mform->removeElement('unlockcompletion');
238                    $mform->getElement('completionunlocked')->setValue(1);
239                } else {
240                    // No, add in the warning text with the count (now we know
241                    // it) before the unlock button
242                    $mform->insertElementBefore(
243                        $mform->createElement('static', 'completedwarning',
244                            get_string('completedwarning', 'completion'),
245                            get_string('completedwarningtext', 'completion', $completedcount)),
246                        'unlockcompletion');
247                    $freeze = true;
248                }
249            }
250
251            if ($freeze) {
252                $mform->freeze('completion');
253                if ($mform->elementExists('completionview')) {
254                    $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
255                }
256                if ($mform->elementExists('completionusegrade')) {
257                    $mform->freeze('completionusegrade');
258                }
259                $mform->freeze($this->_customcompletionelements);
260            }
261        }
262
263        // Availability conditions
264        if (!empty($CFG->enableavailability) && $this->_cm) {
265            $ci = new condition_info($this->_cm);
266            $fullcm=$ci->get_full_course_module();
267
268            $num=0;
269            foreach($fullcm->conditionsgrade as $gradeitemid=>$minmax) {
270                $groupelements=$mform->getElement('conditiongradegroup['.$num.']')->getElements();
271                $groupelements[0]->setValue($gradeitemid);
272                $groupelements[2]->setValue(is_null($minmax->min) ? '' :
273                        format_float($minmax->min, 5, true, true));
274                $groupelements[4]->setValue(is_null($minmax->max) ? '' :
275                        format_float($minmax->max, 5, true, true));
276                $num++;
277            }
278
279            $num = 0;
280            foreach($fullcm->conditionsfield as $field => $details) {
281                $groupelements = $mform->getElement('conditionfieldgroup['.$num.']')->getElements();
282                $groupelements[0]->setValue($field);
283                $groupelements[1]->setValue(is_null($details->operator) ? '' : $details->operator);
284                $groupelements[2]->setValue(is_null($details->value) ? '' : $details->value);
285                $num++;
286            }
287
288            if ($completion->is_enabled()) {
289                $num=0;
290                foreach($fullcm->conditionscompletion as $othercmid=>$state) {
291                    $groupelements=$mform->getElement('conditioncompletiongroup['.$num.']')->getElements();
292                    $groupelements[0]->setValue($othercmid);
293                    $groupelements[1]->setValue($state);
294                    $num++;
295                }
296            }
297        }
298
299        // Freeze admin defaults if required (and not different from default)
300        $this->apply_admin_locked_flags();
301    }
302
303    // form verification
304    function validation($data, $files) {
305        global $COURSE, $DB;
306        $errors = parent::validation($data, $files);
307
308        $mform =& $this->_form;
309
310        $errors = array();
311
312        if ($mform->elementExists('name')) {
313            $name = trim($data['name']);
314            if ($name == '') {
315                $errors['name'] = get_string('required');
316            }
317        }
318
319        $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
320                     'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
321        if ($data['coursemodule']) {
322            $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
323        } else {
324            $cm = null;
325        }
326
327        if ($mform->elementExists('cmidnumber')) {
328            // verify the idnumber
329            if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
330                $errors['cmidnumber'] = get_string('idnumbertaken');
331            }
332        }
333
334        // Completion: Don't let them choose automatic completion without turning
335        // on some conditions. Ignore this check when completion settings are
336        // locked, as the options are then disabled.
337        if (array_key_exists('completion', $data) &&
338                $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
339                !empty($data['completionunlocked'])) {
340            if (empty($data['completionview']) && empty($data['completionusegrade']) &&
341                !$this->completion_rule_enabled($data)) {
342                $errors['completion'] = get_string('badautocompletion', 'completion');
343            }
344        }
345
346        // Conditions: Don't let them set dates which make no sense
347        if (array_key_exists('availablefrom', $data) &&
348            $data['availablefrom'] && $data['availableuntil'] &&
349            $data['availablefrom'] >= $data['availableuntil']) {
350            $errors['availablefrom'] = get_string('badavailabledates', 'condition');
351        }
352
353        // Conditions: Verify that the grade conditions are numbers, and make sense.
354        if (array_key_exists('conditiongradegroup', $data)) {
355            foreach ($data['conditiongradegroup'] as $i => $gradedata) {
356                if ($gradedata['conditiongrademin'] !== '' &&
357                        !is_numeric(unformat_float($gradedata['conditiongrademin']))) {
358                    $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
359                    continue;
360                }
361                if ($gradedata['conditiongrademax'] !== '' &&
362                        !is_numeric(unformat_float($gradedata['conditiongrademax']))) {
363                    $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
364                    continue;
365                }
366                if ($gradedata['conditiongrademin'] !== '' && $gradedata['conditiongrademax'] !== '' &&
367                        unformat_float($gradedata['conditiongrademax']) <= unformat_float($gradedata['conditiongrademin'])) {
368                    $errors["conditiongradegroup[{$i}]"] = get_string('badgradelimits', 'condition');
369                    continue;
370                }
371                if ($gradedata['conditiongrademin'] === '' && $gradedata['conditiongrademax'] === '' &&
372                        $gradedata['conditiongradeitemid']) {
373                    $errors["conditiongradegroup[{$i}]"] = get_string('gradeitembutnolimits', 'condition');
374                    continue;
375                }
376                if (($gradedata['conditiongrademin'] !== '' || $gradedata['conditiongrademax'] !== '') &&
377                        !$gradedata['conditiongradeitemid']) {
378                    $errors["conditiongradegroup[{$i}]"] = get_string('gradelimitsbutnoitem', 'condition');
379                    continue;
380                }
381            }
382        }
383
384        // Conditions: Verify that the user profile field has not been declared more than once
385        if (array_key_exists('conditionfieldgroup', $data)) {
386            // Array to store the existing fields
387            $arrcurrentfields = array();
388            // Error message displayed if any condition is declared more than once. We use lang string because
389            // this way we don't actually generate the string unless there is an error.
390            $stralreadydeclaredwarning = new lang_string('fielddeclaredmultipletimes', 'condition');
391            foreach ($data['conditionfieldgroup'] as $i => $fielddata) {
392                if ($fielddata['conditionfield'] == 0) { // Don't need to bother if none is selected
393                    continue;
394                }
395                if (in_array($fielddata['conditionfield'], $arrcurrentfields)) {
396                    $errors["conditionfieldgroup[{$i}]"] = $stralreadydeclaredwarning->out();
397                }
398                // Add the field to the array
399                $arrcurrentfields[] = $fielddata['conditionfield'];
400            }
401        }
402
403        return $errors;
404    }
405
406    /**
407     * Load in existing data as form defaults. Usually new entry defaults are stored directly in
408     * form definition (new entry form); this function is used to load in data where values
409     * already exist and data is being edited (edit entry form).
410     *
411     * @param mixed $default_values object or array of default values
412     */
413    function set_data($default_values) {
414        if (is_object($default_values)) {
415            $default_values = (array)$default_values;
416        }
417
418        $this->data_preprocessing($default_values);
419        parent::set_data($default_values);
420    }
421
422    /**
423     * Adds all the standard elements to a form to edit the settings for an activity module.
424     */
425    function standard_coursemodule_elements(){
426        global $COURSE, $CFG, $DB;
427        $mform =& $this->_form;
428
429        $this->_outcomesused = false;
430        if ($this->_features->outcomes) {
431            if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
432                $this->_outcomesused = true;
433                $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
434                foreach($outcomes as $outcome) {
435                    $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
436                }
437            }
438        }
439
440
441        if ($this->_features->rating) {
442            require_once($CFG->dirroot.'/rating/lib.php');
443            $rm = new rating_manager();
444
445            $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
446
447            $permission=CAP_ALLOW;
448            $rolenamestring = null;
449            if (!empty($this->_cm)) {
450                $context = context_module::instance($this->_cm->id);
451
452                $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
453                $rolenamestring = implode(', ', $rolenames);
454            } else {
455                $rolenamestring = get_string('capabilitychecknotavailable','rating');
456            }
457            $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
458            $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
459
460            $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
461            $mform->setDefault('assessed', 0);
462            $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
463
464            $mform->addElement('modgrade', 'scale', get_string('scale'), false);
465            $mform->disabledIf('scale', 'assessed', 'eq', 0);
466
467            $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
468            $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
469
470            $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
471            $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
472            $mform->disabledIf('assesstimestart', 'ratingtime');
473
474            $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
475            $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
476            $mform->disabledIf('assesstimefinish', 'ratingtime');
477        }
478
479        //doing this here means splitting up the grade related settings on the lesson settings page
480        //$this->standard_grading_coursemodule_elements();
481
482        $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
483
484        $mform->addElement('modvisible', 'visible', get_string('visible'));
485        if (!empty($this->_cm)) {
486            $context = context_module::instance($this->_cm->id);
487            if (!has_capability('moodle/course:activityvisibility', $context)) {
488                $mform->hardFreeze('visible');
489            }
490        }
491
492        if ($this->_features->idnumber) {
493            $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
494            $mform->setType('cmidnumber', PARAM_RAW);
495            $mform->addHelpButton('cmidnumber', 'idnumbermod');
496        }
497
498        if ($this->_features->groups) {
499            $options = array(NOGROUPS       => get_string('groupsnone'),
500                             SEPARATEGROUPS => get_string('groupsseparate'),
501                             VISIBLEGROUPS  => get_string('groupsvisible'));
502            $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
503            $mform->addHelpButton('groupmode', 'groupmode', 'group');
504        }
505
506        if ($this->_features->groupings or $this->_features->groupmembersonly) {
507            //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
508            $options = array();
509            if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
510                foreach ($groupings as $grouping) {
511                    $options[$grouping->id] = format_string($grouping->name);
512                }
513            }
514            core_collator::asort($options);
515            $options = array(0 => get_string('none')) + $options;
516            $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
517            $mform->addHelpButton('groupingid', 'grouping', 'group');
518        }
519
520        if ($this->_features->groupmembersonly) {
521            $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
522            $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
523        }
524
525        if (!empty($CFG->enableavailability)) {
526            // String used by conditions
527            $strnone = get_string('none','condition');
528            // Conditional availability
529
530            // Available from/to defaults to midnight because then the display
531            // will be nicer where it tells users when they can access it (it
532            // shows only the date and not time).
533            $date = usergetdate(time());
534            $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
535
536            // From/until controls
537            $mform->addElement('header', 'availabilityconditionsheader',
538                    get_string('availabilityconditions', 'condition'));
539            $mform->addElement('date_time_selector', 'availablefrom',
540                    get_string('availablefrom', 'condition'),
541                    array('optional' => true, 'defaulttime' => $midnight));
542            $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
543            $mform->addElement('date_time_selector', 'availableuntil',
544                    get_string('availableuntil', 'condition'),
545                    array('optional' => true, 'defaulttime' => $midnight));
546
547            // Conditions based on grades
548            $gradeoptions = array();
549            $items = grade_item::fetch_all(array('courseid'=>$COURSE->id));
550            $items = $items ? $items : array();
551            foreach($items as $id=>$item) {
552                // Do not include grades for current item
553                if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance
554                    && $this->_cm->modname == $item->itemmodule
555                    && $item->itemtype == 'mod') {
556                    continue;
557                }
558                $gradeoptions[$id] = $item->get_name();
559            }
560            asort($gradeoptions);
561            $gradeoptions = array(0 => $strnone) + $gradeoptions;
562
563            $grouparray = array();
564            $grouparray[] =& $mform->createElement('select','conditiongradeitemid','',$gradeoptions);
565            $grouparray[] =& $mform->createElement('static', '', '',' '.get_string('grade_atleast','condition').' ');
566            $grouparray[] =& $mform->createElement('text', 'conditiongrademin','',array('size'=>3));
567            $grouparray[] =& $mform->createElement('static', '', '','% '.get_string('grade_upto','condition').' ');
568            $grouparray[] =& $mform->createElement('text', 'conditiongrademax','',array('size'=>3));
569            $grouparray[] =& $mform->createElement('static', '', '','%');
570            $group = $mform->createElement('group','conditiongradegroup',
571                get_string('gradecondition', 'condition'),$grouparray);
572
573            // Get version with condition info and store it so we don't ask
574            // twice
575            if(!empty($this->_cm)) {
576                $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
577                $this->_cm = $ci->get_full_course_module();
578                $count = count($this->_cm->conditionsgrade)+1;
579                $fieldcount = count($this->_cm->conditionsfield) + 1;
580            } else {
581                $count = 1;
582                $fieldcount = 1;
583            }
584
585            $this->repeat_elements(array($group), $count, array(
586                'conditiongradegroup[conditiongrademin]' => array('type' => PARAM_RAW),
587                'conditiongradegroup[conditiongrademax]' => array('type' => PARAM_RAW)
588                ), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true);
589            $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
590
591            // Conditions based on user fields
592            $operators = condition_info::get_condition_user_field_operators();
593            $useroptions = condition_info::get_condition_user_fields(
594                    array('context' => $this->context));
595            asort($useroptions);
596
597            $useroptions = array(0 => $strnone) + $useroptions;
598            $grouparray = array();
599            $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions);
600            $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators);
601            $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue');
602            $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray);
603
604            $this->repeat_elements(array($group), $fieldcount, array(
605                'conditionfieldgroup[conditionfieldvalue]' => array('type' => PARAM_RAW)),
606                'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true);
607            $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition');
608
609            // Conditions based on completion
610            $completion = new completion_info($COURSE);
611            if ($completion->is_enabled()) {
612                $completionoptions = array();
613                $modinfo = get_fast_modinfo($COURSE);
614                foreach($modinfo->cms as $id=>$cm) {
615                    // Add each course-module if it:
616                    // (a) has completion turned on
617                    // (b) is not the same as current course-module
618                    if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
619                        $completionoptions[$id]=$cm->name;
620                    }
621                }
622                asort($completionoptions);
623                $completionoptions = array(0 => $strnone) + $completionoptions;
624
625                $completionvalues=array(
626                    COMPLETION_COMPLETE=>get_string('completion_complete','condition'),
627                    COMPLETION_INCOMPLETE=>get_string('completion_incomplete','condition'),
628                    COMPLETION_COMPLETE_PASS=>get_string('completion_pass','condition'),
629                    COMPLETION_COMPLETE_FAIL=>get_string('completion_fail','condition'));
630
631                $grouparray = array();
632                $grouparray[] =& $mform->createElement('select','conditionsourcecmid','',$completionoptions);
633                $grouparray[] =& $mform->createElement('select','conditionrequiredcompletion','',$completionvalues);
634                $group = $mform->createElement('group','conditioncompletiongroup',
635                    get_string('completioncondition', 'condition'),$grouparray);
636
637                $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion)+1;
638                $this->repeat_elements(array($group),$count,array(),
639                    'conditioncompletionrepeats','conditioncompletionadds',2,
640                    get_string('addcompletions','condition'),true);
641                $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
642            }
643
644            // Do we display availability info to students?
645            $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'),
646                    array(CONDITION_STUDENTVIEW_SHOW=>get_string('showavailability_show', 'condition'),
647                    CONDITION_STUDENTVIEW_HIDE=>get_string('showavailability_hide', 'condition')));
648            $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
649        }
650
651        // Conditional activities: completion tracking section
652        if(!isset($completion)) {
653            $completion = new completion_info($COURSE);
654        }
655        if ($completion->is_enabled()) {
656            $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
657
658            // Unlock button for if people have completed it (will
659            // be removed in definition_after_data if they haven't)
660            $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
661            $mform->registerNoSubmitButton('unlockcompletion');
662            $mform->addElement('hidden', 'completionunlocked', 0);
663            $mform->setType('completionunlocked', PARAM_INT);
664
665            $trackingdefault = COMPLETION_TRACKING_NONE;
666            // If system and activity default is on, set it.
667            if ($CFG->completiondefault && $this->_features->defaultcompletion) {
668                $trackingdefault = COMPLETION_TRACKING_MANUAL;
669            }
670
671            $mform->addElement('select', 'completion', get_string('completion', 'completion'),
672                array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
673                COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
674            $mform->setDefault('completion', $trackingdefault);
675            $mform->addHelpButton('completion', 'completion', 'completion');
676
677            // Automatic completion once you view it
678            $gotcompletionoptions = false;
679            if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
680                $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
681                    get_string('completionview_desc', 'completion'));
682                $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
683                $gotcompletionoptions = true;
684            }
685
686            // Automatic completion once it's graded
687            if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
688                $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
689                    get_string('completionusegrade_desc', 'completion'));
690                $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
691                $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
692                $gotcompletionoptions = true;
693
694                // If using the rating system, there is no grade unless ratings are enabled.
695                if ($this->_features->rating) {
696                    $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
697                }
698            }
699
700            // Automatic completion according to module-specific rules
701            $this->_customcompletionelements = $this->add_completion_rules();
702            foreach ($this->_customcompletionelements as $element) {
703                $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
704            }
705
706            $gotcompletionoptions = $gotcompletionoptions ||
707                count($this->_customcompletionelements)>0;
708
709            // Automatic option only appears if possible
710            if ($gotcompletionoptions) {
711                $mform->getElement('completion')->addOption(
712                    get_string('completion_automatic', 'completion'),
713                    COMPLETION_TRACKING_AUTOMATIC);
714            }
715
716            // Completion expected at particular date? (For progress tracking)
717            $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
718            $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
719            $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
720        }
721
722        $this->standard_hidden_coursemodule_elements();
723    }
724
725    /**
726     * Can be overridden to add custom completion rules if the module wishes
727     * them. If overriding this, you should also override completion_rule_enabled.
728     * <p>
729     * Just add elements to the form as needed and return the list of IDs. The
730     * system will call disabledIf and handle other behaviour for each returned
731     * ID.
732     * @return array Array of string IDs of added items, empty array if none
733     */
734    function add_completion_rules() {
735        return array();
736    }
737
738    /**
739     * Called during validation. Override to indicate, based on the data, whether
740     * a custom completion rule is enabled (selected).
741     *
742     * @param array $data Input data (not yet validated)
743     * @return bool True if one or more rules is enabled, false if none are;
744     *   default returns false
745     */
746    function completion_rule_enabled($data) {
747        return false;
748    }
749
750    function standard_hidden_coursemodule_elements(){
751        $mform =& $this->_form;
752        $mform->addElement('hidden', 'course', 0);
753        $mform->setType('course', PARAM_INT);
754
755        $mform->addElement('hidden', 'coursemodule', 0);
756        $mform->setType('coursemodule', PARAM_INT);
757
758        $mform->addElement('hidden', 'section', 0);
759        $mform->setType('section', PARAM_INT);
760
761        $mform->addElement('hidden', 'module', 0);
762        $mform->setType('module', PARAM_INT);
763
764        $mform->addElement('hidden', 'modulename', '');
765        $mform->setType('modulename', PARAM_PLUGIN);
766
767        $mform->addElement('hidden', 'instance', 0);
768        $mform->setType('instance', PARAM_INT);
769
770        $mform->addElement('hidden', 'add', 0);
771        $mform->setType('add', PARAM_ALPHA);
772
773        $mform->addElement('hidden', 'update', 0);
774        $mform->setType('update', PARAM_INT);
775
776        $mform->addElement('hidden', 'return', 0);
777        $mform->setType('return', PARAM_BOOL);
778
779        $mform->addElement('hidden', 'sr', 0);
780        $mform->setType('sr', PARAM_INT);
781    }
782
783    public function standard_grading_coursemodule_elements() {
784        global $COURSE, $CFG;
785        $mform =& $this->_form;
786
787        if ($this->_features->hasgrades) {
788
789            if (!$this->_features->rating || $this->_features->gradecat) {
790                $mform->addElement('header', 'modstandardgrade', get_string('grade'));
791            }
792
793            //if supports grades and grades arent being handled via ratings
794            if (!$this->_features->rating) {
795                $mform->addElement('modgrade', 'grade', get_string('grade'));
796                $mform->setDefault('grade', 100);
797            }
798
799            if ($this->_features->advancedgrading
800                    and !empty($this->current->_advancedgradingdata['methods'])
801                    and !empty($this->current->_advancedgradingdata['areas'])) {
802
803                if (count($this->current->_advancedgradingdata['areas']) == 1) {
804                    // if there is just one gradable area (most cases), display just the selector
805                    // without its name to make UI simplier
806                    $areadata = reset($this->current->_advancedgradingdata['areas']);
807                    $areaname = key($this->current->_advancedgradingdata['areas']);
808                    $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
809                        get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
810                    $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
811
812                } else {
813                    // the module defines multiple gradable areas, display a selector
814                    // for each of them together with a name of the area
815                    $areasgroup = array();
816                    foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
817                        $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
818                            $areadata['title'], $this->current->_advancedgradingdata['methods']);
819                        $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
820                    }
821                    $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
822                        array(' ', '<br />'), false);
823                }
824            }
825
826            if ($this->_features->gradecat) {
827                $mform->addElement('select', 'gradecat',
828                        get_string('gradecategoryonmodform', 'grades'),
829                        grade_get_categories_menu($COURSE->id, $this->_outcomesused));
830                $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
831            }
832        }
833    }
834
835    function add_intro_editor($required=false, $customlabel=null) {
836        if (!$this->_features->introeditor) {
837            // intro editor not supported in this module
838            return;
839        }
840
841        $mform = $this->_form;
842        $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
843
844        $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
845            'noclean' => true, 'context' => $this->context, 'subdirs' => true));
846        $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
847        if ($required) {
848            $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
849        }
850
851        // If the 'show description' feature is enabled, this checkbox appears below the intro.
852        // We want to hide that when using the singleactivity course format because it is confusing.
853        if ($this->_features->showdescription  && $this->courseformat->has_view_page()) {
854            $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
855            $mform->addHelpButton('showdescription', 'showdescription');
856        }
857    }
858
859    /**
860     * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
861     *
862     * @param bool $cancel show cancel button
863     * @param string $submitlabel null means default, false means none, string is label text
864     * @param string $submit2label  null means default, false means none, string is label text
865     * @return void
866     */
867    function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
868        if (is_null($submitlabel)) {
869            $submitlabel = get_string('savechangesanddisplay');
870        }
871
872        if (is_null($submit2label)) {
873            $submit2label = get_string('savechangesandreturntocourse');
874        }
875
876        $mform = $this->_form;
877
878        // elements in a row need a group
879        $buttonarray = array();
880
881        // Label for the submit button to return to the course.
882        // Ignore this button in single activity format because it is confusing.
883        if ($submit2label !== false && $this->courseformat->has_view_page()) {
884            $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
885        }
886
887        if ($submitlabel !== false) {
888            $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
889        }
890
891        if ($cancel) {
892            $buttonarray[] = &$mform->createElement('cancel');
893        }
894
895        $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
896        $mform->setType('buttonar', PARAM_RAW);
897        $mform->closeHeaderBefore('buttonar');
898    }
899
900    /**
901     * Get the list of admin settings for this module and apply any locked settings.
902     * This cannot happen in apply_admin_defaults because we do not the current values of the settings
903     * in that function because set_data has not been called yet.
904     *
905     * @return void
906     */
907    protected function apply_admin_locked_flags() {
908        global $OUTPUT;
909
910        if (!$this->applyadminlockedflags) {
911            return;
912        }
913
914        $settings = get_config($this->_modname);
915        $mform = $this->_form;
916        $lockedicon = html_writer::tag('span',
917                                       $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
918                                       array('class' => 'action-icon'));
919        $isupdate = !empty($this->_cm);
920
921        foreach ($settings as $name => $value) {
922            if (strpos('_', $name) !== false) {
923                continue;
924            }
925            if ($mform->elementExists($name)) {
926                $element = $mform->getElement($name);
927                $lockedsetting = $name . '_locked';
928                if (!empty($settings->$lockedsetting)) {
929                    // Always lock locked settings for new modules,
930                    // for updates, only lock them if the current value is the same as the default (or there is no current value).
931                    $value = $settings->$name;
932                    if ($isupdate && isset($this->current->$name)) {
933                        $value = $this->current->$name;
934                    }
935                    if ($value == $settings->$name) {
936                        $mform->setConstant($name, $settings->$name);
937                        $element->setLabel($element->getLabel() . $lockedicon);
938                        // Do not use hardfreeze because we need the hidden input to check dependencies.
939                        $element->freeze();
940                    }
941                }
942            }
943        }
944    }
945
946    /**
947     * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
948     *
949     * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
950     *                         default date/time value should be relative to. If not passed, all
951     *                         date/time fields are set relative to the users current midnight.
952     * @return void
953     */
954    public function apply_admin_defaults($datetimeoffsets = array()) {
955        // This flag triggers the settings to be locked in apply_admin_locked_flags().
956        $this->applyadminlockedflags = true;
957
958        $settings = get_config($this->_modname);
959        $mform = $this->_form;
960        $usermidnight = usergetmidnight(time());
961        $isupdate = !empty($this->_cm);
962
963        foreach ($settings as $name => $value) {
964            if (strpos('_', $name) !== false) {
965                continue;
966            }
967            if ($mform->elementExists($name)) {
968                $element = $mform->getElement($name);
969                if (!$isupdate) {
970                    if ($element->getType() == 'date_time_selector') {
971                        $enabledsetting = $name . '_enabled';
972                        if (empty($settings->$enabledsetting)) {
973                            $mform->setDefault($name, 0);
974                        } else {
975                            $relativetime = $usermidnight;
976                            if (isset($datetimeoffsets[$name])) {
977                                $relativetime = $datetimeoffsets[$name];
978                            }
979                            $mform->setDefault($name, $relativetime + $settings->$name);
980                        }
981                    } else {
982                        $mform->setDefault($name, $settings->$name);
983                    }
984                }
985                $advancedsetting = $name . '_adv';
986                if (!empty($settings->$advancedsetting)) {
987                    $mform->setAdvanced($name);
988                }
989            }
990        }
991    }
992}
993
994