Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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