1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
19 *
20 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
21 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
22 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
23 * and validation.
24 *
25 * See examples of use of this library in course/edit.php and course/edit_form.php
26 *
27 * A few notes :
28 *      form definition is used for both printing of form and processing and should be the same
29 *              for both or you may lose some submitted data which won't be let through.
30 *      you should be using setType for every form element except select, radio or checkbox
31 *              elements, these elements clean themselves.
32 *
33 * @package   core_form
34 * @copyright 2006 Jamie Pratt <me@jamiep.org>
35 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 */
37
38defined('MOODLE_INTERNAL') || die();
39
40/** setup.php includes our hacked pear libs first */
41require_once 'HTML/QuickForm.php';
42require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43require_once 'HTML/QuickForm/Renderer/Tableless.php';
44require_once 'HTML/QuickForm/Rule.php';
45
46require_once $CFG->libdir.'/filelib.php';
47
48/**
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
50 */
51define('EDITOR_UNLIMITED_FILES', -1);
52
53/**
54 * Callback called when PEAR throws an error
55 *
56 * @param PEAR_Error $error
57 */
58function pear_handle_error($error){
59    echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
60    echo '<br /> <strong>Backtrace </strong>:';
61    print_object($error->backtrace);
62}
63
64if ($CFG->debugdeveloper) {
65    //TODO: this is a wrong place to init PEAR!
66    $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
67    $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
68}
69
70/**
71 * Initalize javascript for date type form element
72 *
73 * @staticvar bool $done make sure it gets initalize once.
74 * @global moodle_page $PAGE
75 */
76function form_init_date_js() {
77    global $PAGE;
78    static $done = false;
79    if (!$done) {
80        $done = true;
81        $calendar = \core_calendar\type_factory::get_calendar_instance();
82        if ($calendar->get_name() !== 'gregorian') {
83            // The YUI2 calendar only supports the gregorian calendar type.
84            return;
85        }
86        $module   = 'moodle-form-dateselector';
87        $function = 'M.form.dateselector.init_date_selectors';
88        $defaulttimezone = date_default_timezone_get();
89
90        $config = array(array(
91            'firstdayofweek'    => $calendar->get_starting_weekday(),
92            'mon'               => date_format_string(strtotime("Monday"), '%a', $defaulttimezone),
93            'tue'               => date_format_string(strtotime("Tuesday"), '%a', $defaulttimezone),
94            'wed'               => date_format_string(strtotime("Wednesday"), '%a', $defaulttimezone),
95            'thu'               => date_format_string(strtotime("Thursday"), '%a', $defaulttimezone),
96            'fri'               => date_format_string(strtotime("Friday"), '%a', $defaulttimezone),
97            'sat'               => date_format_string(strtotime("Saturday"), '%a', $defaulttimezone),
98            'sun'               => date_format_string(strtotime("Sunday"), '%a', $defaulttimezone),
99            'january'           => date_format_string(strtotime("January 1"), '%B', $defaulttimezone),
100            'february'          => date_format_string(strtotime("February 1"), '%B', $defaulttimezone),
101            'march'             => date_format_string(strtotime("March 1"), '%B', $defaulttimezone),
102            'april'             => date_format_string(strtotime("April 1"), '%B', $defaulttimezone),
103            'may'               => date_format_string(strtotime("May 1"), '%B', $defaulttimezone),
104            'june'              => date_format_string(strtotime("June 1"), '%B', $defaulttimezone),
105            'july'              => date_format_string(strtotime("July 1"), '%B', $defaulttimezone),
106            'august'            => date_format_string(strtotime("August 1"), '%B', $defaulttimezone),
107            'september'         => date_format_string(strtotime("September 1"), '%B', $defaulttimezone),
108            'october'           => date_format_string(strtotime("October 1"), '%B', $defaulttimezone),
109            'november'          => date_format_string(strtotime("November 1"), '%B', $defaulttimezone),
110            'december'          => date_format_string(strtotime("December 1"), '%B', $defaulttimezone)
111        ));
112        $PAGE->requires->yui_module($module, $function, $config);
113    }
114}
115
116/**
117 * Wrapper that separates quickforms syntax from moodle code
118 *
119 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
120 * use this class you should write a class definition which extends this class or a more specific
121 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
122 *
123 * You will write your own definition() method which performs the form set up.
124 *
125 * @package   core_form
126 * @copyright 2006 Jamie Pratt <me@jamiep.org>
127 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
128 * @todo      MDL-19380 rethink the file scanning
129 */
130abstract class moodleform {
131    /** @var string name of the form */
132    protected $_formname;       // form name
133
134    /** @var MoodleQuickForm quickform object definition */
135    protected $_form;
136
137    /** @var array globals workaround */
138    protected $_customdata;
139
140    /** @var array submitted form data when using mforms with ajax */
141    protected $_ajaxformdata;
142
143    /** @var object definition_after_data executed flag */
144    protected $_definition_finalized = false;
145
146    /** @var bool|null stores the validation result of this form or null if not yet validated */
147    protected $_validated = null;
148
149    /**
150     * The constructor function calls the abstract function definition() and it will then
151     * process and clean and attempt to validate incoming data.
152     *
153     * It will call your custom validate method to validate data and will also check any rules
154     * you have specified in definition using addRule
155     *
156     * The name of the form (id attribute of the form) is automatically generated depending on
157     * the name you gave the class extending moodleform. You should call your class something
158     * like
159     *
160     * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
161     *              current url. If a moodle_url object then outputs params as hidden variables.
162     * @param mixed $customdata if your form defintion method needs access to data such as $course
163     *              $cm, etc. to construct the form definition then pass it in this array. You can
164     *              use globals for somethings.
165     * @param string $method if you set this to anything other than 'post' then _GET and _POST will
166     *               be merged and used as incoming data to the form.
167     * @param string $target target frame for form submission. You will rarely use this. Don't use
168     *               it if you don't need to as the target attribute is deprecated in xhtml strict.
169     * @param mixed $attributes you can pass a string of html attributes here or an array.
170     *               Special attribute 'data-random-ids' will randomise generated elements ids. This
171     *               is necessary when there are several forms on the same page.
172     *               Special attribute 'data-double-submit-protection' set to 'off' will turn off
173     *               double-submit protection JavaScript - this may be necessary if your form sends
174     *               downloadable files in response to a submit button, and can't call
175     *               \core_form\util::form_download_complete();
176     * @param bool $editable
177     * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
178     */
179    public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true,
180                                $ajaxformdata=null) {
181        global $CFG, $FULLME;
182        // no standard mform in moodle should allow autocomplete with the exception of user signup
183        if (empty($attributes)) {
184            $attributes = array('autocomplete'=>'off');
185        } else if (is_array($attributes)) {
186            $attributes['autocomplete'] = 'off';
187        } else {
188            if (strpos($attributes, 'autocomplete') === false) {
189                $attributes .= ' autocomplete="off" ';
190            }
191        }
192
193
194        if (empty($action)){
195            // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
196            $action = strip_querystring($FULLME);
197            if (!empty($CFG->sslproxy)) {
198                // return only https links when using SSL proxy
199                $action = preg_replace('/^http:/', 'https:', $action, 1);
200            }
201            //TODO: use following instead of FULLME - see MDL-33015
202            //$action = strip_querystring(qualified_me());
203        }
204        // Assign custom data first, so that get_form_identifier can use it.
205        $this->_customdata = $customdata;
206        $this->_formname = $this->get_form_identifier();
207        $this->_ajaxformdata = $ajaxformdata;
208
209        $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes, $ajaxformdata);
210        if (!$editable){
211            $this->_form->hardFreeze();
212        }
213
214        $this->definition();
215
216        $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
217        $this->_form->setType('sesskey', PARAM_RAW);
218        $this->_form->setDefault('sesskey', sesskey());
219        $this->_form->addElement('hidden', '_qf__'.$this->_formname, null);   // form submission marker
220        $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
221        $this->_form->setDefault('_qf__'.$this->_formname, 1);
222        $this->_form->_setDefaultRuleMessages();
223
224        // Hook to inject logic after the definition was provided.
225        $this->after_definition();
226
227        // we have to know all input types before processing submission ;-)
228        $this->_process_submission($method);
229    }
230
231    /**
232     * Old syntax of class constructor. Deprecated in PHP7.
233     *
234     * @deprecated since Moodle 3.1
235     */
236    public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
237        debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
238        self::__construct($action, $customdata, $method, $target, $attributes, $editable);
239    }
240
241    /**
242     * It should returns unique identifier for the form.
243     * Currently it will return class name, but in case two same forms have to be
244     * rendered on same page then override function to get unique form identifier.
245     * e.g This is used on multiple self enrollments page.
246     *
247     * @return string form identifier.
248     */
249    protected function get_form_identifier() {
250        $class = get_class($this);
251
252        return preg_replace('/[^a-z0-9_]/i', '_', $class);
253    }
254
255    /**
256     * To autofocus on first form element or first element with error.
257     *
258     * @param string $name if this is set then the focus is forced to a field with this name
259     * @return string javascript to select form element with first error or
260     *                first element if no errors. Use this as a parameter
261     *                when calling print_header
262     */
263    function focus($name=NULL) {
264        $form =& $this->_form;
265        $elkeys = array_keys($form->_elementIndex);
266        $error = false;
267        if (isset($form->_errors) &&  0 != count($form->_errors)){
268            $errorkeys = array_keys($form->_errors);
269            $elkeys = array_intersect($elkeys, $errorkeys);
270            $error = true;
271        }
272
273        if ($error or empty($name)) {
274            $names = array();
275            while (empty($names) and !empty($elkeys)) {
276                $el = array_shift($elkeys);
277                $names = $form->_getElNamesRecursive($el);
278            }
279            if (!empty($names)) {
280                $name = array_shift($names);
281            }
282        }
283
284        $focus = '';
285        if (!empty($name)) {
286            $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
287        }
288
289        return $focus;
290     }
291
292    /**
293     * Internal method. Alters submitted data to be suitable for quickforms processing.
294     * Must be called when the form is fully set up.
295     *
296     * @param string $method name of the method which alters submitted data
297     */
298    function _process_submission($method) {
299        $submission = array();
300        if (!empty($this->_ajaxformdata)) {
301            $submission = $this->_ajaxformdata;
302        } else if ($method == 'post') {
303            if (!empty($_POST)) {
304                $submission = $_POST;
305            }
306        } else {
307            $submission = $_GET;
308            merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
309        }
310
311        // following trick is needed to enable proper sesskey checks when using GET forms
312        // the _qf__.$this->_formname serves as a marker that form was actually submitted
313        if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
314            if (!confirm_sesskey()) {
315                print_error('invalidsesskey');
316            }
317            $files = $_FILES;
318        } else {
319            $submission = array();
320            $files = array();
321        }
322        $this->detectMissingSetType();
323
324        $this->_form->updateSubmission($submission, $files);
325    }
326
327    /**
328     * Internal method - should not be used anywhere.
329     * @deprecated since 2.6
330     * @return array $_POST.
331     */
332    protected function _get_post_params() {
333        return $_POST;
334    }
335
336    /**
337     * Internal method. Validates all old-style deprecated uploaded files.
338     * The new way is to upload files via repository api.
339     *
340     * @param array $files list of files to be validated
341     * @return bool|array Success or an array of errors
342     */
343    function _validate_files(&$files) {
344        global $CFG, $COURSE;
345
346        $files = array();
347
348        if (empty($_FILES)) {
349            // we do not need to do any checks because no files were submitted
350            // note: server side rules do not work for files - use custom verification in validate() instead
351            return true;
352        }
353
354        $errors = array();
355        $filenames = array();
356
357        // now check that we really want each file
358        foreach ($_FILES as $elname=>$file) {
359            $required = $this->_form->isElementRequired($elname);
360
361            if ($file['error'] == 4 and $file['size'] == 0) {
362                if ($required) {
363                    $errors[$elname] = get_string('required');
364                }
365                unset($_FILES[$elname]);
366                continue;
367            }
368
369            if (!empty($file['error'])) {
370                $errors[$elname] = file_get_upload_error($file['error']);
371                unset($_FILES[$elname]);
372                continue;
373            }
374
375            if (!is_uploaded_file($file['tmp_name'])) {
376                // TODO: improve error message
377                $errors[$elname] = get_string('error');
378                unset($_FILES[$elname]);
379                continue;
380            }
381
382            if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
383                // hmm, this file was not requested
384                unset($_FILES[$elname]);
385                continue;
386            }
387
388            // NOTE: the viruses are scanned in file picker, no need to deal with them here.
389
390            $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
391            if ($filename === '') {
392                // TODO: improve error message - wrong chars
393                $errors[$elname] = get_string('error');
394                unset($_FILES[$elname]);
395                continue;
396            }
397            if (in_array($filename, $filenames)) {
398                // TODO: improve error message - duplicate name
399                $errors[$elname] = get_string('error');
400                unset($_FILES[$elname]);
401                continue;
402            }
403            $filenames[] = $filename;
404            $_FILES[$elname]['name'] = $filename;
405
406            $files[$elname] = $_FILES[$elname]['tmp_name'];
407        }
408
409        // return errors if found
410        if (count($errors) == 0){
411            return true;
412
413        } else {
414            $files = array();
415            return $errors;
416        }
417    }
418
419    /**
420     * Internal method. Validates filepicker and filemanager files if they are
421     * set as required fields. Also, sets the error message if encountered one.
422     *
423     * @return bool|array with errors
424     */
425    protected function validate_draft_files() {
426        global $USER;
427        $mform =& $this->_form;
428
429        $errors = array();
430        //Go through all the required elements and make sure you hit filepicker or
431        //filemanager element.
432        foreach ($mform->_rules as $elementname => $rules) {
433            $elementtype = $mform->getElementType($elementname);
434            //If element is of type filepicker then do validation
435            if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
436                //Check if rule defined is required rule
437                foreach ($rules as $rule) {
438                    if ($rule['type'] == 'required') {
439                        $draftid = (int)$mform->getSubmitValue($elementname);
440                        $fs = get_file_storage();
441                        $context = context_user::instance($USER->id);
442                        if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
443                            $errors[$elementname] = $rule['message'];
444                        }
445                    }
446                }
447            }
448        }
449        // Check all the filemanager elements to make sure they do not have too many
450        // files in them.
451        foreach ($mform->_elements as $element) {
452            if ($element->_type == 'filemanager') {
453                $maxfiles = $element->getMaxfiles();
454                if ($maxfiles > 0) {
455                    $draftid = (int)$element->getValue();
456                    $fs = get_file_storage();
457                    $context = context_user::instance($USER->id);
458                    $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
459                    if (count($files) > $maxfiles) {
460                        $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
461                    }
462                }
463            }
464        }
465        if (empty($errors)) {
466            return true;
467        } else {
468            return $errors;
469        }
470    }
471
472    /**
473     * Load in existing data as form defaults. Usually new entry defaults are stored directly in
474     * form definition (new entry form); this function is used to load in data where values
475     * already exist and data is being edited (edit entry form).
476     *
477     * note: $slashed param removed
478     *
479     * @param stdClass|array $default_values object or array of default values
480     */
481    function set_data($default_values) {
482        if (is_object($default_values)) {
483            $default_values = (array)$default_values;
484        }
485        $this->_form->setDefaults($default_values);
486    }
487
488    /**
489     * Check that form was submitted. Does not check validity of submitted data.
490     *
491     * @return bool true if form properly submitted
492     */
493    function is_submitted() {
494        return $this->_form->isSubmitted();
495    }
496
497    /**
498     * Checks if button pressed is not for submitting the form
499     *
500     * @staticvar bool $nosubmit keeps track of no submit button
501     * @return bool
502     */
503    function no_submit_button_pressed(){
504        static $nosubmit = null; // one check is enough
505        if (!is_null($nosubmit)){
506            return $nosubmit;
507        }
508        $mform =& $this->_form;
509        $nosubmit = false;
510        if (!$this->is_submitted()){
511            return false;
512        }
513        foreach ($mform->_noSubmitButtons as $nosubmitbutton){
514            if ($this->optional_param($nosubmitbutton, 0, PARAM_RAW)) {
515                $nosubmit = true;
516                break;
517            }
518        }
519        return $nosubmit;
520    }
521
522    /**
523     * Returns an element of multi-dimensional array given the list of keys
524     *
525     * Example:
526     * $array['a']['b']['c'] = 13;
527     * $v = $this->get_array_value_by_keys($array, ['a', 'b', 'c']);
528     *
529     * Will result it $v==13
530     *
531     * @param array $array
532     * @param array $keys
533     * @return mixed returns null if keys not present
534     */
535    protected function get_array_value_by_keys(array $array, array $keys) {
536        $value = $array;
537        foreach ($keys as $key) {
538            if (array_key_exists($key, $value)) {
539                $value = $value[$key];
540            } else {
541                return null;
542            }
543        }
544        return $value;
545    }
546
547    /**
548     * Checks if a parameter was passed in the previous form submission
549     *
550     * @param string $name the name of the page parameter we want, for example 'id' or 'element[sub][13]'
551     * @param mixed  $default the default value to return if nothing is found
552     * @param string $type expected type of parameter
553     * @return mixed
554     */
555    public function optional_param($name, $default, $type) {
556        $nameparsed = [];
557        // Convert element name into a sequence of keys, for example 'element[sub][13]' -> ['element', 'sub', '13'].
558        parse_str($name . '=1', $nameparsed);
559        $keys = [];
560        while (is_array($nameparsed)) {
561            $key = key($nameparsed);
562            $keys[] = $key;
563            $nameparsed = $nameparsed[$key];
564        }
565
566        // Search for the element first in $this->_ajaxformdata, then in $_POST and then in $_GET.
567        if (($value = $this->get_array_value_by_keys($this->_ajaxformdata ?? [], $keys)) !== null ||
568            ($value = $this->get_array_value_by_keys($_POST, $keys)) !== null ||
569            ($value = $this->get_array_value_by_keys($_GET, $keys)) !== null) {
570            return $type == PARAM_RAW ? $value : clean_param($value, $type);
571        }
572
573        return $default;
574    }
575
576    /**
577     * Check that form data is valid.
578     * You should almost always use this, rather than {@link validate_defined_fields}
579     *
580     * @return bool true if form data valid
581     */
582    function is_validated() {
583        //finalize the form definition before any processing
584        if (!$this->_definition_finalized) {
585            $this->_definition_finalized = true;
586            $this->definition_after_data();
587        }
588
589        return $this->validate_defined_fields();
590    }
591
592    /**
593     * Validate the form.
594     *
595     * You almost always want to call {@link is_validated} instead of this
596     * because it calls {@link definition_after_data} first, before validating the form,
597     * which is what you want in 99% of cases.
598     *
599     * This is provided as a separate function for those special cases where
600     * you want the form validated before definition_after_data is called
601     * for example, to selectively add new elements depending on a no_submit_button press,
602     * but only when the form is valid when the no_submit_button is pressed,
603     *
604     * @param bool $validateonnosubmit optional, defaults to false.  The default behaviour
605     *             is NOT to validate the form when a no submit button has been pressed.
606     *             pass true here to override this behaviour
607     *
608     * @return bool true if form data valid
609     */
610    function validate_defined_fields($validateonnosubmit=false) {
611        $mform =& $this->_form;
612        if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
613            return false;
614        } elseif ($this->_validated === null) {
615            $internal_val = $mform->validate();
616
617            $files = array();
618            $file_val = $this->_validate_files($files);
619            //check draft files for validation and flag them if required files
620            //are not in draft area.
621            $draftfilevalue = $this->validate_draft_files();
622
623            if ($file_val !== true && $draftfilevalue !== true) {
624                $file_val = array_merge($file_val, $draftfilevalue);
625            } else if ($draftfilevalue !== true) {
626                $file_val = $draftfilevalue;
627            } //default is file_val, so no need to assign.
628
629            if ($file_val !== true) {
630                if (!empty($file_val)) {
631                    foreach ($file_val as $element=>$msg) {
632                        $mform->setElementError($element, $msg);
633                    }
634                }
635                $file_val = false;
636            }
637
638            // Give the elements a chance to perform an implicit validation.
639            $element_val = true;
640            foreach ($mform->_elements as $element) {
641                if (method_exists($element, 'validateSubmitValue')) {
642                    $value = $mform->getSubmitValue($element->getName());
643                    $result = $element->validateSubmitValue($value);
644                    if (!empty($result) && is_string($result)) {
645                        $element_val = false;
646                        $mform->setElementError($element->getName(), $result);
647                    }
648                }
649            }
650
651            // Let the form instance validate the submitted values.
652            $data = $mform->exportValues();
653            $moodle_val = $this->validation($data, $files);
654            if ((is_array($moodle_val) && count($moodle_val)!==0)) {
655                // non-empty array means errors
656                foreach ($moodle_val as $element=>$msg) {
657                    $mform->setElementError($element, $msg);
658                }
659                $moodle_val = false;
660
661            } else {
662                // anything else means validation ok
663                $moodle_val = true;
664            }
665
666            $this->_validated = ($internal_val and $element_val and $moodle_val and $file_val);
667        }
668        return $this->_validated;
669    }
670
671    /**
672     * Return true if a cancel button has been pressed resulting in the form being submitted.
673     *
674     * @return bool true if a cancel button has been pressed
675     */
676    function is_cancelled(){
677        $mform =& $this->_form;
678        if ($mform->isSubmitted()){
679            foreach ($mform->_cancelButtons as $cancelbutton){
680                if ($this->optional_param($cancelbutton, 0, PARAM_RAW)) {
681                    return true;
682                }
683            }
684        }
685        return false;
686    }
687
688    /**
689     * Return submitted data if properly submitted or returns NULL if validation fails or
690     * if there is no submitted data.
691     *
692     * note: $slashed param removed
693     *
694     * @return object submitted data; NULL if not valid or not submitted or cancelled
695     */
696    function get_data() {
697        $mform =& $this->_form;
698
699        if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
700            $data = $mform->exportValues();
701            unset($data['sesskey']); // we do not need to return sesskey
702            unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
703            if (empty($data)) {
704                return NULL;
705            } else {
706                return (object)$data;
707            }
708        } else {
709            return NULL;
710        }
711    }
712
713    /**
714     * Return submitted data without validation or NULL if there is no submitted data.
715     * note: $slashed param removed
716     *
717     * @return object submitted data; NULL if not submitted
718     */
719    function get_submitted_data() {
720        $mform =& $this->_form;
721
722        if ($this->is_submitted()) {
723            $data = $mform->exportValues();
724            unset($data['sesskey']); // we do not need to return sesskey
725            unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
726            if (empty($data)) {
727                return NULL;
728            } else {
729                return (object)$data;
730            }
731        } else {
732            return NULL;
733        }
734    }
735
736    /**
737     * Save verified uploaded files into directory. Upload process can be customised from definition()
738     *
739     * @deprecated since Moodle 2.0
740     * @todo MDL-31294 remove this api
741     * @see moodleform::save_stored_file()
742     * @see moodleform::save_file()
743     * @param string $destination path where file should be stored
744     * @return bool Always false
745     */
746    function save_files($destination) {
747        debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
748        return false;
749    }
750
751    /**
752     * Returns name of uploaded file.
753     *
754     * @param string $elname first element if null
755     * @return string|bool false in case of failure, string if ok
756     */
757    function get_new_filename($elname=null) {
758        global $USER;
759
760        if (!$this->is_submitted() or !$this->is_validated()) {
761            return false;
762        }
763
764        if (is_null($elname)) {
765            if (empty($_FILES)) {
766                return false;
767            }
768            reset($_FILES);
769            $elname = key($_FILES);
770        }
771
772        if (empty($elname)) {
773            return false;
774        }
775
776        $element = $this->_form->getElement($elname);
777
778        if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
779            $values = $this->_form->exportValues($elname);
780            if (empty($values[$elname])) {
781                return false;
782            }
783            $draftid = $values[$elname];
784            $fs = get_file_storage();
785            $context = context_user::instance($USER->id);
786            if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
787                return false;
788            }
789            $file = reset($files);
790            return $file->get_filename();
791        }
792
793        if (!isset($_FILES[$elname])) {
794            return false;
795        }
796
797        return $_FILES[$elname]['name'];
798    }
799
800    /**
801     * Save file to standard filesystem
802     *
803     * @param string $elname name of element
804     * @param string $pathname full path name of file
805     * @param bool $override override file if exists
806     * @return bool success
807     */
808    function save_file($elname, $pathname, $override=false) {
809        global $USER;
810
811        if (!$this->is_submitted() or !$this->is_validated()) {
812            return false;
813        }
814        if (file_exists($pathname)) {
815            if ($override) {
816                if (!@unlink($pathname)) {
817                    return false;
818                }
819            } else {
820                return false;
821            }
822        }
823
824        $element = $this->_form->getElement($elname);
825
826        if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
827            $values = $this->_form->exportValues($elname);
828            if (empty($values[$elname])) {
829                return false;
830            }
831            $draftid = $values[$elname];
832            $fs = get_file_storage();
833            $context = context_user::instance($USER->id);
834            if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
835                return false;
836            }
837            $file = reset($files);
838
839            return $file->copy_content_to($pathname);
840
841        } else if (isset($_FILES[$elname])) {
842            return copy($_FILES[$elname]['tmp_name'], $pathname);
843        }
844
845        return false;
846    }
847
848    /**
849     * Returns a temporary file, do not forget to delete after not needed any more.
850     *
851     * @param string $elname name of the elmenet
852     * @return string|bool either string or false
853     */
854    function save_temp_file($elname) {
855        if (!$this->get_new_filename($elname)) {
856            return false;
857        }
858        if (!$dir = make_temp_directory('forms')) {
859            return false;
860        }
861        if (!$tempfile = tempnam($dir, 'tempup_')) {
862            return false;
863        }
864        if (!$this->save_file($elname, $tempfile, true)) {
865            // something went wrong
866            @unlink($tempfile);
867            return false;
868        }
869
870        return $tempfile;
871    }
872
873    /**
874     * Get draft files of a form element
875     * This is a protected method which will be used only inside moodleforms
876     *
877     * @param string $elname name of element
878     * @return array|bool|null
879     */
880    protected function get_draft_files($elname) {
881        global $USER;
882
883        if (!$this->is_submitted()) {
884            return false;
885        }
886
887        $element = $this->_form->getElement($elname);
888
889        if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
890            $values = $this->_form->exportValues($elname);
891            if (empty($values[$elname])) {
892                return false;
893            }
894            $draftid = $values[$elname];
895            $fs = get_file_storage();
896            $context = context_user::instance($USER->id);
897            if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
898                return null;
899            }
900            return $files;
901        }
902        return null;
903    }
904
905    /**
906     * Save file to local filesystem pool
907     *
908     * @param string $elname name of element
909     * @param int $newcontextid id of context
910     * @param string $newcomponent name of the component
911     * @param string $newfilearea name of file area
912     * @param int $newitemid item id
913     * @param string $newfilepath path of file where it get stored
914     * @param string $newfilename use specified filename, if not specified name of uploaded file used
915     * @param bool $overwrite overwrite file if exists
916     * @param int $newuserid new userid if required
917     * @return mixed stored_file object or false if error; may throw exception if duplicate found
918     */
919    function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
920                              $newfilename=null, $overwrite=false, $newuserid=null) {
921        global $USER;
922
923        if (!$this->is_submitted() or !$this->is_validated()) {
924            return false;
925        }
926
927        if (empty($newuserid)) {
928            $newuserid = $USER->id;
929        }
930
931        $element = $this->_form->getElement($elname);
932        $fs = get_file_storage();
933
934        if ($element instanceof MoodleQuickForm_filepicker) {
935            $values = $this->_form->exportValues($elname);
936            if (empty($values[$elname])) {
937                return false;
938            }
939            $draftid = $values[$elname];
940            $context = context_user::instance($USER->id);
941            if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
942                return false;
943            }
944            $file = reset($files);
945            if (is_null($newfilename)) {
946                $newfilename = $file->get_filename();
947            }
948
949            if ($overwrite) {
950                if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
951                    if (!$oldfile->delete()) {
952                        return false;
953                    }
954                }
955            }
956
957            $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
958                                 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
959            return $fs->create_file_from_storedfile($file_record, $file);
960
961        } else if (isset($_FILES[$elname])) {
962            $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
963
964            if ($overwrite) {
965                if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
966                    if (!$oldfile->delete()) {
967                        return false;
968                    }
969                }
970            }
971
972            $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
973                                 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
974            return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
975        }
976
977        return false;
978    }
979
980    /**
981     * Get content of uploaded file.
982     *
983     * @param string $elname name of file upload element
984     * @return string|bool false in case of failure, string if ok
985     */
986    function get_file_content($elname) {
987        global $USER;
988
989        if (!$this->is_submitted() or !$this->is_validated()) {
990            return false;
991        }
992
993        $element = $this->_form->getElement($elname);
994
995        if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
996            $values = $this->_form->exportValues($elname);
997            if (empty($values[$elname])) {
998                return false;
999            }
1000            $draftid = $values[$elname];
1001            $fs = get_file_storage();
1002            $context = context_user::instance($USER->id);
1003            if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
1004                return false;
1005            }
1006            $file = reset($files);
1007
1008            return $file->get_content();
1009
1010        } else if (isset($_FILES[$elname])) {
1011            return file_get_contents($_FILES[$elname]['tmp_name']);
1012        }
1013
1014        return false;
1015    }
1016
1017    /**
1018     * Print html form.
1019     */
1020    function display() {
1021        //finalize the form definition if not yet done
1022        if (!$this->_definition_finalized) {
1023            $this->_definition_finalized = true;
1024            $this->definition_after_data();
1025        }
1026
1027        $this->_form->display();
1028    }
1029
1030    /**
1031     * Renders the html form (same as display, but returns the result).
1032     *
1033     * Note that you can only output this rendered result once per page, as
1034     * it contains IDs which must be unique.
1035     *
1036     * @return string HTML code for the form
1037     */
1038    public function render() {
1039        ob_start();
1040        $this->display();
1041        $out = ob_get_contents();
1042        ob_end_clean();
1043        return $out;
1044    }
1045
1046    /**
1047     * Form definition. Abstract method - always override!
1048     */
1049    protected abstract function definition();
1050
1051    /**
1052     * After definition hook.
1053     *
1054     * This is useful for intermediate classes to inject logic after the definition was
1055     * provided without requiring developers to call the parent {{@link self::definition()}}
1056     * as it's not obvious by design. The 'intermediate' class is 'MyClass extends
1057     * IntermediateClass extends moodleform'.
1058     *
1059     * Classes overriding this method should always call the parent. We may not add
1060     * anything specifically in this instance of the method, but intermediate classes
1061     * are likely to do so, and so it is a good practice to always call the parent.
1062     *
1063     * @return void
1064     */
1065    protected function after_definition() {
1066    }
1067
1068    /**
1069     * Dummy stub method - override if you need to setup the form depending on current
1070     * values. This method is called after definition(), data submission and set_data().
1071     * All form setup that is dependent on form values should go in here.
1072     */
1073    function definition_after_data(){
1074    }
1075
1076    /**
1077     * Dummy stub method - override if you needed to perform some extra validation.
1078     * If there are errors return array of errors ("fieldname"=>"error message"),
1079     * otherwise true if ok.
1080     *
1081     * Server side rules do not work for uploaded files, implement serverside rules here if needed.
1082     *
1083     * @param array $data array of ("fieldname"=>value) of submitted data
1084     * @param array $files array of uploaded files "element_name"=>tmp_file_path
1085     * @return array of "element_name"=>"error_description" if there are errors,
1086     *         or an empty array if everything is OK (true allowed for backwards compatibility too).
1087     */
1088    function validation($data, $files) {
1089        return array();
1090    }
1091
1092    /**
1093     * Helper used by {@link repeat_elements()}.
1094     *
1095     * @param int $i the index of this element.
1096     * @param HTML_QuickForm_element $elementclone
1097     * @param array $namecloned array of names
1098     */
1099    function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1100        $name = $elementclone->getName();
1101        $namecloned[] = $name;
1102
1103        if (!empty($name)) {
1104            $elementclone->setName($name."[$i]");
1105        }
1106
1107        if (is_a($elementclone, 'HTML_QuickForm_header')) {
1108            $value = $elementclone->_text;
1109            $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1110
1111        } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1112            $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1113
1114        } else {
1115            $value=$elementclone->getLabel();
1116            $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1117        }
1118    }
1119
1120    /**
1121     * Method to add a repeating group of elements to a form.
1122     *
1123     * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1124     * @param int $repeats no of times to repeat elements initially
1125     * @param array $options a nested array. The first array key is the element name.
1126     *    the second array key is the type of option to set, and depend on that option,
1127     *    the value takes different forms.
1128     *         'default'    - default value to set. Can include '{no}' which is replaced by the repeat number.
1129     *         'type'       - PARAM_* type.
1130     *         'helpbutton' - array containing the helpbutton params.
1131     *         'disabledif' - array containing the disabledIf() arguments after the element name.
1132     *         'rule'       - array containing the addRule arguments after the element name.
1133     *         'expanded'   - whether this section of the form should be expanded by default. (Name be a header element.)
1134     *         'advanced'   - whether this element is hidden by 'Show more ...'.
1135     * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1136     * @param string $addfieldsname name for button to add more fields
1137     * @param int $addfieldsno how many fields to add at a time
1138     * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1139     * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1140     * @param string $deletebuttonname if specified, treats the no-submit button with this name as a "delete element" button
1141     *         in each of the elements
1142     * @return int no of repeats of element in this page
1143     */
1144    public function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1145                                    $addfieldsname, $addfieldsno = 5, $addstring = null, $addbuttoninside = false,
1146                                    $deletebuttonname = '') {
1147        if ($addstring === null) {
1148            $addstring = get_string('addfields', 'form', $addfieldsno);
1149        } else {
1150            $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1151        }
1152        $repeats = $this->optional_param($repeathiddenname, $repeats, PARAM_INT);
1153        $addfields = $this->optional_param($addfieldsname, '', PARAM_TEXT);
1154        $oldrepeats = $repeats;
1155        if (!empty($addfields)){
1156            $repeats += $addfieldsno;
1157        }
1158        $mform =& $this->_form;
1159        $mform->registerNoSubmitButton($addfieldsname);
1160        $mform->addElement('hidden', $repeathiddenname, $repeats);
1161        $mform->setType($repeathiddenname, PARAM_INT);
1162        //value not to be overridden by submitted value
1163        $mform->setConstants(array($repeathiddenname=>$repeats));
1164        $namecloned = array();
1165        $no = 1;
1166        for ($i = 0; $i < $repeats; $i++) {
1167            if ($deletebuttonname) {
1168                $mform->registerNoSubmitButton($deletebuttonname . "[$i]");
1169                $isdeleted = $this->optional_param($deletebuttonname . "[$i]", false, PARAM_RAW) ||
1170                    $this->optional_param($deletebuttonname . "-hidden[$i]", false, PARAM_RAW);
1171                if ($isdeleted) {
1172                    $mform->addElement('hidden', $deletebuttonname . "-hidden[$i]", 1);
1173                    $mform->setType($deletebuttonname . "-hidden[$i]", PARAM_INT);
1174                    continue;
1175                }
1176            }
1177            foreach ($elementobjs as $elementobj){
1178                $elementclone = fullclone($elementobj);
1179                $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1180
1181                if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1182                    foreach ($elementclone->getElements() as $el) {
1183                        $this->repeat_elements_fix_clone($i, $el, $namecloned);
1184                    }
1185                    $elementclone->setLabel(str_replace('{no}', $no, $elementclone->getLabel()));
1186                } else if ($elementobj instanceof \HTML_QuickForm_submit && $elementobj->getName() == $deletebuttonname) {
1187                    // Mark the "Delete" button as no-submit.
1188                    $onclick = $elementclone->getAttribute('onclick');
1189                    $skip = 'skipClientValidation = true;';
1190                    $onclick = ($onclick !== null) ? $skip . ' ' . $onclick : $skip;
1191                    $elementclone->updateAttributes(['data-skip-validation' => 1, 'data-no-submit' => 1, 'onclick' => $onclick]);
1192                }
1193
1194                // Mark newly created elements, so they know not to look for any submitted data.
1195                if ($i >= $oldrepeats) {
1196                    $mform->note_new_repeat($elementclone->getName());
1197                }
1198
1199                $mform->addElement($elementclone);
1200                $no++;
1201            }
1202        }
1203        for ($i=0; $i<$repeats; $i++) {
1204            foreach ($options as $elementname => $elementoptions){
1205                $pos=strpos($elementname, '[');
1206                if ($pos!==FALSE){
1207                    $realelementname = substr($elementname, 0, $pos)."[$i]";
1208                    $realelementname .= substr($elementname, $pos);
1209                }else {
1210                    $realelementname = $elementname."[$i]";
1211                }
1212                foreach ($elementoptions as  $option => $params){
1213
1214                    switch ($option){
1215                        case 'default' :
1216                            $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1217                            break;
1218                        case 'helpbutton' :
1219                            $params = array_merge(array($realelementname), $params);
1220                            call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1221                            break;
1222                        case 'disabledif' :
1223                        case 'hideif' :
1224                            $pos = strpos($params[0], '[');
1225                            $ending = '';
1226                            if ($pos !== false) {
1227                                $ending = substr($params[0], $pos);
1228                                $params[0] = substr($params[0], 0, $pos);
1229                            }
1230                            foreach ($namecloned as $num => $name){
1231                                if ($params[0] == $name){
1232                                    $params[0] = $params[0] . "[$i]" . $ending;
1233                                    break;
1234                                }
1235                            }
1236                            $params = array_merge(array($realelementname), $params);
1237                            $function = ($option === 'disabledif') ? 'disabledIf' : 'hideIf';
1238                            call_user_func_array(array(&$mform, $function), $params);
1239                            break;
1240                        case 'rule' :
1241                            if (is_string($params)){
1242                                $params = array(null, $params, null, 'client');
1243                            }
1244                            $params = array_merge(array($realelementname), $params);
1245                            call_user_func_array(array(&$mform, 'addRule'), $params);
1246                            break;
1247
1248                        case 'type':
1249                            $mform->setType($realelementname, $params);
1250                            break;
1251
1252                        case 'expanded':
1253                            $mform->setExpanded($realelementname, $params);
1254                            break;
1255
1256                        case 'advanced' :
1257                            $mform->setAdvanced($realelementname, $params);
1258                            break;
1259                    }
1260                }
1261            }
1262        }
1263        $mform->addElement('submit', $addfieldsname, $addstring, [], false);
1264
1265        if (!$addbuttoninside) {
1266            $mform->closeHeaderBefore($addfieldsname);
1267        }
1268
1269        return $repeats;
1270    }
1271
1272    /**
1273     * Adds a link/button that controls the checked state of a group of checkboxes.
1274     *
1275     * @param int $groupid The id of the group of advcheckboxes this element controls
1276     * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1277     * @param array $attributes associative array of HTML attributes
1278     * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1279     */
1280    function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1281        global $CFG, $PAGE;
1282
1283        // Name of the controller button
1284        $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1285        $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1286        $checkboxgroupclass = 'checkboxgroup'.$groupid;
1287
1288        // Set the default text if none was specified
1289        if (empty($text)) {
1290            $text = get_string('selectallornone', 'form');
1291        }
1292
1293        $mform = $this->_form;
1294        $selectvalue = $this->optional_param($checkboxcontrollerparam, null, PARAM_INT);
1295        $contollerbutton = $this->optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1296
1297        $newselectvalue = $selectvalue;
1298        if (is_null($selectvalue)) {
1299            $newselectvalue = $originalValue;
1300        } else if (!is_null($contollerbutton)) {
1301            $newselectvalue = (int) !$selectvalue;
1302        }
1303        // set checkbox state depending on orignal/submitted value by controoler button
1304        if (!is_null($contollerbutton) || is_null($selectvalue)) {
1305            foreach ($mform->_elements as $element) {
1306                if (($element instanceof MoodleQuickForm_advcheckbox) &&
1307                        $element->getAttribute('class') == $checkboxgroupclass &&
1308                        !$element->isFrozen()) {
1309                    $mform->setConstants(array($element->getName() => $newselectvalue));
1310                }
1311            }
1312        }
1313
1314        $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1315        $mform->setType($checkboxcontrollerparam, PARAM_INT);
1316        $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1317
1318        $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1319                array(
1320                    array('groupid' => $groupid,
1321                        'checkboxclass' => $checkboxgroupclass,
1322                        'checkboxcontroller' => $checkboxcontrollerparam,
1323                        'controllerbutton' => $checkboxcontrollername)
1324                    )
1325                );
1326
1327        require_once("$CFG->libdir/form/submit.php");
1328        $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1329        $mform->addElement($submitlink);
1330        $mform->registerNoSubmitButton($checkboxcontrollername);
1331        $mform->setDefault($checkboxcontrollername, $text);
1332    }
1333
1334    /**
1335     * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1336     * if you don't want a cancel button in your form. If you have a cancel button make sure you
1337     * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1338     * get data with get_data().
1339     *
1340     * @param bool $cancel whether to show cancel button, default true
1341     * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1342     */
1343    function add_action_buttons($cancel = true, $submitlabel=null){
1344        if (is_null($submitlabel)){
1345            $submitlabel = get_string('savechanges');
1346        }
1347        $mform =& $this->_form;
1348        if ($cancel){
1349            //when two elements we need a group
1350            $buttonarray=array();
1351            $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1352            $buttonarray[] = &$mform->createElement('cancel');
1353            $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1354            $mform->closeHeaderBefore('buttonar');
1355        } else {
1356            //no group needed
1357            $mform->addElement('submit', 'submitbutton', $submitlabel);
1358            $mform->closeHeaderBefore('submitbutton');
1359        }
1360    }
1361
1362    /**
1363     * Adds an initialisation call for a standard JavaScript enhancement.
1364     *
1365     * This function is designed to add an initialisation call for a JavaScript
1366     * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1367     *
1368     * Current options:
1369     *  - Selectboxes
1370     *      - smartselect:  Turns a nbsp indented select box into a custom drop down
1371     *                      control that supports multilevel and category selection.
1372     *                      $enhancement = 'smartselect';
1373     *                      $options = array('selectablecategories' => true|false)
1374     *
1375     * @param string|element $element form element for which Javascript needs to be initalized
1376     * @param string $enhancement which init function should be called
1377     * @param array $options options passed to javascript
1378     * @param array $strings strings for javascript
1379     * @deprecated since Moodle 3.3 MDL-57471
1380     */
1381    function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1382        debugging('$mform->init_javascript_enhancement() is deprecated and no longer does anything. '.
1383            'smartselect uses should be converted to the searchableselector form element.', DEBUG_DEVELOPER);
1384    }
1385
1386    /**
1387     * Returns a JS module definition for the mforms JS
1388     *
1389     * @return array
1390     */
1391    public static function get_js_module() {
1392        global $CFG;
1393        return array(
1394            'name' => 'mform',
1395            'fullpath' => '/lib/form/form.js',
1396            'requires' => array('base', 'node')
1397        );
1398    }
1399
1400    /**
1401     * Detects elements with missing setType() declerations.
1402     *
1403     * Finds elements in the form which should a PARAM_ type set and throws a
1404     * developer debug warning for any elements without it. This is to reduce the
1405     * risk of potential security issues by developers mistakenly forgetting to set
1406     * the type.
1407     *
1408     * @return void
1409     */
1410    private function detectMissingSetType() {
1411        global $CFG;
1412
1413        if (!$CFG->debugdeveloper) {
1414            // Only for devs.
1415            return;
1416        }
1417
1418        $mform = $this->_form;
1419        foreach ($mform->_elements as $element) {
1420            $group = false;
1421            $elements = array($element);
1422
1423            if ($element->getType() == 'group') {
1424                $group = $element;
1425                $elements = $element->getElements();
1426            }
1427
1428            foreach ($elements as $index => $element) {
1429                switch ($element->getType()) {
1430                    case 'hidden':
1431                    case 'text':
1432                    case 'url':
1433                        if ($group) {
1434                            $name = $group->getElementName($index);
1435                        } else {
1436                            $name = $element->getName();
1437                        }
1438                        $key = $name;
1439                        $found = array_key_exists($key, $mform->_types);
1440                        // For repeated elements we need to look for
1441                        // the "main" type, not for the one present
1442                        // on each repetition. All the stuff in formslib
1443                        // (repeat_elements(), updateSubmission()... seems
1444                        // to work that way.
1445                        while (!$found && strrpos($key, '[') !== false) {
1446                            $pos = strrpos($key, '[');
1447                            $key = substr($key, 0, $pos);
1448                            $found = array_key_exists($key, $mform->_types);
1449                        }
1450                        if (!$found) {
1451                            debugging("Did you remember to call setType() for '$name'? ".
1452                                'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1453                        }
1454                        break;
1455                }
1456            }
1457        }
1458    }
1459
1460    /**
1461     * Used by tests to simulate submitted form data submission from the user.
1462     *
1463     * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1464     * get_data.
1465     *
1466     * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1467     * global arrays after each test.
1468     *
1469     * @param array  $simulatedsubmitteddata       An associative array of form values (same format as $_POST).
1470     * @param array  $simulatedsubmittedfiles      An associative array of files uploaded (same format as $_FILES). Can be omitted.
1471     * @param string $method                       'post' or 'get', defaults to 'post'.
1472     * @param null   $formidentifier               the default is to use the class name for this class but you may need to provide
1473     *                                              a different value here for some forms that are used more than once on the
1474     *                                              same page.
1475     */
1476    public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1477                                       $formidentifier = null) {
1478        $_FILES = $simulatedsubmittedfiles;
1479        if ($formidentifier === null) {
1480            $formidentifier = get_called_class();
1481            $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1482        }
1483        $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1484        $simulatedsubmitteddata['sesskey'] = sesskey();
1485        if (strtolower($method) === 'get') {
1486            $_GET = $simulatedsubmitteddata;
1487        } else {
1488            $_POST = $simulatedsubmitteddata;
1489        }
1490    }
1491
1492    /**
1493     * Used by tests to simulate submitted form data submission via AJAX.
1494     *
1495     * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1496     * get_data.
1497     *
1498     * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1499     * global arrays after each test.
1500     *
1501     * @param array  $simulatedsubmitteddata       An associative array of form values (same format as $_POST).
1502     * @param array  $simulatedsubmittedfiles      An associative array of files uploaded (same format as $_FILES). Can be omitted.
1503     * @param string $method                       'post' or 'get', defaults to 'post'.
1504     * @param null   $formidentifier               the default is to use the class name for this class but you may need to provide
1505     *                                              a different value here for some forms that are used more than once on the
1506     *                                              same page.
1507     * @return array array to pass to form constructor as $ajaxdata
1508     */
1509    public static function mock_ajax_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1510                                            $formidentifier = null) {
1511        $_FILES = $simulatedsubmittedfiles;
1512        if ($formidentifier === null) {
1513            $formidentifier = get_called_class();
1514            $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1515        }
1516        $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1517        $simulatedsubmitteddata['sesskey'] = sesskey();
1518        if (strtolower($method) === 'get') {
1519            $_GET = ['sesskey' => sesskey()];
1520        } else {
1521            $_POST = ['sesskey' => sesskey()];
1522        }
1523        return $simulatedsubmitteddata;
1524    }
1525
1526    /**
1527     * Used by tests to generate valid submit keys for moodle forms that are
1528     * submitted with ajax data.
1529     *
1530     * @throws \moodle_exception If called outside unit test environment
1531     * @param array  $data Existing form data you wish to add the keys to.
1532     * @return array
1533     */
1534    public static function mock_generate_submit_keys($data = []) {
1535        if (!defined('PHPUNIT_TEST') || !PHPUNIT_TEST) {
1536            throw new \moodle_exception("This function can only be used for unit testing.");
1537        }
1538
1539        $formidentifier = get_called_class();
1540        $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1541        $data['sesskey'] = sesskey();
1542        $data['_qf__' . $formidentifier] = 1;
1543
1544        return $data;
1545    }
1546
1547    /**
1548     * Set display mode for the form when labels take full width of the form and above the elements even on big screens
1549     *
1550     * Useful for forms displayed inside modals or in narrow containers
1551     */
1552    public function set_display_vertical() {
1553        $oldclass = $this->_form->getAttribute('class');
1554        $this->_form->updateAttributes(array('class' => $oldclass . ' full-width-labels'));
1555    }
1556
1557    /**
1558     * Set the initial 'dirty' state of the form.
1559     *
1560     * @param bool $state
1561     * @since Moodle 3.7.1
1562     */
1563    public function set_initial_dirty_state($state = false) {
1564        $this->_form->set_initial_dirty_state($state);
1565    }
1566}
1567
1568/**
1569 * MoodleQuickForm implementation
1570 *
1571 * You never extend this class directly. The class methods of this class are available from
1572 * the private $this->_form property on moodleform and its children. You generally only
1573 * call methods on this class from within abstract methods that you override on moodleform such
1574 * as definition and definition_after_data
1575 *
1576 * @package   core_form
1577 * @category  form
1578 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1579 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1580 */
1581class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1582    /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1583    var $_types = array();
1584
1585    /** @var array dependent state for the element/'s */
1586    var $_dependencies = array();
1587
1588    /**
1589     * @var array elements that will become hidden based on another element
1590     */
1591    protected $_hideifs = array();
1592
1593    /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1594    var $_noSubmitButtons=array();
1595
1596    /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1597    var $_cancelButtons=array();
1598
1599    /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1600    var $_advancedElements = array();
1601
1602    /**
1603     * Array whose keys are element names and values are the desired collapsible state.
1604     * True for collapsed, False for expanded. If not present, set to default in
1605     * {@link self::accept()}.
1606     *
1607     * @var array
1608     */
1609    var $_collapsibleElements = array();
1610
1611    /**
1612     * Whether to enable shortforms for this form
1613     *
1614     * @var boolean
1615     */
1616    var $_disableShortforms = false;
1617
1618    /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1619    protected $_use_form_change_checker = true;
1620
1621    /**
1622     * The initial state of the dirty state.
1623     *
1624     * @var bool
1625     */
1626    protected $_initial_form_dirty_state = false;
1627
1628    /**
1629     * The form name is derived from the class name of the wrapper minus the trailing form
1630     * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1631     * @var string
1632     */
1633    var $_formName = '';
1634
1635    /**
1636     * String with the html for hidden params passed in as part of a moodle_url
1637     * object for the action. Output in the form.
1638     * @var string
1639     */
1640    var $_pageparams = '';
1641
1642    /** @var array names of new repeating elements that should not expect to find submitted data */
1643    protected $_newrepeats = array();
1644
1645    /** @var array $_ajaxformdata submitted form data when using mforms with ajax */
1646    protected $_ajaxformdata;
1647
1648    /**
1649     * Whether the form contains any client-side validation or not.
1650     * @var bool
1651     */
1652    protected $clientvalidation = false;
1653
1654    /**
1655     * Is this a 'disableIf' dependency ?
1656     */
1657    const DEP_DISABLE = 0;
1658
1659    /**
1660     * Is this a 'hideIf' dependency?
1661     */
1662    const DEP_HIDE = 1;
1663
1664    /**
1665     * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1666     *
1667     * @staticvar int $formcounter counts number of forms
1668     * @param string $formName Form's name.
1669     * @param string $method Form's method defaults to 'POST'
1670     * @param string|moodle_url $action Form's action
1671     * @param string $target (optional)Form's target defaults to none
1672     * @param mixed $attributes (optional)Extra attributes for <form> tag
1673     * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
1674     */
1675    public function __construct($formName, $method, $action, $target = '', $attributes = null, $ajaxformdata = null) {
1676        global $CFG, $OUTPUT;
1677
1678        static $formcounter = 1;
1679
1680        // TODO MDL-52313 Replace with the call to parent::__construct().
1681        HTML_Common::__construct($attributes);
1682        $target = empty($target) ? array() : array('target' => $target);
1683        $this->_formName = $formName;
1684        if (is_a($action, 'moodle_url')){
1685            $this->_pageparams = html_writer::input_hidden_params($action);
1686            $action = $action->out_omit_querystring();
1687        } else {
1688            $this->_pageparams = '';
1689        }
1690        // No 'name' atttribute for form in xhtml strict :
1691        $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1692        if (is_null($this->getAttribute('id'))) {
1693            // Append a random id, forms can be loaded in different requests using Fragments API.
1694            $attributes['id'] = 'mform' . $formcounter . '_' . random_string();
1695        }
1696        $formcounter++;
1697        $this->updateAttributes($attributes);
1698
1699        // This is custom stuff for Moodle :
1700        $this->_ajaxformdata = $ajaxformdata;
1701        $oldclass=   $this->getAttribute('class');
1702        if (!empty($oldclass)){
1703            $this->updateAttributes(array('class'=>$oldclass.' mform'));
1704        }else {
1705            $this->updateAttributes(array('class'=>'mform'));
1706        }
1707        $this->_reqHTML = '<span class="req">' . $OUTPUT->pix_icon('req', get_string('requiredelement', 'form')) . '</span>';
1708        $this->_advancedHTML = '<span class="adv">' . $OUTPUT->pix_icon('adv', get_string('advancedelement', 'form')) . '</span>';
1709        $this->setRequiredNote(get_string('somefieldsrequired', 'form', $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'))));
1710    }
1711
1712    /**
1713     * Old syntax of class constructor. Deprecated in PHP7.
1714     *
1715     * @deprecated since Moodle 3.1
1716     */
1717    public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1718        debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1719        self::__construct($formName, $method, $action, $target, $attributes);
1720    }
1721
1722    /**
1723     * Use this method to indicate an element in a form is an advanced field. If items in a form
1724     * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1725     * form so the user can decide whether to display advanced form controls.
1726     *
1727     * If you set a header element to advanced then all elements it contains will also be set as advanced.
1728     *
1729     * @param string $elementName group or element name (not the element name of something inside a group).
1730     * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1731     */
1732    function setAdvanced($elementName, $advanced = true) {
1733        if ($advanced){
1734            $this->_advancedElements[$elementName]='';
1735        } elseif (isset($this->_advancedElements[$elementName])) {
1736            unset($this->_advancedElements[$elementName]);
1737        }
1738    }
1739
1740    /**
1741     * Checks if a parameter was passed in the previous form submission
1742     *
1743     * @param string $name the name of the page parameter we want
1744     * @param mixed  $default the default value to return if nothing is found
1745     * @param string $type expected type of parameter
1746     * @return mixed
1747     */
1748    public function optional_param($name, $default, $type) {
1749        if (isset($this->_ajaxformdata[$name])) {
1750            return clean_param($this->_ajaxformdata[$name], $type);
1751        } else {
1752            return optional_param($name, $default, $type);
1753        }
1754    }
1755
1756    /**
1757     * Use this method to indicate that the fieldset should be shown as expanded.
1758     * The method is applicable to header elements only.
1759     *
1760     * @param string $headername header element name
1761     * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1762     * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1763     *                                 the form was submitted.
1764     * @return void
1765     */
1766    function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1767        if (empty($headername)) {
1768            return;
1769        }
1770        $element = $this->getElement($headername);
1771        if ($element->getType() != 'header') {
1772            debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1773            return;
1774        }
1775        if (!$headerid = $element->getAttribute('id')) {
1776            $element->_generateId();
1777            $headerid = $element->getAttribute('id');
1778        }
1779        if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1780            // See if the form has been submitted already.
1781            $formexpanded = $this->optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1782            if (!$ignoreuserstate && $formexpanded != -1) {
1783                // Override expanded state with the form variable.
1784                $expanded = $formexpanded;
1785            }
1786            // Create the form element for storing expanded state.
1787            $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1788            $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1789            $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1790        }
1791        $this->_collapsibleElements[$headername] = !$expanded;
1792    }
1793
1794    /**
1795     * Use this method to add show more/less status element required for passing
1796     * over the advanced elements visibility status on the form submission.
1797     *
1798     * @param string $headerName header element name.
1799     * @param boolean $showmore default false sets the advanced elements to be hidden.
1800     */
1801    function addAdvancedStatusElement($headerid, $showmore=false){
1802        // Add extra hidden element to store advanced items state for each section.
1803        if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1804            // See if we the form has been submitted already.
1805            $formshowmore = $this->optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1806            if (!$showmore && $formshowmore != -1) {
1807                // Override showmore state with the form variable.
1808                $showmore = $formshowmore;
1809            }
1810            // Create the form element for storing advanced items state.
1811            $this->addElement('hidden', 'mform_showmore_' . $headerid);
1812            $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1813            $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1814        }
1815    }
1816
1817    /**
1818     * This function has been deprecated. Show advanced has been replaced by
1819     * "Show more.../Show less..." in the shortforms javascript module.
1820     *
1821     * @deprecated since Moodle 2.5
1822     * @param bool $showadvancedNow if true will show advanced elements.
1823      */
1824    function setShowAdvanced($showadvancedNow = null){
1825        debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1826    }
1827
1828    /**
1829     * This function has been deprecated. Show advanced has been replaced by
1830     * "Show more.../Show less..." in the shortforms javascript module.
1831     *
1832     * @deprecated since Moodle 2.5
1833     * @return bool (Always false)
1834      */
1835    function getShowAdvanced(){
1836        debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1837        return false;
1838    }
1839
1840    /**
1841     * Use this method to indicate that the form will not be using shortforms.
1842     *
1843     * @param boolean $disable default true, controls if the shortforms are disabled.
1844     */
1845    function setDisableShortforms ($disable = true) {
1846        $this->_disableShortforms = $disable;
1847    }
1848
1849    /**
1850     * Set the initial 'dirty' state of the form.
1851     *
1852     * @param bool $state
1853     * @since Moodle 3.7.1
1854     */
1855    public function set_initial_dirty_state($state = false) {
1856        $this->_initial_form_dirty_state = $state;
1857    }
1858
1859    /**
1860     * Is the form currently set to dirty?
1861     *
1862     * @return boolean Initial dirty state.
1863     * @since Moodle 3.7.1
1864     */
1865    public function is_dirty() {
1866        return $this->_initial_form_dirty_state;
1867    }
1868
1869    /**
1870     * Call this method if you don't want the formchangechecker JavaScript to be
1871     * automatically initialised for this form.
1872     */
1873    public function disable_form_change_checker() {
1874        $this->_use_form_change_checker = false;
1875    }
1876
1877    /**
1878     * If you have called {@link disable_form_change_checker()} then you can use
1879     * this method to re-enable it. It is enabled by default, so normally you don't
1880     * need to call this.
1881     */
1882    public function enable_form_change_checker() {
1883        $this->_use_form_change_checker = true;
1884    }
1885
1886    /**
1887     * @return bool whether this form should automatically initialise
1888     *      formchangechecker for itself.
1889     */
1890    public function is_form_change_checker_enabled() {
1891        return $this->_use_form_change_checker;
1892    }
1893
1894    /**
1895    * Accepts a renderer
1896    *
1897    * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1898    */
1899    function accept(&$renderer) {
1900        if (method_exists($renderer, 'setAdvancedElements')){
1901            //Check for visible fieldsets where all elements are advanced
1902            //and mark these headers as advanced as well.
1903            //Also mark all elements in a advanced header as advanced.
1904            $stopFields = $renderer->getStopFieldSetElements();
1905            $lastHeader = null;
1906            $lastHeaderAdvanced = false;
1907            $anyAdvanced = false;
1908            $anyError = false;
1909            foreach (array_keys($this->_elements) as $elementIndex){
1910                $element =& $this->_elements[$elementIndex];
1911
1912                // if closing header and any contained element was advanced then mark it as advanced
1913                if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1914                    if ($anyAdvanced && !is_null($lastHeader)) {
1915                        $lastHeader->_generateId();
1916                        $this->setAdvanced($lastHeader->getName());
1917                        $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1918                    }
1919                    $lastHeaderAdvanced = false;
1920                    unset($lastHeader);
1921                    $lastHeader = null;
1922                } elseif ($lastHeaderAdvanced) {
1923                    $this->setAdvanced($element->getName());
1924                }
1925
1926                if ($element->getType()=='header'){
1927                    $lastHeader =& $element;
1928                    $anyAdvanced = false;
1929                    $anyError = false;
1930                    $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1931                } elseif (isset($this->_advancedElements[$element->getName()])){
1932                    $anyAdvanced = true;
1933                    if (isset($this->_errors[$element->getName()])) {
1934                        $anyError = true;
1935                    }
1936                }
1937            }
1938            // the last header may not be closed yet...
1939            if ($anyAdvanced && !is_null($lastHeader)){
1940                $this->setAdvanced($lastHeader->getName());
1941                $lastHeader->_generateId();
1942                $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1943            }
1944            $renderer->setAdvancedElements($this->_advancedElements);
1945        }
1946        if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1947
1948            // Count the number of sections.
1949            $headerscount = 0;
1950            foreach (array_keys($this->_elements) as $elementIndex){
1951                $element =& $this->_elements[$elementIndex];
1952                if ($element->getType() == 'header') {
1953                    $headerscount++;
1954                }
1955            }
1956
1957            $anyrequiredorerror = false;
1958            $headercounter = 0;
1959            $headername = null;
1960            foreach (array_keys($this->_elements) as $elementIndex){
1961                $element =& $this->_elements[$elementIndex];
1962
1963                if ($element->getType() == 'header') {
1964                    $headercounter++;
1965                    $element->_generateId();
1966                    $headername = $element->getName();
1967                    $anyrequiredorerror = false;
1968                } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1969                    $anyrequiredorerror = true;
1970                } else {
1971                    // Do not reset $anyrequiredorerror to false because we do not want any other element
1972                    // in this header (fieldset) to possibly revert the state given.
1973                }
1974
1975                if ($element->getType() == 'header') {
1976                    if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1977                        // By default the first section is always expanded, except if a state has already been set.
1978                        $this->setExpanded($headername, true);
1979                    } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1980                        // The second section is always expanded if the form only contains 2 sections),
1981                        // except if a state has already been set.
1982                        $this->setExpanded($headername, true);
1983                    }
1984                } else if ($anyrequiredorerror) {
1985                    // If any error or required field are present within the header, we need to expand it.
1986                    $this->setExpanded($headername, true, true);
1987                } else if (!isset($this->_collapsibleElements[$headername])) {
1988                    // Define element as collapsed by default.
1989                    $this->setExpanded($headername, false);
1990                }
1991            }
1992
1993            // Pass the array to renderer object.
1994            $renderer->setCollapsibleElements($this->_collapsibleElements);
1995        }
1996        parent::accept($renderer);
1997    }
1998
1999    /**
2000     * Adds one or more element names that indicate the end of a fieldset
2001     *
2002     * @param string $elementName name of the element
2003     */
2004    function closeHeaderBefore($elementName){
2005        $renderer =& $this->defaultRenderer();
2006        $renderer->addStopFieldsetElements($elementName);
2007    }
2008
2009    /**
2010     * Set an element to be forced to flow LTR.
2011     *
2012     * The element must exist and support this functionality. Also note that
2013     * when setting the type of a field (@link self::setType} we try to guess the
2014     * whether the field should be force to LTR or not. Make sure you're always
2015     * calling this method last.
2016     *
2017     * @param string $elementname The element name.
2018     * @param bool $value When false, disables force LTR, else enables it.
2019     */
2020    public function setForceLtr($elementname, $value = true) {
2021        $this->getElement($elementname)->set_force_ltr($value);
2022    }
2023
2024    /**
2025     * Should be used for all elements of a form except for select, radio and checkboxes which
2026     * clean their own data.
2027     *
2028     * @param string $elementname
2029     * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
2030     *        {@link lib/moodlelib.php} for defined parameter types
2031     */
2032    function setType($elementname, $paramtype) {
2033        $this->_types[$elementname] = $paramtype;
2034
2035        // This will not always get it right, but it should be accurate in most cases.
2036        // When inaccurate use setForceLtr().
2037        if (!is_rtl_compatible($paramtype)
2038                && $this->elementExists($elementname)
2039                && ($element =& $this->getElement($elementname))
2040                && method_exists($element, 'set_force_ltr')) {
2041
2042            $element->set_force_ltr(true);
2043        }
2044    }
2045
2046    /**
2047     * This can be used to set several types at once.
2048     *
2049     * @param array $paramtypes types of parameters.
2050     * @see MoodleQuickForm::setType
2051     */
2052    function setTypes($paramtypes) {
2053        foreach ($paramtypes as $elementname => $paramtype) {
2054            $this->setType($elementname, $paramtype);
2055        }
2056    }
2057
2058    /**
2059     * Return the type(s) to use to clean an element.
2060     *
2061     * In the case where the element has an array as a value, we will try to obtain a
2062     * type defined for that specific key, and recursively until done.
2063     *
2064     * This method does not work reverse, you cannot pass a nested element and hoping to
2065     * fallback on the clean type of a parent. This method intends to be used with the
2066     * main element, which will generate child types if needed, not the other way around.
2067     *
2068     * Example scenario:
2069     *
2070     * You have defined a new repeated element containing a text field called 'foo'.
2071     * By default there will always be 2 occurence of 'foo' in the form. Even though
2072     * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
2073     * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
2074     * $mform->setType('foo[0]', PARAM_FLOAT).
2075     *
2076     * Now if you call this method passing 'foo', along with the submitted values of 'foo':
2077     * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
2078     * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
2079     * get the default clean type returned (param $default).
2080     *
2081     * @param string $elementname name of the element.
2082     * @param mixed $value value that should be cleaned.
2083     * @param int $default default constant value to be returned (PARAM_...)
2084     * @return string|array constant value or array of constant values (PARAM_...)
2085     */
2086    public function getCleanType($elementname, $value, $default = PARAM_RAW) {
2087        $type = $default;
2088        if (array_key_exists($elementname, $this->_types)) {
2089            $type = $this->_types[$elementname];
2090        }
2091        if (is_array($value)) {
2092            $default = $type;
2093            $type = array();
2094            foreach ($value as $subkey => $subvalue) {
2095                $typekey = "$elementname" . "[$subkey]";
2096                if (array_key_exists($typekey, $this->_types)) {
2097                    $subtype = $this->_types[$typekey];
2098                } else {
2099                    $subtype = $default;
2100                }
2101                if (is_array($subvalue)) {
2102                    $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
2103                } else {
2104                    $type[$subkey] = $subtype;
2105                }
2106            }
2107        }
2108        return $type;
2109    }
2110
2111    /**
2112     * Return the cleaned value using the passed type(s).
2113     *
2114     * @param mixed $value value that has to be cleaned.
2115     * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
2116     * @return mixed cleaned up value.
2117     */
2118    public function getCleanedValue($value, $type) {
2119        if (is_array($type) && is_array($value)) {
2120            foreach ($type as $key => $param) {
2121                $value[$key] = $this->getCleanedValue($value[$key], $param);
2122            }
2123        } else if (!is_array($type) && !is_array($value)) {
2124            $value = clean_param($value, $type);
2125        } else if (!is_array($type) && is_array($value)) {
2126            $value = clean_param_array($value, $type, true);
2127        } else {
2128            throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
2129        }
2130        return $value;
2131    }
2132
2133    /**
2134     * Updates submitted values
2135     *
2136     * @param array $submission submitted values
2137     * @param array $files list of files
2138     */
2139    function updateSubmission($submission, $files) {
2140        $this->_flagSubmitted = false;
2141
2142        if (empty($submission)) {
2143            $this->_submitValues = array();
2144        } else {
2145            foreach ($submission as $key => $s) {
2146                $type = $this->getCleanType($key, $s);
2147                $submission[$key] = $this->getCleanedValue($s, $type);
2148            }
2149            $this->_submitValues = $submission;
2150            $this->_flagSubmitted = true;
2151        }
2152
2153        if (empty($files)) {
2154            $this->_submitFiles = array();
2155        } else {
2156            $this->_submitFiles = $files;
2157            $this->_flagSubmitted = true;
2158        }
2159
2160        // need to tell all elements that they need to update their value attribute.
2161         foreach (array_keys($this->_elements) as $key) {
2162             $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
2163         }
2164    }
2165
2166    /**
2167     * Returns HTML for required elements
2168     *
2169     * @return string
2170     */
2171    function getReqHTML(){
2172        return $this->_reqHTML;
2173    }
2174
2175    /**
2176     * Returns HTML for advanced elements
2177     *
2178     * @return string
2179     */
2180    function getAdvancedHTML(){
2181        return $this->_advancedHTML;
2182    }
2183
2184    /**
2185     * Initializes a default form value. Used to specify the default for a new entry where
2186     * no data is loaded in using moodleform::set_data()
2187     *
2188     * note: $slashed param removed
2189     *
2190     * @param string $elementName element name
2191     * @param mixed $defaultValue values for that element name
2192     */
2193    function setDefault($elementName, $defaultValue){
2194        $this->setDefaults(array($elementName=>$defaultValue));
2195    }
2196
2197    /**
2198     * Add a help button to element, only one button per element is allowed.
2199     *
2200     * This is new, simplified and preferable method of setting a help icon on form elements.
2201     * It uses the new $OUTPUT->help_icon().
2202     *
2203     * Typically, you will provide the same identifier and the component as you have used for the
2204     * label of the element. The string identifier with the _help suffix added is then used
2205     * as the help string.
2206     *
2207     * There has to be two strings defined:
2208     *   1/ get_string($identifier, $component) - the title of the help page
2209     *   2/ get_string($identifier.'_help', $component) - the actual help page text
2210     *
2211     * @since Moodle 2.0
2212     * @param string $elementname name of the element to add the item to
2213     * @param string $identifier help string identifier without _help suffix
2214     * @param string $component component name to look the help string in
2215     * @param string $linktext optional text to display next to the icon
2216     * @param bool $suppresscheck set to true if the element may not exist
2217     */
2218    function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
2219        global $OUTPUT;
2220        if (array_key_exists($elementname, $this->_elementIndex)) {
2221            $element = $this->_elements[$this->_elementIndex[$elementname]];
2222            $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
2223        } else if (!$suppresscheck) {
2224            debugging(get_string('nonexistentformelements', 'form', $elementname));
2225        }
2226    }
2227
2228    /**
2229     * Set constant value not overridden by _POST or _GET
2230     * note: this does not work for complex names with [] :-(
2231     *
2232     * @param string $elname name of element
2233     * @param mixed $value
2234     */
2235    function setConstant($elname, $value) {
2236        $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
2237        $element =& $this->getElement($elname);
2238        $element->onQuickFormEvent('updateValue', null, $this);
2239    }
2240
2241    /**
2242     * export submitted values
2243     *
2244     * @param string $elementList list of elements in form
2245     * @return array
2246     */
2247    function exportValues($elementList = null){
2248        $unfiltered = array();
2249        if (null === $elementList) {
2250            // iterate over all elements, calling their exportValue() methods
2251            foreach (array_keys($this->_elements) as $key) {
2252                if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
2253                    $varname = $this->_elements[$key]->_attributes['name'];
2254                    $value = '';
2255                    // If we have a default value then export it.
2256                    if (isset($this->_defaultValues[$varname])) {
2257                        $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
2258                    }
2259                } else {
2260                    $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
2261                }
2262
2263                if (is_array($value)) {
2264                    // This shit throws a bogus warning in PHP 4.3.x
2265                    $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2266                }
2267            }
2268        } else {
2269            if (!is_array($elementList)) {
2270                $elementList = array_map('trim', explode(',', $elementList));
2271            }
2272            foreach ($elementList as $elementName) {
2273                $value = $this->exportValue($elementName);
2274                if ((new PEAR())->isError($value)) {
2275                    return $value;
2276                }
2277                //oh, stock QuickFOrm was returning array of arrays!
2278                $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2279            }
2280        }
2281
2282        if (is_array($this->_constantValues)) {
2283            $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
2284        }
2285        return $unfiltered;
2286    }
2287
2288    /**
2289     * This is a bit of a hack, and it duplicates the code in
2290     * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
2291     * reliably calling that code. (Think about date selectors, for example.)
2292     * @param string $name the element name.
2293     * @param mixed $value the fixed value to set.
2294     * @return mixed the appropriate array to add to the $unfiltered array.
2295     */
2296    protected function prepare_fixed_value($name, $value) {
2297        if (null === $value) {
2298            return null;
2299        } else {
2300            if (!strpos($name, '[')) {
2301                return array($name => $value);
2302            } else {
2303                $valueAry = array();
2304                $myIndex  = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2305                eval("\$valueAry$myIndex = \$value;");
2306                return $valueAry;
2307            }
2308        }
2309    }
2310
2311    /**
2312     * Adds a validation rule for the given field
2313     *
2314     * If the element is in fact a group, it will be considered as a whole.
2315     * To validate grouped elements as separated entities,
2316     * use addGroupRule instead of addRule.
2317     *
2318     * @param string $element Form element name
2319     * @param string $message Message to display for invalid data
2320     * @param string $type Rule type, use getRegisteredRules() to get types
2321     * @param string $format (optional)Required for extra rule data
2322     * @param string $validation (optional)Where to perform validation: "server", "client"
2323     * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2324     * @param bool $force Force the rule to be applied, even if the target form element does not exist
2325     */
2326    function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2327    {
2328        parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2329        if ($validation == 'client') {
2330            $this->clientvalidation = true;
2331        }
2332
2333    }
2334
2335    /**
2336     * Adds a validation rule for the given group of elements
2337     *
2338     * Only groups with a name can be assigned a validation rule
2339     * Use addGroupRule when you need to validate elements inside the group.
2340     * Use addRule if you need to validate the group as a whole. In this case,
2341     * the same rule will be applied to all elements in the group.
2342     * Use addRule if you need to validate the group against a function.
2343     *
2344     * @param string $group Form group name
2345     * @param array|string $arg1 Array for multiple elements or error message string for one element
2346     * @param string $type (optional)Rule type use getRegisteredRules() to get types
2347     * @param string $format (optional)Required for extra rule data
2348     * @param int $howmany (optional)How many valid elements should be in the group
2349     * @param string $validation (optional)Where to perform validation: "server", "client"
2350     * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2351     */
2352    function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2353    {
2354        parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2355        if (is_array($arg1)) {
2356             foreach ($arg1 as $rules) {
2357                foreach ($rules as $rule) {
2358                    $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2359                    if ($validation == 'client') {
2360                        $this->clientvalidation = true;
2361                    }
2362                }
2363            }
2364        } elseif (is_string($arg1)) {
2365            if ($validation == 'client') {
2366                $this->clientvalidation = true;
2367            }
2368        }
2369    }
2370
2371    /**
2372     * Returns the client side validation script
2373     *
2374     * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from  HTML_QuickForm
2375     * and slightly modified to run rules per-element
2376     * Needed to override this because of an error with client side validation of grouped elements.
2377     *
2378     * @return string Javascript to perform validation, empty string if no 'client' rules were added
2379     */
2380    function getValidationScript()
2381    {
2382        global $PAGE;
2383
2384        if (empty($this->_rules) || $this->clientvalidation === false) {
2385            return '';
2386        }
2387
2388        include_once('HTML/QuickForm/RuleRegistry.php');
2389        $registry =& HTML_QuickForm_RuleRegistry::singleton();
2390        $test = array();
2391        $js_escape = array(
2392            "\r"    => '\r',
2393            "\n"    => '\n',
2394            "\t"    => '\t',
2395            "'"     => "\\'",
2396            '"'     => '\"',
2397            '\\'    => '\\\\'
2398        );
2399
2400        foreach ($this->_rules as $elementName => $rules) {
2401            foreach ($rules as $rule) {
2402                if ('client' == $rule['validation']) {
2403                    unset($element); //TODO: find out how to properly initialize it
2404
2405                    $dependent  = isset($rule['dependent']) && is_array($rule['dependent']);
2406                    $rule['message'] = strtr($rule['message'], $js_escape);
2407
2408                    if (isset($rule['group'])) {
2409                        $group    =& $this->getElement($rule['group']);
2410                        // No JavaScript validation for frozen elements
2411                        if ($group->isFrozen()) {
2412                            continue 2;
2413                        }
2414                        $elements =& $group->getElements();
2415                        foreach (array_keys($elements) as $key) {
2416                            if ($elementName == $group->getElementName($key)) {
2417                                $element =& $elements[$key];
2418                                break;
2419                            }
2420                        }
2421                    } elseif ($dependent) {
2422                        $element   =  array();
2423                        $element[] =& $this->getElement($elementName);
2424                        foreach ($rule['dependent'] as $elName) {
2425                            $element[] =& $this->getElement($elName);
2426                        }
2427                    } else {
2428                        $element =& $this->getElement($elementName);
2429                    }
2430                    // No JavaScript validation for frozen elements
2431                    if (is_object($element) && $element->isFrozen()) {
2432                        continue 2;
2433                    } elseif (is_array($element)) {
2434                        foreach (array_keys($element) as $key) {
2435                            if ($element[$key]->isFrozen()) {
2436                                continue 3;
2437                            }
2438                        }
2439                    }
2440                    //for editor element, [text] is appended to the name.
2441                    $fullelementname = $elementName;
2442                    if (is_object($element) && $element->getType() == 'editor') {
2443                        if ($element->getType() == 'editor') {
2444                            $fullelementname .= '[text]';
2445                            // Add format to rule as moodleform check which format is supported by browser
2446                            // it is not set anywhere... So small hack to make sure we pass it down to quickform.
2447                            if (is_null($rule['format'])) {
2448                                $rule['format'] = $element->getFormat();
2449                            }
2450                        }
2451                    }
2452                    // Fix for bug displaying errors for elements in a group
2453                    $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2454                    $test[$fullelementname][1]=$element;
2455                    //end of fix
2456                }
2457            }
2458        }
2459
2460        // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2461        // the form, and then that form field gets corrupted by the code that follows.
2462        unset($element);
2463
2464        $js = '
2465
2466require(["core/event", "jquery"], function(Event, $) {
2467
2468    function qf_errorHandler(element, _qfMsg, escapedName) {
2469        var event = $.Event(Event.Events.FORM_FIELD_VALIDATION);
2470        $(element).trigger(event, _qfMsg);
2471        if (event.isDefaultPrevented()) {
2472            return _qfMsg == \'\';
2473        } else {
2474            // Legacy mforms.
2475            var div = element.parentNode;
2476
2477            if ((div == undefined) || (element.name == undefined)) {
2478                // No checking can be done for undefined elements so let server handle it.
2479                return true;
2480            }
2481
2482            if (_qfMsg != \'\') {
2483                var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2484                if (!errorSpan) {
2485                    errorSpan = document.createElement("span");
2486                    errorSpan.id = \'id_error_\' + escapedName;
2487                    errorSpan.className = "error";
2488                    element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2489                    document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2490                    document.getElementById(errorSpan.id).focus();
2491                }
2492
2493                while (errorSpan.firstChild) {
2494                    errorSpan.removeChild(errorSpan.firstChild);
2495                }
2496
2497                errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2498
2499                if (div.className.substr(div.className.length - 6, 6) != " error"
2500                        && div.className != "error") {
2501                    div.className += " error";
2502                    linebreak = document.createElement("br");
2503                    linebreak.className = "error";
2504                    linebreak.id = \'id_error_break_\' + escapedName;
2505                    errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2506                }
2507
2508                return false;
2509            } else {
2510                var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2511                if (errorSpan) {
2512                    errorSpan.parentNode.removeChild(errorSpan);
2513                }
2514                var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2515                if (linebreak) {
2516                    linebreak.parentNode.removeChild(linebreak);
2517                }
2518
2519                if (div.className.substr(div.className.length - 6, 6) == " error") {
2520                    div.className = div.className.substr(0, div.className.length - 6);
2521                } else if (div.className == "error") {
2522                    div.className = "";
2523                }
2524
2525                return true;
2526            } // End if.
2527        } // End if.
2528    } // End function.
2529    ';
2530        $validateJS = '';
2531        foreach ($test as $elementName => $jsandelement) {
2532            // Fix for bug displaying errors for elements in a group
2533            //unset($element);
2534            list($jsArr,$element)=$jsandelement;
2535            //end of fix
2536            $escapedElementName = preg_replace_callback(
2537                '/[_\[\]-]/',
2538                function($matches) {
2539                    return sprintf("_%2x", ord($matches[0]));
2540                },
2541                $elementName);
2542            $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
2543
2544            if (!is_array($element)) {
2545                $element = [$element];
2546            }
2547            foreach ($element as $elem) {
2548                if (key_exists('id', $elem->_attributes)) {
2549                    $js .= '
2550    function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2551      if (undefined == element) {
2552         //required element was not found, then let form be submitted without client side validation
2553         return true;
2554      }
2555      var value = \'\';
2556      var errFlag = new Array();
2557      var _qfGroups = {};
2558      var _qfMsg = \'\';
2559      var frm = element.parentNode;
2560      if ((undefined != element.name) && (frm != undefined)) {
2561          while (frm && frm.nodeName.toUpperCase() != "FORM") {
2562            frm = frm.parentNode;
2563          }
2564        ' . join("\n", $jsArr) . '
2565          return qf_errorHandler(element, _qfMsg, escapedName);
2566      } else {
2567        //element name should be defined else error msg will not be displayed.
2568        return true;
2569      }
2570    }
2571
2572    document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'blur\', function(ev) {
2573        ' . $valFunc . '
2574    });
2575    document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'change\', function(ev) {
2576        ' . $valFunc . '
2577    });
2578';
2579                }
2580            }
2581            // This handles both randomised (MDL-65217) and non-randomised IDs.
2582            $errorid = preg_replace('/^id_/', 'id_error_', $elem->_attributes['id']);
2583            $validateJS .= '
2584      ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2585      if (!ret && !first_focus) {
2586        first_focus = true;
2587        Y.use(\'moodle-core-event\', function() {
2588            Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes['id'] . '\',
2589                                                           elementid: \'' . $errorid. '\'});
2590            document.getElementById(\'' . $errorid . '\').focus();
2591        });
2592      }
2593';
2594
2595            // Fix for bug displaying errors for elements in a group
2596            //unset($element);
2597            //$element =& $this->getElement($elementName);
2598            //end of fix
2599            //$onBlur = $element->getAttribute('onBlur');
2600            //$onChange = $element->getAttribute('onChange');
2601            //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2602                                             //'onChange' => $onChange . $valFunc));
2603        }
2604//  do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2605        $js .= '
2606
2607    function validate_' . $this->_formName . '() {
2608      if (skipClientValidation) {
2609         return true;
2610      }
2611      var ret = true;
2612
2613      var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2614      var first_focus = false;
2615    ' . $validateJS . ';
2616      return ret;
2617    }
2618
2619    var form = $(document.getElementById(\'' . $this->_attributes['id'] . '\')).closest(\'form\');
2620    form.on(M.core.event.FORM_SUBMIT_AJAX, function() {
2621        try {
2622            var myValidator = validate_' . $this->_formName . ';
2623        } catch(e) {
2624            return true;
2625        }
2626        if (myValidator) {
2627            myValidator();
2628        }
2629    });
2630
2631    document.getElementById(\'' . $this->_attributes['id'] . '\').addEventListener(\'submit\', function(ev) {
2632        try {
2633            var myValidator = validate_' . $this->_formName . ';
2634        } catch(e) {
2635            return true;
2636        }
2637        if (typeof window.tinyMCE !== \'undefined\') {
2638            window.tinyMCE.triggerSave();
2639        }
2640        if (!myValidator()) {
2641            ev.preventDefault();
2642        }
2643    });
2644
2645});
2646';
2647
2648        $PAGE->requires->js_amd_inline($js);
2649
2650        // Global variable used to skip the client validation.
2651        return html_writer::tag('script', 'var skipClientValidation = false;');
2652    } // end func getValidationScript
2653
2654    /**
2655     * Sets default error message
2656     */
2657    function _setDefaultRuleMessages(){
2658        foreach ($this->_rules as $field => $rulesarr){
2659            foreach ($rulesarr as $key => $rule){
2660                if ($rule['message']===null){
2661                    $a=new stdClass();
2662                    $a->format=$rule['format'];
2663                    $str=get_string('err_'.$rule['type'], 'form', $a);
2664                    if (strpos($str, '[[')!==0){
2665                        $this->_rules[$field][$key]['message']=$str;
2666                    }
2667                }
2668            }
2669        }
2670    }
2671
2672    /**
2673     * Get list of attributes which have dependencies
2674     *
2675     * @return array
2676     */
2677    function getLockOptionObject(){
2678        $result = array();
2679        foreach ($this->_dependencies as $dependentOn => $conditions){
2680            $result[$dependentOn] = array();
2681            foreach ($conditions as $condition=>$values) {
2682                $result[$dependentOn][$condition] = array();
2683                foreach ($values as $value=>$dependents) {
2684                    $result[$dependentOn][$condition][$value][self::DEP_DISABLE] = array();
2685                    foreach ($dependents as $dependent) {
2686                        $elements = $this->_getElNamesRecursive($dependent);
2687                        if (empty($elements)) {
2688                            // probably element inside of some group
2689                            $elements = array($dependent);
2690                        }
2691                        foreach($elements as $element) {
2692                            if ($element == $dependentOn) {
2693                                continue;
2694                            }
2695                            $result[$dependentOn][$condition][$value][self::DEP_DISABLE][] = $element;
2696                        }
2697                    }
2698                }
2699            }
2700        }
2701        foreach ($this->_hideifs as $dependenton => $conditions) {
2702            if (!isset($result[$dependenton])) {
2703                $result[$dependenton] = array();
2704            }
2705            foreach ($conditions as $condition => $values) {
2706                if (!isset($result[$dependenton][$condition])) {
2707                    $result[$dependenton][$condition] = array();
2708                }
2709                foreach ($values as $value => $dependents) {
2710                    $result[$dependenton][$condition][$value][self::DEP_HIDE] = array();
2711                    foreach ($dependents as $dependent) {
2712                        $elements = $this->_getElNamesRecursive($dependent);
2713                        if (!in_array($dependent, $elements)) {
2714                            // Always want to hide the main element, even if it contains sub-elements as well.
2715                            $elements[] = $dependent;
2716                        }
2717                        foreach ($elements as $element) {
2718                            if ($element == $dependenton) {
2719                                continue;
2720                            }
2721                            $result[$dependenton][$condition][$value][self::DEP_HIDE][] = $element;
2722                        }
2723                    }
2724                }
2725            }
2726        }
2727        return array($this->getAttribute('id'), $result);
2728    }
2729
2730    /**
2731     * Get names of element or elements in a group.
2732     *
2733     * @param HTML_QuickForm_group|element $element element group or element object
2734     * @return array
2735     */
2736    function _getElNamesRecursive($element) {
2737        if (is_string($element)) {
2738            if (!$this->elementExists($element)) {
2739                return array();
2740            }
2741            $element = $this->getElement($element);
2742        }
2743
2744        if (is_a($element, 'HTML_QuickForm_group')) {
2745            $elsInGroup = $element->getElements();
2746            $elNames = array();
2747            foreach ($elsInGroup as $elInGroup){
2748                if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2749                    // Groups nested in groups: append the group name to the element and then change it back.
2750                    // We will be appending group name again in MoodleQuickForm_group::export_for_template().
2751                    $oldname = $elInGroup->getName();
2752                    if ($element->_appendName) {
2753                        $elInGroup->setName($element->getName() . '[' . $oldname . ']');
2754                    }
2755                    $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2756                    $elInGroup->setName($oldname);
2757                } else {
2758                    $elNames[] = $element->getElementName($elInGroup->getName());
2759                }
2760            }
2761
2762        } else if (is_a($element, 'HTML_QuickForm_header')) {
2763            return array();
2764
2765        } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2766            return array();
2767
2768        } else if (method_exists($element, 'getPrivateName') &&
2769                !($element instanceof HTML_QuickForm_advcheckbox)) {
2770            // The advcheckbox element implements a method called getPrivateName,
2771            // but in a way that is not compatible with the generic API, so we
2772            // have to explicitly exclude it.
2773            return array($element->getPrivateName());
2774
2775        } else {
2776            $elNames = array($element->getName());
2777        }
2778
2779        return $elNames;
2780    }
2781
2782    /**
2783     * Adds a dependency for $elementName which will be disabled if $condition is met.
2784     * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2785     * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2786     * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2787     * of the $dependentOn element is $condition (such as equal) to $value.
2788     *
2789     * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2790     * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2791     * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2792     *
2793     * @param string $elementName the name of the element which will be disabled
2794     * @param string $dependentOn the name of the element whose state will be checked for condition
2795     * @param string $condition the condition to check
2796     * @param mixed $value used in conjunction with condition.
2797     */
2798    function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2799        // Multiple selects allow for a multiple selection, we transform the array to string here as
2800        // an array cannot be used as a key in an associative array.
2801        if (is_array($value)) {
2802            $value = implode('|', $value);
2803        }
2804        if (!array_key_exists($dependentOn, $this->_dependencies)) {
2805            $this->_dependencies[$dependentOn] = array();
2806        }
2807        if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2808            $this->_dependencies[$dependentOn][$condition] = array();
2809        }
2810        if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2811            $this->_dependencies[$dependentOn][$condition][$value] = array();
2812        }
2813        $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2814    }
2815
2816    /**
2817     * Adds a dependency for $elementName which will be hidden if $condition is met.
2818     * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2819     * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2820     * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2821     * of the $dependentOn element is $condition (such as equal) to $value.
2822     *
2823     * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2824     * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2825     * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2826     *
2827     * @param string $elementname the name of the element which will be hidden
2828     * @param string $dependenton the name of the element whose state will be checked for condition
2829     * @param string $condition the condition to check
2830     * @param mixed $value used in conjunction with condition.
2831     */
2832    public function hideIf($elementname, $dependenton, $condition = 'notchecked', $value = '1') {
2833        // Multiple selects allow for a multiple selection, we transform the array to string here as
2834        // an array cannot be used as a key in an associative array.
2835        if (is_array($value)) {
2836            $value = implode('|', $value);
2837        }
2838        if (!array_key_exists($dependenton, $this->_hideifs)) {
2839            $this->_hideifs[$dependenton] = array();
2840        }
2841        if (!array_key_exists($condition, $this->_hideifs[$dependenton])) {
2842            $this->_hideifs[$dependenton][$condition] = array();
2843        }
2844        if (!array_key_exists($value, $this->_hideifs[$dependenton][$condition])) {
2845            $this->_hideifs[$dependenton][$condition][$value] = array();
2846        }
2847        $this->_hideifs[$dependenton][$condition][$value][] = $elementname;
2848    }
2849
2850    /**
2851     * Registers button as no submit button
2852     *
2853     * @param string $buttonname name of the button
2854     */
2855    function registerNoSubmitButton($buttonname){
2856        $this->_noSubmitButtons[]=$buttonname;
2857    }
2858
2859    /**
2860     * Checks if button is a no submit button, i.e it doesn't submit form
2861     *
2862     * @param string $buttonname name of the button to check
2863     * @return bool
2864     */
2865    function isNoSubmitButton($buttonname){
2866        return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2867    }
2868
2869    /**
2870     * Registers a button as cancel button
2871     *
2872     * @param string $addfieldsname name of the button
2873     */
2874    function _registerCancelButton($addfieldsname){
2875        $this->_cancelButtons[]=$addfieldsname;
2876    }
2877
2878    /**
2879     * Displays elements without HTML input tags.
2880     * This method is different to freeze() in that it makes sure no hidden
2881     * elements are included in the form.
2882     * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2883     *
2884     * This function also removes all previously defined rules.
2885     *
2886     * @param string|array $elementList array or string of element(s) to be frozen
2887     * @return object|bool if element list is not empty then return error object, else true
2888     */
2889    function hardFreeze($elementList=null)
2890    {
2891        if (!isset($elementList)) {
2892            $this->_freezeAll = true;
2893            $elementList = array();
2894        } else {
2895            if (!is_array($elementList)) {
2896                $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2897            }
2898            $elementList = array_flip($elementList);
2899        }
2900
2901        foreach (array_keys($this->_elements) as $key) {
2902            $name = $this->_elements[$key]->getName();
2903            if ($this->_freezeAll || isset($elementList[$name])) {
2904                $this->_elements[$key]->freeze();
2905                $this->_elements[$key]->setPersistantFreeze(false);
2906                unset($elementList[$name]);
2907
2908                // remove all rules
2909                $this->_rules[$name] = array();
2910                // if field is required, remove the rule
2911                $unset = array_search($name, $this->_required);
2912                if ($unset !== false) {
2913                    unset($this->_required[$unset]);
2914                }
2915            }
2916        }
2917
2918        if (!empty($elementList)) {
2919            return self::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
2920        }
2921        return true;
2922    }
2923
2924    /**
2925     * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2926     *
2927     * This function also removes all previously defined rules of elements it freezes.
2928     *
2929     * @throws HTML_QuickForm_Error
2930     * @param array $elementList array or string of element(s) not to be frozen
2931     * @return bool returns true
2932     */
2933    function hardFreezeAllVisibleExcept($elementList)
2934    {
2935        $elementList = array_flip($elementList);
2936        foreach (array_keys($this->_elements) as $key) {
2937            $name = $this->_elements[$key]->getName();
2938            $type = $this->_elements[$key]->getType();
2939
2940            if ($type == 'hidden'){
2941                // leave hidden types as they are
2942            } elseif (!isset($elementList[$name])) {
2943                $this->_elements[$key]->freeze();
2944                $this->_elements[$key]->setPersistantFreeze(false);
2945
2946                // remove all rules
2947                $this->_rules[$name] = array();
2948                // if field is required, remove the rule
2949                $unset = array_search($name, $this->_required);
2950                if ($unset !== false) {
2951                    unset($this->_required[$unset]);
2952                }
2953            }
2954        }
2955        return true;
2956    }
2957
2958   /**
2959    * Tells whether the form was already submitted
2960    *
2961    * This is useful since the _submitFiles and _submitValues arrays
2962    * may be completely empty after the trackSubmit value is removed.
2963    *
2964    * @return bool
2965    */
2966    function isSubmitted()
2967    {
2968        return parent::isSubmitted() && (!$this->isFrozen());
2969    }
2970
2971    /**
2972     * Add the element name to the list of newly-created repeat elements
2973     * (So that elements that interpret 'no data submitted' as a valid state
2974     * can tell when they should get the default value instead).
2975     *
2976     * @param string $name the name of the new element
2977     */
2978    public function note_new_repeat($name) {
2979        $this->_newrepeats[] = $name;
2980    }
2981
2982    /**
2983     * Check if the element with the given name has just been added by clicking
2984     * on the 'Add repeating elements' button.
2985     *
2986     * @param string $name the name of the element being checked
2987     * @return bool true if the element is newly added
2988     */
2989    public function is_new_repeat($name) {
2990        return in_array($name, $this->_newrepeats);
2991    }
2992}
2993
2994/**
2995 * MoodleQuickForm renderer
2996 *
2997 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2998 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2999 *
3000 * Stylesheet is part of standard theme and should be automatically included.
3001 *
3002 * @package   core_form
3003 * @copyright 2007 Jamie Pratt <me@jamiep.org>
3004 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3005 */
3006class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
3007
3008    /** @var array Element template array */
3009    var $_elementTemplates;
3010
3011    /**
3012     * Template used when opening a hidden fieldset
3013     * (i.e. a fieldset that is opened when there is no header element)
3014     * @var string
3015     */
3016    var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
3017
3018    /** @var string Header Template string */
3019    var $_headerTemplate =
3020       "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
3021
3022    /** @var string Template used when opening a fieldset */
3023    var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
3024
3025    /** @var string Template used when closing a fieldset */
3026    var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
3027
3028    /** @var string Required Note template string */
3029    var $_requiredNoteTemplate =
3030        "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
3031
3032    /**
3033     * Collapsible buttons string template.
3034     *
3035     * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
3036     * until the Javascript has been fully loaded.
3037     *
3038     * @var string
3039     */
3040    var $_collapseButtonsTemplate =
3041        "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
3042
3043    /**
3044     * Array whose keys are element names. If the key exists this is a advanced element
3045     *
3046     * @var array
3047     */
3048    var $_advancedElements = array();
3049
3050    /**
3051     * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
3052     *
3053     * @var array
3054     */
3055    var $_collapsibleElements = array();
3056
3057    /**
3058     * @var string Contains the collapsible buttons to add to the form.
3059     */
3060    var $_collapseButtons = '';
3061
3062    /**
3063     * Constructor
3064     */
3065    public function __construct() {
3066        // switch next two lines for ol li containers for form items.
3067        //        $this->_elementTemplates=array('default'=>"\n\t\t".'<li class="fitem"><label>{label}{help}<!-- BEGIN required -->{req}<!-- END required --></label><div class="qfelement<!-- BEGIN error --> error<!-- END error --> {typeclass}"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></li>');
3068        $this->_elementTemplates = array(
3069        'default' => "\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{typeclass} {emptylabel} {class}" {aria-live} {groupname}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {typeclass}<!-- BEGIN error --> error<!-- END error -->" data-fieldtype="{type}"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
3070
3071        'actionbuttons' => "\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{typeclass} {class}" {groupname}><div class="felement {typeclass}" data-fieldtype="{type}">{element}</div></div>',
3072
3073        'fieldset' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {class}<!-- BEGIN required --> required<!-- END required --> fitem_{typeclass} {emptylabel}" {groupname}><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {typeclass}<!-- BEGIN error --> error<!-- END error -->" data-fieldtype="{type}"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
3074
3075        'static' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}" {groupname}><div class="fitemtitle"><div class="fstaticlabel">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->" data-fieldtype="static"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
3076
3077        'warning' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}">{element}</div>',
3078
3079        'nodisplay' => '');
3080
3081        parent::__construct();
3082    }
3083
3084    /**
3085     * Old syntax of class constructor. Deprecated in PHP7.
3086     *
3087     * @deprecated since Moodle 3.1
3088     */
3089    public function MoodleQuickForm_Renderer() {
3090        debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
3091        self::__construct();
3092    }
3093
3094    /**
3095     * Set element's as adavance element
3096     *
3097     * @param array $elements form elements which needs to be grouped as advance elements.
3098     */
3099    function setAdvancedElements($elements){
3100        $this->_advancedElements = $elements;
3101    }
3102
3103    /**
3104     * Setting collapsible elements
3105     *
3106     * @param array $elements
3107     */
3108    function setCollapsibleElements($elements) {
3109        $this->_collapsibleElements = $elements;
3110    }
3111
3112    /**
3113     * What to do when starting the form
3114     *
3115     * @param MoodleQuickForm $form reference of the form
3116     */
3117    function startForm(&$form){
3118        global $PAGE;
3119        $this->_reqHTML = $form->getReqHTML();
3120        $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
3121        $this->_advancedHTML = $form->getAdvancedHTML();
3122        $this->_collapseButtons = '';
3123        $formid = $form->getAttribute('id');
3124        parent::startForm($form);
3125        if ($form->isFrozen()){
3126            $this->_formTemplate = "\n<div id=\"$formid\" class=\"mform frozen\">\n{collapsebtns}\n{content}\n</div>";
3127        } else {
3128            $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
3129            $this->_hiddenHtml .= $form->_pageparams;
3130        }
3131
3132        if ($form->is_form_change_checker_enabled()) {
3133            $PAGE->requires->yui_module('moodle-core-formchangechecker',
3134                    'M.core_formchangechecker.init',
3135                    array(array(
3136                        'formid' => $formid,
3137                        'initialdirtystate' => $form->is_dirty(),
3138                    ))
3139            );
3140            $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
3141        }
3142        if (!empty($this->_collapsibleElements)) {
3143            if (count($this->_collapsibleElements) > 1) {
3144                $this->_collapseButtons = $this->_collapseButtonsTemplate;
3145                $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
3146            }
3147            $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
3148        }
3149        if (!empty($this->_advancedElements)){
3150            $PAGE->requires->js_call_amd('core_form/showadvanced', 'init', [$formid]);
3151        }
3152    }
3153
3154    /**
3155     * Create advance group of elements
3156     *
3157     * @param MoodleQuickForm_group $group Passed by reference
3158     * @param bool $required if input is required field
3159     * @param string $error error message to display
3160     */
3161    function startGroup(&$group, $required, $error){
3162        global $OUTPUT;
3163
3164        // Make sure the element has an id.
3165        $group->_generateId();
3166
3167        // Prepend 'fgroup_' to the ID we generated.
3168        $groupid = 'fgroup_' . $group->getAttribute('id');
3169
3170        // Update the ID.
3171        $group->updateAttributes(array('id' => $groupid));
3172        $advanced = isset($this->_advancedElements[$group->getName()]);
3173
3174        $html = $OUTPUT->mform_element($group, $required, $advanced, $error, false);
3175        $fromtemplate = !empty($html);
3176        if (!$fromtemplate) {
3177            if (method_exists($group, 'getElementTemplateType')) {
3178                $html = $this->_elementTemplates[$group->getElementTemplateType()];
3179            } else {
3180                $html = $this->_elementTemplates['default'];
3181            }
3182
3183            if (isset($this->_advancedElements[$group->getName()])) {
3184                $html = str_replace(' {advanced}', ' advanced', $html);
3185                $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
3186            } else {
3187                $html = str_replace(' {advanced}', '', $html);
3188                $html = str_replace('{advancedimg}', '', $html);
3189            }
3190            if (method_exists($group, 'getHelpButton')) {
3191                $html = str_replace('{help}', $group->getHelpButton(), $html);
3192            } else {
3193                $html = str_replace('{help}', '', $html);
3194            }
3195            $html = str_replace('{id}', $group->getAttribute('id'), $html);
3196            $html = str_replace('{name}', $group->getName(), $html);
3197            $html = str_replace('{groupname}', 'data-groupname="'.$group->getName().'"', $html);
3198            $html = str_replace('{typeclass}', 'fgroup', $html);
3199            $html = str_replace('{type}', 'group', $html);
3200            $html = str_replace('{class}', $group->getAttribute('class'), $html);
3201            $emptylabel = '';
3202            if ($group->getLabel() == '') {
3203                $emptylabel = 'femptylabel';
3204            }
3205            $html = str_replace('{emptylabel}', $emptylabel, $html);
3206        }
3207        $this->_templates[$group->getName()] = $html;
3208        // Fix for bug in tableless quickforms that didn't allow you to stop a
3209        // fieldset before a group of elements.
3210        // if the element name indicates the end of a fieldset, close the fieldset
3211        if (in_array($group->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
3212            $this->_html .= $this->_closeFieldsetTemplate;
3213            $this->_fieldsetsOpen--;
3214        }
3215        if (!$fromtemplate) {
3216            parent::startGroup($group, $required, $error);
3217        } else {
3218            $this->_html .= $html;
3219        }
3220    }
3221
3222    /**
3223     * Renders element
3224     *
3225     * @param HTML_QuickForm_element $element element
3226     * @param bool $required if input is required field
3227     * @param string $error error message to display
3228     */
3229    function renderElement(&$element, $required, $error){
3230        global $OUTPUT;
3231
3232        // Make sure the element has an id.
3233        $element->_generateId();
3234        $advanced = isset($this->_advancedElements[$element->getName()]);
3235
3236        $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
3237        $fromtemplate = !empty($html);
3238        if (!$fromtemplate) {
3239            // Adding stuff to place holders in template
3240            // check if this is a group element first.
3241            if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3242                // So it gets substitutions for *each* element.
3243                $html = $this->_groupElementTemplate;
3244            } else if (method_exists($element, 'getElementTemplateType')) {
3245                $html = $this->_elementTemplates[$element->getElementTemplateType()];
3246            } else {
3247                $html = $this->_elementTemplates['default'];
3248            }
3249            if (isset($this->_advancedElements[$element->getName()])) {
3250                $html = str_replace(' {advanced}', ' advanced', $html);
3251                $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
3252            } else {
3253                $html = str_replace(' {advanced}', '', $html);
3254                $html = str_replace(' {aria-live}', '', $html);
3255            }
3256            if (isset($this->_advancedElements[$element->getName()]) || $element->getName() == 'mform_showadvanced') {
3257                $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
3258            } else {
3259                $html = str_replace('{advancedimg}', '', $html);
3260            }
3261            $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
3262            $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
3263            $html = str_replace('{type}', $element->getType(), $html);
3264            $html = str_replace('{name}', $element->getName(), $html);
3265            $html = str_replace('{groupname}', '', $html);
3266            $html = str_replace('{class}', $element->getAttribute('class'), $html);
3267            $emptylabel = '';
3268            if ($element->getLabel() == '') {
3269                $emptylabel = 'femptylabel';
3270            }
3271            $html = str_replace('{emptylabel}', $emptylabel, $html);
3272            if (method_exists($element, 'getHelpButton')) {
3273                $html = str_replace('{help}', $element->getHelpButton(), $html);
3274            } else {
3275                $html = str_replace('{help}', '', $html);
3276            }
3277        } else {
3278            if ($this->_inGroup) {
3279                $this->_groupElementTemplate = $html;
3280            }
3281        }
3282        if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3283            $this->_groupElementTemplate = $html;
3284        } else if (!isset($this->_templates[$element->getName()])) {
3285            $this->_templates[$element->getName()] = $html;
3286        }
3287
3288        if (!$fromtemplate) {
3289            parent::renderElement($element, $required, $error);
3290        } else {
3291            if (in_array($element->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
3292                $this->_html .= $this->_closeFieldsetTemplate;
3293                $this->_fieldsetsOpen--;
3294            }
3295            $this->_html .= $html;
3296        }
3297    }
3298
3299    /**
3300     * Called when visiting a form, after processing all form elements
3301     * Adds required note, form attributes, validation javascript and form content.
3302     *
3303     * @global moodle_page $PAGE
3304     * @param moodleform $form Passed by reference
3305     */
3306    function finishForm(&$form){
3307        global $PAGE;
3308        if ($form->isFrozen()){
3309            $this->_hiddenHtml = '';
3310        }
3311        parent::finishForm($form);
3312        $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
3313        if (!$form->isFrozen()) {
3314            $args = $form->getLockOptionObject();
3315            if (count($args[1]) > 0) {
3316                $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
3317            }
3318        }
3319    }
3320   /**
3321    * Called when visiting a header element
3322    *
3323    * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
3324    * @global moodle_page $PAGE
3325    */
3326    function renderHeader(&$header) {
3327        global $PAGE;
3328
3329        $header->_generateId();
3330        $name = $header->getName();
3331
3332        $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
3333        if (is_null($header->_text)) {
3334            $header_html = '';
3335        } elseif (!empty($name) && isset($this->_templates[$name])) {
3336            $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
3337        } else {
3338            $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
3339        }
3340
3341        if ($this->_fieldsetsOpen > 0) {
3342            $this->_html .= $this->_closeFieldsetTemplate;
3343            $this->_fieldsetsOpen--;
3344        }
3345
3346        // Define collapsible classes for fieldsets.
3347        $arialive = '';
3348        $fieldsetclasses = array('clearfix');
3349        if (isset($this->_collapsibleElements[$header->getName()])) {
3350            $fieldsetclasses[] = 'collapsible';
3351            if ($this->_collapsibleElements[$header->getName()]) {
3352                $fieldsetclasses[] = 'collapsed';
3353            }
3354        }
3355
3356        if (isset($this->_advancedElements[$name])){
3357            $fieldsetclasses[] = 'containsadvancedelements';
3358        }
3359
3360        $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
3361        $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
3362
3363        $this->_html .= $openFieldsetTemplate . $header_html;
3364        $this->_fieldsetsOpen++;
3365    }
3366
3367    /**
3368     * Return Array of element names that indicate the end of a fieldset
3369     *
3370     * @return array
3371     */
3372    function getStopFieldsetElements(){
3373        return $this->_stopFieldsetElements;
3374    }
3375}
3376
3377/**
3378 * Required elements validation
3379 *
3380 * This class overrides QuickForm validation since it allowed space or empty tag as a value
3381 *
3382 * @package   core_form
3383 * @category  form
3384 * @copyright 2006 Jamie Pratt <me@jamiep.org>
3385 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3386 */
3387class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
3388    /**
3389     * Checks if an element is not empty.
3390     * This is a server-side validation, it works for both text fields and editor fields
3391     *
3392     * @param string $value Value to check
3393     * @param int|string|array $options Not used yet
3394     * @return bool true if value is not empty
3395     */
3396    function validate($value, $options = null) {
3397        global $CFG;
3398        if (is_array($value) && array_key_exists('text', $value)) {
3399            $value = $value['text'];
3400        }
3401        if (is_array($value)) {
3402            // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
3403            $value = implode('', $value);
3404        }
3405        $stripvalues = array(
3406            '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
3407            '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
3408        );
3409        if (!empty($CFG->strictformsrequired)) {
3410            $value = preg_replace($stripvalues, '', (string)$value);
3411        }
3412        if ((string)$value == '') {
3413            return false;
3414        }
3415        return true;
3416    }
3417
3418    /**
3419     * This function returns Javascript code used to build client-side validation.
3420     * It checks if an element is not empty.
3421     *
3422     * @param int $format format of data which needs to be validated.
3423     * @return array
3424     */
3425    function getValidationScript($format = null) {
3426        global $CFG;
3427        if (!empty($CFG->strictformsrequired)) {
3428            if (!empty($format) && $format == FORMAT_HTML) {
3429                return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
3430            } else {
3431                return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
3432            }
3433        } else {
3434            return array('', "{jsVar} == ''");
3435        }
3436    }
3437}
3438
3439/**
3440 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
3441 * @name $_HTML_QuickForm_default_renderer
3442 */
3443$GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
3444
3445/** Please keep this list in alphabetical order. */
3446MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
3447MoodleQuickForm::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
3448MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
3449MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3450MoodleQuickForm::registerElementType('course', "$CFG->libdir/form/course.php", 'MoodleQuickForm_course');
3451MoodleQuickForm::registerElementType('cohort', "$CFG->libdir/form/cohort.php", 'MoodleQuickForm_cohort');
3452MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
3453MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
3454MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
3455MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
3456MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
3457MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
3458MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
3459MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
3460MoodleQuickForm::registerElementType('filetypes', "$CFG->libdir/form/filetypes.php", 'MoodleQuickForm_filetypes');
3461MoodleQuickForm::registerElementType('float', "$CFG->libdir/form/float.php", 'MoodleQuickForm_float');
3462MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
3463MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
3464MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
3465MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
3466MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
3467MoodleQuickForm::registerElementType('defaultcustom', "$CFG->libdir/form/defaultcustom.php", 'MoodleQuickForm_defaultcustom');
3468MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
3469MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
3470MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
3471MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
3472MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
3473MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
3474MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
3475MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
3476MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
3477MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
3478MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
3479MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
3480MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
3481MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
3482MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
3483MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
3484MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
3485MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
3486
3487MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");
3488