Merge branch 'master_MDL-78698' of https://github.com/mattporritt/moodle
[moodle.git] / lib / formslib.php
blob2eb2f78bd0def422c1e11e0d9cc029c0e7f5e85e
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.
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/>.
17 /**
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
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.
25 * See examples of use of this library in course/edit.php and course/edit_form.php
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.
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
38 defined('MOODLE_INTERNAL') || die();
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';
46 require_once $CFG->libdir.'/filelib.php';
48 /**
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
53 /**
54 * Callback called when PEAR throws an error
56 * @param PEAR_Error $error
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);
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';
70 /**
71 * Initalize javascript for date type form element
73 * @staticvar bool $done make sure it gets initalize once.
74 * @global moodle_page $PAGE
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;
86 $module = 'moodle-form-dateselector';
87 $function = 'M.form.dateselector.init_date_selectors';
88 $defaulttimezone = date_default_timezone_get();
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)
112 $PAGE->requires->yui_module($module, $function, $config);
117 * Wrapper that separates quickforms syntax from moodle code
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.
123 * You will write your own definition() method which performs the form set up.
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
130 abstract class moodleform {
131 /** @var string name of the form */
132 protected $_formname; // form name
134 /** @var MoodleQuickForm quickform object definition */
135 protected $_form;
137 /** @var mixed globals workaround */
138 protected $_customdata;
140 /** @var array submitted form data when using mforms with ajax */
141 protected $_ajaxformdata;
143 /** @var object definition_after_data executed flag */
144 protected $_definition_finalized = false;
146 /** @var bool|null stores the validation result of this form or null if not yet validated */
147 protected $_validated = null;
150 * The constructor function calls the abstract function definition() and it will then
151 * process and clean and attempt to validate incoming data.
153 * It will call your custom validate method to validate data and will also check any rules
154 * you have specified in definition using addRule
156 * The name of the form (id attribute of the form) is automatically generated depending on
157 * the name you gave the class extending moodleform. You should call your class something
158 * like
160 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
161 * current url. If a moodle_url object then outputs params as hidden variables.
162 * @param mixed $customdata if your form defintion method needs access to data such as $course
163 * $cm, etc. to construct the form definition then pass it in this array. You can
164 * use globals for somethings.
165 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
166 * be merged and used as incoming data to the form.
167 * @param string $target target frame for form submission. You will rarely use this. Don't use
168 * it if you don't need to as the target attribute is deprecated in xhtml strict.
169 * @param mixed $attributes you can pass a string of html attributes here or an array.
170 * Special attribute 'data-random-ids' will randomise generated elements ids. This
171 * is necessary when there are several forms on the same page.
172 * Special attribute 'data-double-submit-protection' set to 'off' will turn off
173 * double-submit protection JavaScript - this may be necessary if your form sends
174 * downloadable files in response to a submit button, and can't call
175 * \core_form\util::form_download_complete();
176 * @param bool $editable
177 * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
179 public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true,
180 $ajaxformdata=null) {
181 global $CFG, $FULLME;
182 // no standard mform in moodle should allow autocomplete with the exception of user signup
183 if (empty($attributes)) {
184 $attributes = array('autocomplete'=>'off');
185 } else if (is_array($attributes)) {
186 $attributes['autocomplete'] = 'off';
187 } else {
188 if (strpos($attributes, 'autocomplete') === false) {
189 $attributes .= ' autocomplete="off" ';
194 if (empty($action)){
195 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
196 $action = strip_querystring($FULLME);
197 if (!empty($CFG->sslproxy)) {
198 // return only https links when using SSL proxy
199 $action = preg_replace('/^http:/', 'https:', $action, 1);
201 //TODO: use following instead of FULLME - see MDL-33015
202 //$action = strip_querystring(qualified_me());
204 // Assign custom data first, so that get_form_identifier can use it.
205 $this->_customdata = $customdata;
206 $this->_formname = $this->get_form_identifier();
207 $this->_ajaxformdata = $ajaxformdata;
209 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes, $ajaxformdata);
210 if (!$editable){
211 $this->_form->hardFreeze();
214 $this->definition();
216 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
217 $this->_form->setType('sesskey', PARAM_RAW);
218 $this->_form->setDefault('sesskey', sesskey());
219 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
220 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
221 $this->_form->setDefault('_qf__'.$this->_formname, 1);
222 $this->_form->_setDefaultRuleMessages();
224 // Hook to inject logic after the definition was provided.
225 $this->after_definition();
227 // we have to know all input types before processing submission ;-)
228 $this->_process_submission($method);
232 * Old syntax of class constructor. Deprecated in PHP7.
234 * @deprecated since Moodle 3.1
236 public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
237 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
238 self::__construct($action, $customdata, $method, $target, $attributes, $editable);
242 * It should returns unique identifier for the form.
243 * Currently it will return class name, but in case two same forms have to be
244 * rendered on same page then override function to get unique form identifier.
245 * e.g This is used on multiple self enrollments page.
247 * @return string form identifier.
249 protected function get_form_identifier() {
250 $class = get_class($this);
252 return preg_replace('/[^a-z0-9_]/i', '_', $class);
256 * To autofocus on first form element or first element with error.
258 * @param string $name if this is set then the focus is forced to a field with this name
259 * @return string javascript to select form element with first error or
260 * first element if no errors. Use this as a parameter
261 * when calling print_header
263 function focus($name=NULL) {
264 $form =& $this->_form;
265 $elkeys = array_keys($form->_elementIndex);
266 $error = false;
267 if (isset($form->_errors) && 0 != count($form->_errors)){
268 $errorkeys = array_keys($form->_errors);
269 $elkeys = array_intersect($elkeys, $errorkeys);
270 $error = true;
273 if ($error or empty($name)) {
274 $names = array();
275 while (empty($names) and !empty($elkeys)) {
276 $el = array_shift($elkeys);
277 $names = $form->_getElNamesRecursive($el);
279 if (!empty($names)) {
280 $name = array_shift($names);
284 $focus = '';
285 if (!empty($name)) {
286 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
289 return $focus;
293 * Internal method. Alters submitted data to be suitable for quickforms processing.
294 * Must be called when the form is fully set up.
296 * @param string $method name of the method which alters submitted data
298 function _process_submission($method) {
299 $submission = array();
300 if (!empty($this->_ajaxformdata)) {
301 $submission = $this->_ajaxformdata;
302 } else if ($method == 'post') {
303 if (!empty($_POST)) {
304 $submission = $_POST;
306 } else {
307 $submission = $_GET;
308 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
311 // following trick is needed to enable proper sesskey checks when using GET forms
312 // the _qf__.$this->_formname serves as a marker that form was actually submitted
313 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
314 if (!confirm_sesskey()) {
315 throw new \moodle_exception('invalidsesskey');
317 $files = $_FILES;
318 } else {
319 $submission = array();
320 $files = array();
322 $this->detectMissingSetType();
324 $this->_form->updateSubmission($submission, $files);
328 * Internal method - should not be used anywhere.
329 * @deprecated since 2.6
330 * @return array $_POST.
332 protected function _get_post_params() {
333 return $_POST;
337 * Internal method. Validates all old-style deprecated uploaded files.
338 * The new way is to upload files via repository api.
340 * @param array $files list of files to be validated
341 * @return bool|array Success or an array of errors
343 function _validate_files(&$files) {
344 global $CFG, $COURSE;
346 $files = array();
348 if (empty($_FILES)) {
349 // we do not need to do any checks because no files were submitted
350 // note: server side rules do not work for files - use custom verification in validate() instead
351 return true;
354 $errors = array();
355 $filenames = array();
357 // now check that we really want each file
358 foreach ($_FILES as $elname=>$file) {
359 $required = $this->_form->isElementRequired($elname);
361 if ($file['error'] == 4 and $file['size'] == 0) {
362 if ($required) {
363 $errors[$elname] = get_string('required');
365 unset($_FILES[$elname]);
366 continue;
369 if (!empty($file['error'])) {
370 $errors[$elname] = file_get_upload_error($file['error']);
371 unset($_FILES[$elname]);
372 continue;
375 if (!is_uploaded_file($file['tmp_name'])) {
376 // TODO: improve error message
377 $errors[$elname] = get_string('error');
378 unset($_FILES[$elname]);
379 continue;
382 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
383 // hmm, this file was not requested
384 unset($_FILES[$elname]);
385 continue;
388 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
390 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
391 if ($filename === '') {
392 // TODO: improve error message - wrong chars
393 $errors[$elname] = get_string('error');
394 unset($_FILES[$elname]);
395 continue;
397 if (in_array($filename, $filenames)) {
398 // TODO: improve error message - duplicate name
399 $errors[$elname] = get_string('error');
400 unset($_FILES[$elname]);
401 continue;
403 $filenames[] = $filename;
404 $_FILES[$elname]['name'] = $filename;
406 $files[$elname] = $_FILES[$elname]['tmp_name'];
409 // return errors if found
410 if (count($errors) == 0){
411 return true;
413 } else {
414 $files = array();
415 return $errors;
420 * Internal method. Validates filepicker and filemanager files if they are
421 * set as required fields. Also, sets the error message if encountered one.
423 * @return bool|array with errors
425 protected function validate_draft_files() {
426 global $USER;
427 $mform =& $this->_form;
429 $errors = array();
430 //Go through all the required elements and make sure you hit filepicker or
431 //filemanager element.
432 foreach ($mform->_rules as $elementname => $rules) {
433 $elementtype = $mform->getElementType($elementname);
434 //If element is of type filepicker then do validation
435 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
436 //Check if rule defined is required rule
437 foreach ($rules as $rule) {
438 if ($rule['type'] == 'required') {
439 $draftid = (int)$mform->getSubmitValue($elementname);
440 $fs = get_file_storage();
441 $context = context_user::instance($USER->id);
442 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
443 $errors[$elementname] = $rule['message'];
449 // Check all the filemanager elements to make sure they do not have too many
450 // files in them.
451 foreach ($mform->_elements as $element) {
452 if ($element->_type == 'filemanager') {
453 $maxfiles = $element->getMaxfiles();
454 if ($maxfiles > 0) {
455 $draftid = (int)$element->getValue();
456 $fs = get_file_storage();
457 $context = context_user::instance($USER->id);
458 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
459 if (count($files) > $maxfiles) {
460 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
465 if (empty($errors)) {
466 return true;
467 } else {
468 return $errors;
473 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
474 * form definition (new entry form); this function is used to load in data where values
475 * already exist and data is being edited (edit entry form).
477 * note: $slashed param removed
479 * @param stdClass|array $default_values object or array of default values
481 function set_data($default_values) {
482 if (is_object($default_values)) {
483 $default_values = (array)$default_values;
485 $this->_form->setDefaults($default_values);
489 * Use this method to indicate that the fieldsets should be shown as expanded
490 * and all other fieldsets should be hidden.
491 * The method is applicable to header elements only.
493 * @param array $shownonly array of header element names
494 * @return void
496 public function filter_shown_headers(array $shownonly): void {
497 $toshow = [];
498 foreach ($shownonly as $show) {
499 if ($this->_form->elementExists($show) && $this->_form->getElementType($show) == 'header') {
500 $toshow[] = $show;
503 $this->_form->filter_shown_headers($toshow);
507 * Check that form was submitted. Does not check validity of submitted data.
509 * @return bool true if form properly submitted
511 function is_submitted() {
512 return $this->_form->isSubmitted();
516 * Checks if button pressed is not for submitting the form
518 * @staticvar bool $nosubmit keeps track of no submit button
519 * @return bool
521 function no_submit_button_pressed(){
522 static $nosubmit = null; // one check is enough
523 if (!is_null($nosubmit)){
524 return $nosubmit;
526 $mform =& $this->_form;
527 $nosubmit = false;
528 if (!$this->is_submitted()){
529 return false;
531 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
532 if ($this->optional_param($nosubmitbutton, 0, PARAM_RAW)) {
533 $nosubmit = true;
534 break;
537 return $nosubmit;
541 * Returns an element of multi-dimensional array given the list of keys
543 * Example:
544 * $array['a']['b']['c'] = 13;
545 * $v = $this->get_array_value_by_keys($array, ['a', 'b', 'c']);
547 * Will result it $v==13
549 * @param array $array
550 * @param array $keys
551 * @return mixed returns null if keys not present
553 protected function get_array_value_by_keys(array $array, array $keys) {
554 $value = $array;
555 foreach ($keys as $key) {
556 if (array_key_exists($key, $value)) {
557 $value = $value[$key];
558 } else {
559 return null;
562 return $value;
566 * Checks if a parameter was passed in the previous form submission
568 * @param string $name the name of the page parameter we want, for example 'id' or 'element[sub][13]'
569 * @param mixed $default the default value to return if nothing is found
570 * @param string $type expected type of parameter
571 * @return mixed
573 public function optional_param($name, $default, $type) {
574 $nameparsed = [];
575 // Convert element name into a sequence of keys, for example 'element[sub][13]' -> ['element', 'sub', '13'].
576 parse_str($name . '=1', $nameparsed);
577 $keys = [];
578 while (is_array($nameparsed)) {
579 $key = key($nameparsed);
580 $keys[] = $key;
581 $nameparsed = $nameparsed[$key];
584 // Search for the element first in $this->_ajaxformdata, then in $_POST and then in $_GET.
585 if (($value = $this->get_array_value_by_keys($this->_ajaxformdata ?? [], $keys)) !== null ||
586 ($value = $this->get_array_value_by_keys($_POST, $keys)) !== null ||
587 ($value = $this->get_array_value_by_keys($_GET, $keys)) !== null) {
588 return $type == PARAM_RAW ? $value : clean_param($value, $type);
591 return $default;
595 * Check that form data is valid.
596 * You should almost always use this, rather than {@link validate_defined_fields}
598 * @return bool true if form data valid
600 function is_validated() {
601 //finalize the form definition before any processing
602 if (!$this->_definition_finalized) {
603 $this->_definition_finalized = true;
604 $this->definition_after_data();
607 return $this->validate_defined_fields();
611 * Validate the form.
613 * You almost always want to call {@link is_validated} instead of this
614 * because it calls {@link definition_after_data} first, before validating the form,
615 * which is what you want in 99% of cases.
617 * This is provided as a separate function for those special cases where
618 * you want the form validated before definition_after_data is called
619 * for example, to selectively add new elements depending on a no_submit_button press,
620 * but only when the form is valid when the no_submit_button is pressed,
622 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
623 * is NOT to validate the form when a no submit button has been pressed.
624 * pass true here to override this behaviour
626 * @return bool true if form data valid
628 function validate_defined_fields($validateonnosubmit=false) {
629 $mform =& $this->_form;
630 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
631 return false;
632 } elseif ($this->_validated === null) {
633 $internal_val = $mform->validate();
635 $files = array();
636 $file_val = $this->_validate_files($files);
637 //check draft files for validation and flag them if required files
638 //are not in draft area.
639 $draftfilevalue = $this->validate_draft_files();
641 if ($file_val !== true && $draftfilevalue !== true) {
642 $file_val = array_merge($file_val, $draftfilevalue);
643 } else if ($draftfilevalue !== true) {
644 $file_val = $draftfilevalue;
645 } //default is file_val, so no need to assign.
647 if ($file_val !== true) {
648 if (!empty($file_val)) {
649 foreach ($file_val as $element=>$msg) {
650 $mform->setElementError($element, $msg);
653 $file_val = false;
656 // Give the elements a chance to perform an implicit validation.
657 $element_val = true;
658 foreach ($mform->_elements as $element) {
659 if (method_exists($element, 'validateSubmitValue')) {
660 $value = $mform->getSubmitValue($element->getName());
661 $result = $element->validateSubmitValue($value);
662 if (!empty($result) && is_string($result)) {
663 $element_val = false;
664 $mform->setElementError($element->getName(), $result);
669 // Let the form instance validate the submitted values.
670 $data = $mform->exportValues();
671 $moodle_val = $this->validation($data, $files);
672 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
673 // non-empty array means errors
674 foreach ($moodle_val as $element=>$msg) {
675 $mform->setElementError($element, $msg);
677 $moodle_val = false;
679 } else {
680 // anything else means validation ok
681 $moodle_val = true;
684 $this->_validated = ($internal_val and $element_val and $moodle_val and $file_val);
686 return $this->_validated;
690 * Return true if a cancel button has been pressed resulting in the form being submitted.
692 * @return bool true if a cancel button has been pressed
694 function is_cancelled(){
695 $mform =& $this->_form;
696 if ($mform->isSubmitted()){
697 foreach ($mform->_cancelButtons as $cancelbutton){
698 if ($this->optional_param($cancelbutton, 0, PARAM_RAW)) {
699 return true;
703 return false;
707 * Return submitted data if properly submitted or returns NULL if validation fails or
708 * if there is no submitted data.
710 * note: $slashed param removed
712 * @return stdClass|null submitted data; NULL if not valid or not submitted or cancelled
714 function get_data() {
715 $mform =& $this->_form;
717 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
718 $data = $mform->exportValues();
719 unset($data['sesskey']); // we do not need to return sesskey
720 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
721 if (empty($data)) {
722 return NULL;
723 } else {
724 return (object)$data;
726 } else {
727 return NULL;
732 * Return submitted data without validation or NULL if there is no submitted data.
733 * note: $slashed param removed
735 * @return stdClass|null submitted data; NULL if not submitted
737 function get_submitted_data() {
738 $mform =& $this->_form;
740 if ($this->is_submitted()) {
741 $data = $mform->exportValues();
742 unset($data['sesskey']); // we do not need to return sesskey
743 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
744 if (empty($data)) {
745 return NULL;
746 } else {
747 return (object)$data;
749 } else {
750 return NULL;
755 * Save verified uploaded files into directory. Upload process can be customised from definition()
757 * @deprecated since Moodle 2.0
758 * @todo MDL-31294 remove this api
759 * @see moodleform::save_stored_file()
760 * @see moodleform::save_file()
761 * @param string $destination path where file should be stored
762 * @return bool Always false
764 function save_files($destination) {
765 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
766 return false;
770 * Returns name of uploaded file.
772 * @param string $elname first element if null
773 * @return string|bool false in case of failure, string if ok
775 function get_new_filename($elname=null) {
776 global $USER;
778 if (!$this->is_submitted() or !$this->is_validated()) {
779 return false;
782 if (is_null($elname)) {
783 if (empty($_FILES)) {
784 return false;
786 reset($_FILES);
787 $elname = key($_FILES);
790 if (empty($elname)) {
791 return false;
794 $element = $this->_form->getElement($elname);
796 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
797 $values = $this->_form->exportValues($elname);
798 if (empty($values[$elname])) {
799 return false;
801 $draftid = $values[$elname];
802 $fs = get_file_storage();
803 $context = context_user::instance($USER->id);
804 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
805 return false;
807 $file = reset($files);
808 return $file->get_filename();
811 if (!isset($_FILES[$elname])) {
812 return false;
815 return $_FILES[$elname]['name'];
819 * Save file to standard filesystem
821 * @param string $elname name of element
822 * @param string $pathname full path name of file
823 * @param bool $override override file if exists
824 * @return bool success
826 function save_file($elname, $pathname, $override=false) {
827 global $USER;
829 if (!$this->is_submitted() or !$this->is_validated()) {
830 return false;
832 if (file_exists($pathname)) {
833 if ($override) {
834 if (!@unlink($pathname)) {
835 return false;
837 } else {
838 return false;
842 $element = $this->_form->getElement($elname);
844 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
845 $values = $this->_form->exportValues($elname);
846 if (empty($values[$elname])) {
847 return false;
849 $draftid = $values[$elname];
850 $fs = get_file_storage();
851 $context = context_user::instance($USER->id);
852 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
853 return false;
855 $file = reset($files);
857 return $file->copy_content_to($pathname);
859 } else if (isset($_FILES[$elname])) {
860 return copy($_FILES[$elname]['tmp_name'], $pathname);
863 return false;
867 * Returns a temporary file, do not forget to delete after not needed any more.
869 * @param string $elname name of the elmenet
870 * @return string|bool either string or false
872 function save_temp_file($elname) {
873 if (!$this->get_new_filename($elname)) {
874 return false;
876 if (!$dir = make_temp_directory('forms')) {
877 return false;
879 if (!$tempfile = tempnam($dir, 'tempup_')) {
880 return false;
882 if (!$this->save_file($elname, $tempfile, true)) {
883 // something went wrong
884 @unlink($tempfile);
885 return false;
888 return $tempfile;
892 * Get draft files of a form element
893 * This is a protected method which will be used only inside moodleforms
895 * @param string $elname name of element
896 * @return array|bool|null
898 protected function get_draft_files($elname) {
899 global $USER;
901 if (!$this->is_submitted()) {
902 return false;
905 $element = $this->_form->getElement($elname);
907 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
908 $values = $this->_form->exportValues($elname);
909 if (empty($values[$elname])) {
910 return false;
912 $draftid = $values[$elname];
913 $fs = get_file_storage();
914 $context = context_user::instance($USER->id);
915 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
916 return null;
918 return $files;
920 return null;
924 * Save file to local filesystem pool
926 * @param string $elname name of element
927 * @param int $newcontextid id of context
928 * @param string $newcomponent name of the component
929 * @param string $newfilearea name of file area
930 * @param int $newitemid item id
931 * @param string $newfilepath path of file where it get stored
932 * @param string $newfilename use specified filename, if not specified name of uploaded file used
933 * @param bool $overwrite overwrite file if exists
934 * @param int $newuserid new userid if required
935 * @return mixed stored_file object or false if error; may throw exception if duplicate found
937 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
938 $newfilename=null, $overwrite=false, $newuserid=null) {
939 global $USER;
941 if (!$this->is_submitted() or !$this->is_validated()) {
942 return false;
945 if (empty($newuserid)) {
946 $newuserid = $USER->id;
949 $element = $this->_form->getElement($elname);
950 $fs = get_file_storage();
952 if ($element instanceof MoodleQuickForm_filepicker) {
953 $values = $this->_form->exportValues($elname);
954 if (empty($values[$elname])) {
955 return false;
957 $draftid = $values[$elname];
958 $context = context_user::instance($USER->id);
959 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
960 return false;
962 $file = reset($files);
963 if (is_null($newfilename)) {
964 $newfilename = $file->get_filename();
967 if ($overwrite) {
968 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
969 if (!$oldfile->delete()) {
970 return false;
975 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
976 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
977 return $fs->create_file_from_storedfile($file_record, $file);
979 } else if (isset($_FILES[$elname])) {
980 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
982 if ($overwrite) {
983 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
984 if (!$oldfile->delete()) {
985 return false;
990 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
991 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
992 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
995 return false;
999 * Get content of uploaded file.
1001 * @param string $elname name of file upload element
1002 * @return string|bool false in case of failure, string if ok
1004 function get_file_content($elname) {
1005 global $USER;
1007 if (!$this->is_submitted() or !$this->is_validated()) {
1008 return false;
1011 $element = $this->_form->getElement($elname);
1013 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
1014 $values = $this->_form->exportValues($elname);
1015 if (empty($values[$elname])) {
1016 return false;
1018 $draftid = $values[$elname];
1019 $fs = get_file_storage();
1020 $context = context_user::instance($USER->id);
1021 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
1022 return false;
1024 $file = reset($files);
1026 return $file->get_content();
1028 } else if (isset($_FILES[$elname])) {
1029 return file_get_contents($_FILES[$elname]['tmp_name']);
1032 return false;
1036 * Print html form.
1038 function display() {
1039 //finalize the form definition if not yet done
1040 if (!$this->_definition_finalized) {
1041 $this->_definition_finalized = true;
1042 $this->definition_after_data();
1045 $this->_form->display();
1049 * Renders the html form (same as display, but returns the result).
1051 * Note that you can only output this rendered result once per page, as
1052 * it contains IDs which must be unique.
1054 * @return string HTML code for the form
1056 public function render() {
1057 ob_start();
1058 $this->display();
1059 $out = ob_get_contents();
1060 ob_end_clean();
1061 return $out;
1065 * Form definition. Abstract method - always override!
1067 protected abstract function definition();
1070 * After definition hook.
1072 * This is useful for intermediate classes to inject logic after the definition was
1073 * provided without requiring developers to call the parent {{@link self::definition()}}
1074 * as it's not obvious by design. The 'intermediate' class is 'MyClass extends
1075 * IntermediateClass extends moodleform'.
1077 * Classes overriding this method should always call the parent. We may not add
1078 * anything specifically in this instance of the method, but intermediate classes
1079 * are likely to do so, and so it is a good practice to always call the parent.
1081 * @return void
1083 protected function after_definition() {
1087 * Dummy stub method - override if you need to setup the form depending on current
1088 * values. This method is called after definition(), data submission and set_data().
1089 * All form setup that is dependent on form values should go in here.
1091 function definition_after_data(){
1095 * Dummy stub method - override if you needed to perform some extra validation.
1096 * If there are errors return array of errors ("fieldname"=>"error message"),
1097 * otherwise true if ok.
1099 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
1101 * @param array $data array of ("fieldname"=>value) of submitted data
1102 * @param array $files array of uploaded files "element_name"=>tmp_file_path
1103 * @return array of "element_name"=>"error_description" if there are errors,
1104 * or an empty array if everything is OK (true allowed for backwards compatibility too).
1106 function validation($data, $files) {
1107 return array();
1111 * Helper used by {@link repeat_elements()}.
1113 * @param int $i the index of this element.
1114 * @param HTML_QuickForm_element $elementclone
1115 * @param array $namecloned array of names
1117 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1118 $name = $elementclone->getName();
1119 $namecloned[] = $name;
1121 if (!empty($name)) {
1122 $elementclone->setName($name."[$i]");
1125 if (is_a($elementclone, 'HTML_QuickForm_header')) {
1126 $value = $elementclone->_text;
1127 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1129 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1130 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1132 } else {
1133 $value=$elementclone->getLabel();
1134 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1139 * Method to add a repeating group of elements to a form.
1141 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1142 * @param int $repeats no of times to repeat elements initially
1143 * @param array $options a nested array. The first array key is the element name.
1144 * the second array key is the type of option to set, and depend on that option,
1145 * the value takes different forms.
1146 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1147 * 'type' - PARAM_* type.
1148 * 'helpbutton' - array containing the helpbutton params.
1149 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1150 * 'rule' - array containing the addRule arguments after the element name.
1151 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1152 * 'advanced' - whether this element is hidden by 'Show more ...'.
1153 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1154 * @param string $addfieldsname name for button to add more fields
1155 * @param int $addfieldsno how many fields to add at a time
1156 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1157 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1158 * @param string $deletebuttonname if specified, treats the no-submit button with this name as a "delete element" button
1159 * in each of the elements
1160 * @return int no of repeats of element in this page
1162 public function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1163 $addfieldsname, $addfieldsno = 5, $addstring = null, $addbuttoninside = false,
1164 $deletebuttonname = '') {
1165 if ($addstring === null) {
1166 $addstring = get_string('addfields', 'form', $addfieldsno);
1167 } else {
1168 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1170 $repeats = $this->optional_param($repeathiddenname, $repeats, PARAM_INT);
1171 $addfields = $this->optional_param($addfieldsname, '', PARAM_TEXT);
1172 $oldrepeats = $repeats;
1173 if (!empty($addfields)){
1174 $repeats += $addfieldsno;
1176 $mform =& $this->_form;
1177 $mform->registerNoSubmitButton($addfieldsname);
1178 $mform->addElement('hidden', $repeathiddenname, $repeats);
1179 $mform->setType($repeathiddenname, PARAM_INT);
1180 //value not to be overridden by submitted value
1181 $mform->setConstants(array($repeathiddenname=>$repeats));
1182 $namecloned = array();
1183 $no = 1;
1184 for ($i = 0; $i < $repeats; $i++) {
1185 if ($deletebuttonname) {
1186 $mform->registerNoSubmitButton($deletebuttonname . "[$i]");
1187 $isdeleted = $this->optional_param($deletebuttonname . "[$i]", false, PARAM_RAW) ||
1188 $this->optional_param($deletebuttonname . "-hidden[$i]", false, PARAM_RAW);
1189 if ($isdeleted) {
1190 $mform->addElement('hidden', $deletebuttonname . "-hidden[$i]", 1);
1191 $mform->setType($deletebuttonname . "-hidden[$i]", PARAM_INT);
1192 continue;
1195 foreach ($elementobjs as $elementobj){
1196 $elementclone = fullclone($elementobj);
1197 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1199 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1200 foreach ($elementclone->getElements() as $el) {
1201 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1203 $elementclone->setLabel(str_replace('{no}', $no, $elementclone->getLabel()));
1204 } else if ($elementobj instanceof \HTML_QuickForm_submit && $elementobj->getName() == $deletebuttonname) {
1205 // Mark the "Delete" button as no-submit.
1206 $onclick = $elementclone->getAttribute('onclick');
1207 $skip = 'skipClientValidation = true;';
1208 $onclick = ($onclick !== null) ? $skip . ' ' . $onclick : $skip;
1209 $elementclone->updateAttributes(['data-skip-validation' => 1, 'data-no-submit' => 1, 'onclick' => $onclick]);
1212 // Mark newly created elements, so they know not to look for any submitted data.
1213 if ($i >= $oldrepeats) {
1214 $mform->note_new_repeat($elementclone->getName());
1217 $mform->addElement($elementclone);
1218 $no++;
1221 for ($i=0; $i<$repeats; $i++) {
1222 foreach ($options as $elementname => $elementoptions){
1223 $pos=strpos($elementname, '[');
1224 if ($pos!==FALSE){
1225 $realelementname = substr($elementname, 0, $pos)."[$i]";
1226 $realelementname .= substr($elementname, $pos);
1227 }else {
1228 $realelementname = $elementname."[$i]";
1230 foreach ($elementoptions as $option => $params){
1232 switch ($option){
1233 case 'default' :
1234 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1235 break;
1236 case 'helpbutton' :
1237 $params = array_merge(array($realelementname), $params);
1238 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1239 break;
1240 case 'disabledif' :
1241 case 'hideif' :
1242 $pos = strpos($params[0], '[');
1243 $ending = '';
1244 if ($pos !== false) {
1245 $ending = substr($params[0], $pos);
1246 $params[0] = substr($params[0], 0, $pos);
1248 foreach ($namecloned as $num => $name){
1249 if ($params[0] == $name){
1250 $params[0] = $params[0] . "[$i]" . $ending;
1251 break;
1254 $params = array_merge(array($realelementname), $params);
1255 $function = ($option === 'disabledif') ? 'disabledIf' : 'hideIf';
1256 call_user_func_array(array(&$mform, $function), $params);
1257 break;
1258 case 'rule' :
1259 if (is_string($params)){
1260 $params = array(null, $params, null, 'client');
1262 $params = array_merge(array($realelementname), $params);
1263 call_user_func_array(array(&$mform, 'addRule'), $params);
1264 break;
1266 case 'type':
1267 $mform->setType($realelementname, $params);
1268 break;
1270 case 'expanded':
1271 $mform->setExpanded($realelementname, $params);
1272 break;
1274 case 'advanced' :
1275 $mform->setAdvanced($realelementname, $params);
1276 break;
1281 $mform->addElement('submit', $addfieldsname, $addstring, [], false);
1283 if (!$addbuttoninside) {
1284 $mform->closeHeaderBefore($addfieldsname);
1287 return $repeats;
1291 * Adds a link/button that controls the checked state of a group of checkboxes.
1293 * @param int $groupid The id of the group of advcheckboxes this element controls
1294 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1295 * @param array $attributes associative array of HTML attributes
1296 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1298 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1299 global $CFG, $PAGE;
1301 // Name of the controller button
1302 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1303 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1304 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1306 // Set the default text if none was specified
1307 if (empty($text)) {
1308 $text = get_string('selectallornone', 'form');
1311 $mform = $this->_form;
1312 $selectvalue = $this->optional_param($checkboxcontrollerparam, null, PARAM_INT);
1313 $contollerbutton = $this->optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1315 $newselectvalue = $selectvalue;
1316 if (is_null($selectvalue)) {
1317 $newselectvalue = $originalValue;
1318 } else if (!is_null($contollerbutton)) {
1319 $newselectvalue = (int) !$selectvalue;
1321 // set checkbox state depending on orignal/submitted value by controoler button
1322 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1323 foreach ($mform->_elements as $element) {
1324 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1325 $element->getAttribute('class') == $checkboxgroupclass &&
1326 !$element->isFrozen()) {
1327 $mform->setConstants(array($element->getName() => $newselectvalue));
1332 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1333 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1334 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1336 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1337 array(
1338 array('groupid' => $groupid,
1339 'checkboxclass' => $checkboxgroupclass,
1340 'checkboxcontroller' => $checkboxcontrollerparam,
1341 'controllerbutton' => $checkboxcontrollername)
1345 require_once("$CFG->libdir/form/submit.php");
1346 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1347 $mform->addElement($submitlink);
1348 $mform->registerNoSubmitButton($checkboxcontrollername);
1349 $mform->setDefault($checkboxcontrollername, $text);
1353 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1354 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1355 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1356 * get data with get_data().
1358 * @param bool $cancel whether to show cancel button, default true
1359 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1361 public function add_action_buttons($cancel = true, $submitlabel = null) {
1362 if (is_null($submitlabel)){
1363 $submitlabel = get_string('savechanges');
1365 $mform =& $this->_form;
1366 if ($cancel){
1367 //when two elements we need a group
1368 $buttonarray=array();
1369 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1370 $buttonarray[] = &$mform->createElement('cancel');
1371 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1372 $mform->closeHeaderBefore('buttonar');
1373 } else {
1374 //no group needed
1375 $mform->addElement('submit', 'submitbutton', $submitlabel);
1376 $mform->closeHeaderBefore('submitbutton');
1381 * Use this method to make a sticky submit/cancel button at the end of your form.
1383 * @param bool $cancel whether to show cancel button, default true
1384 * @param string|null $submitlabel label for submit button, defaults to get_string('savechanges')
1386 public function add_sticky_action_buttons(bool $cancel = true, ?string $submitlabel = null): void {
1387 $this->add_action_buttons($cancel, $submitlabel);
1388 if ($cancel) {
1389 $this->_form->set_sticky_footer('buttonar');
1390 } else {
1391 $this->_form->set_sticky_footer('submitbutton');
1396 * Adds an initialisation call for a standard JavaScript enhancement.
1398 * This function is designed to add an initialisation call for a JavaScript
1399 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1401 * Current options:
1402 * - Selectboxes
1403 * - smartselect: Turns a nbsp indented select box into a custom drop down
1404 * control that supports multilevel and category selection.
1405 * $enhancement = 'smartselect';
1406 * $options = array('selectablecategories' => true|false)
1408 * @param string|element $element form element for which Javascript needs to be initalized
1409 * @param string $enhancement which init function should be called
1410 * @param array $options options passed to javascript
1411 * @param array $strings strings for javascript
1412 * @deprecated since Moodle 3.3 MDL-57471
1414 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1415 debugging('$mform->init_javascript_enhancement() is deprecated and no longer does anything. '.
1416 'smartselect uses should be converted to the searchableselector form element.', DEBUG_DEVELOPER);
1420 * Returns a JS module definition for the mforms JS
1422 * @return array
1424 public static function get_js_module() {
1425 global $CFG;
1426 return array(
1427 'name' => 'mform',
1428 'fullpath' => '/lib/form/form.js',
1429 'requires' => array('base', 'node')
1434 * Detects elements with missing setType() declerations.
1436 * Finds elements in the form which should a PARAM_ type set and throws a
1437 * developer debug warning for any elements without it. This is to reduce the
1438 * risk of potential security issues by developers mistakenly forgetting to set
1439 * the type.
1441 * @return void
1443 private function detectMissingSetType() {
1444 global $CFG;
1446 if (!$CFG->debugdeveloper) {
1447 // Only for devs.
1448 return;
1451 $mform = $this->_form;
1452 foreach ($mform->_elements as $element) {
1453 $group = false;
1454 $elements = array($element);
1456 if ($element->getType() == 'group') {
1457 $group = $element;
1458 $elements = $element->getElements();
1461 foreach ($elements as $index => $element) {
1462 switch ($element->getType()) {
1463 case 'hidden':
1464 case 'text':
1465 case 'url':
1466 if ($group) {
1467 $name = $group->getElementName($index);
1468 } else {
1469 $name = $element->getName();
1471 $key = $name;
1472 $found = array_key_exists($key, $mform->_types);
1473 // For repeated elements we need to look for
1474 // the "main" type, not for the one present
1475 // on each repetition. All the stuff in formslib
1476 // (repeat_elements(), updateSubmission()... seems
1477 // to work that way.
1478 while (!$found && strrpos($key, '[') !== false) {
1479 $pos = strrpos($key, '[');
1480 $key = substr($key, 0, $pos);
1481 $found = array_key_exists($key, $mform->_types);
1483 if (!$found) {
1484 debugging("Did you remember to call setType() for '$name'? ".
1485 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1487 break;
1494 * Used by tests to simulate submitted form data submission from the user.
1496 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1497 * get_data.
1499 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1500 * global arrays after each test.
1502 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1503 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1504 * @param string $method 'post' or 'get', defaults to 'post'.
1505 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1506 * a different value here for some forms that are used more than once on the
1507 * same page.
1509 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1510 $formidentifier = null) {
1511 $_FILES = $simulatedsubmittedfiles;
1512 if ($formidentifier === null) {
1513 $formidentifier = get_called_class();
1514 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1516 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1517 $simulatedsubmitteddata['sesskey'] = sesskey();
1518 if (strtolower($method) === 'get') {
1519 $_GET = $simulatedsubmitteddata;
1520 } else {
1521 $_POST = $simulatedsubmitteddata;
1526 * Used by tests to simulate submitted form data submission via AJAX.
1528 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1529 * get_data.
1531 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1532 * global arrays after each test.
1534 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1535 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1536 * @param string $method 'post' or 'get', defaults to 'post'.
1537 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1538 * a different value here for some forms that are used more than once on the
1539 * same page.
1540 * @return array array to pass to form constructor as $ajaxdata
1542 public static function mock_ajax_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1543 $formidentifier = null) {
1544 $_FILES = $simulatedsubmittedfiles;
1545 if ($formidentifier === null) {
1546 $formidentifier = get_called_class();
1547 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1549 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1550 $simulatedsubmitteddata['sesskey'] = sesskey();
1551 if (strtolower($method) === 'get') {
1552 $_GET = ['sesskey' => sesskey()];
1553 } else {
1554 $_POST = ['sesskey' => sesskey()];
1556 return $simulatedsubmitteddata;
1560 * Used by tests to generate valid submit keys for moodle forms that are
1561 * submitted with ajax data.
1563 * @throws \moodle_exception If called outside unit test environment
1564 * @param array $data Existing form data you wish to add the keys to.
1565 * @return array
1567 public static function mock_generate_submit_keys($data = []) {
1568 if (!defined('PHPUNIT_TEST') || !PHPUNIT_TEST) {
1569 throw new \moodle_exception("This function can only be used for unit testing.");
1572 $formidentifier = get_called_class();
1573 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1574 $data['sesskey'] = sesskey();
1575 $data['_qf__' . $formidentifier] = 1;
1577 return $data;
1581 * Set display mode for the form when labels take full width of the form and above the elements even on big screens
1583 * Useful for forms displayed inside modals or in narrow containers
1585 public function set_display_vertical() {
1586 $oldclass = $this->_form->getAttribute('class');
1587 $this->_form->updateAttributes(array('class' => $oldclass . ' full-width-labels'));
1591 * Set the initial 'dirty' state of the form.
1593 * @param bool $state
1594 * @since Moodle 3.7.1
1596 public function set_initial_dirty_state($state = false) {
1597 $this->_form->set_initial_dirty_state($state);
1602 * MoodleQuickForm implementation
1604 * You never extend this class directly. The class methods of this class are available from
1605 * the private $this->_form property on moodleform and its children. You generally only
1606 * call methods on this class from within abstract methods that you override on moodleform such
1607 * as definition and definition_after_data
1609 * @package core_form
1610 * @category form
1611 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1612 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1614 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1615 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1616 var $_types = array();
1618 /** @var array dependent state for the element/'s */
1619 var $_dependencies = array();
1622 * @var array elements that will become hidden based on another element
1624 protected $_hideifs = array();
1626 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1627 var $_noSubmitButtons=array();
1629 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1630 var $_cancelButtons=array();
1632 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1633 var $_advancedElements = array();
1636 * The form element to render in the sticky footer, if any.
1637 * @var string|null $_stickyfooterelement
1639 protected $_stickyfooterelement = null;
1642 * Array whose keys are element names and values are the desired collapsible state.
1643 * True for collapsed, False for expanded. If not present, set to default in
1644 * {@link self::accept()}.
1646 * @var array
1648 var $_collapsibleElements = array();
1651 * Whether to enable shortforms for this form
1653 * @var boolean
1655 var $_disableShortforms = false;
1658 * Array whose keys are the only elements to be shown.
1659 * Rest of the elements that are not in this array will be hidden.
1661 * @var array
1663 protected $_shownonlyelements = [];
1665 /** @var bool whether to automatically initialise the form change detector this form. */
1666 protected $_use_form_change_checker = true;
1669 * The initial state of the dirty state.
1671 * @var bool
1673 protected $_initial_form_dirty_state = false;
1676 * The form name is derived from the class name of the wrapper minus the trailing form
1677 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1678 * @var string
1680 var $_formName = '';
1683 * String with the html for hidden params passed in as part of a moodle_url
1684 * object for the action. Output in the form.
1685 * @var string
1687 var $_pageparams = '';
1689 /** @var array names of new repeating elements that should not expect to find submitted data */
1690 protected $_newrepeats = array();
1692 /** @var array $_ajaxformdata submitted form data when using mforms with ajax */
1693 protected $_ajaxformdata;
1696 * Whether the form contains any client-side validation or not.
1697 * @var bool
1699 protected $clientvalidation = false;
1702 * Is this a 'disableIf' dependency ?
1704 const DEP_DISABLE = 0;
1707 * Is this a 'hideIf' dependency?
1709 const DEP_HIDE = 1;
1711 /** @var string request class HTML. */
1712 protected $_reqHTML;
1714 /** @var string advanced class HTML. */
1715 protected $_advancedHTML;
1718 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1720 * @staticvar int $formcounter counts number of forms
1721 * @param string $formName Form's name.
1722 * @param string $method Form's method defaults to 'POST'
1723 * @param string|moodle_url $action Form's action
1724 * @param string $target (optional)Form's target defaults to none
1725 * @param mixed $attributes (optional)Extra attributes for <form> tag
1726 * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
1728 public function __construct($formName, $method, $action, $target = '', $attributes = null, $ajaxformdata = null) {
1729 global $CFG, $OUTPUT;
1731 static $formcounter = 1;
1733 // TODO MDL-52313 Replace with the call to parent::__construct().
1734 HTML_Common::__construct($attributes);
1735 $target = empty($target) ? array() : array('target' => $target);
1736 $this->_formName = $formName;
1737 if (is_a($action, 'moodle_url')){
1738 $this->_pageparams = html_writer::input_hidden_params($action);
1739 $action = $action->out_omit_querystring();
1740 } else {
1741 $this->_pageparams = '';
1743 // No 'name' atttribute for form in xhtml strict :
1744 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1745 if (is_null($this->getAttribute('id'))) {
1746 // Append a random id, forms can be loaded in different requests using Fragments API.
1747 $attributes['id'] = 'mform' . $formcounter . '_' . random_string();
1749 $formcounter++;
1750 $this->updateAttributes($attributes);
1752 // This is custom stuff for Moodle :
1753 $this->_ajaxformdata = $ajaxformdata;
1754 $oldclass= $this->getAttribute('class');
1755 if (!empty($oldclass)){
1756 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1757 }else {
1758 $this->updateAttributes(array('class'=>'mform'));
1760 $this->_reqHTML = '<span class="req">' . $OUTPUT->pix_icon('req', get_string('requiredelement', 'form')) . '</span>';
1761 $this->_advancedHTML = '<span class="adv">' . $OUTPUT->pix_icon('adv', get_string('advancedelement', 'form')) . '</span>';
1762 $this->setRequiredNote(get_string('somefieldsrequired', 'form', $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'))));
1766 * Old syntax of class constructor. Deprecated in PHP7.
1768 * @deprecated since Moodle 3.1
1770 public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1771 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1772 self::__construct($formName, $method, $action, $target, $attributes);
1776 * Use this method to indicate an element in a form is an advanced field. If items in a form
1777 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1778 * form so the user can decide whether to display advanced form controls.
1780 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1782 * @param string $elementName group or element name (not the element name of something inside a group).
1783 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1785 function setAdvanced($elementName, $advanced = true) {
1786 if ($advanced){
1787 $this->_advancedElements[$elementName]='';
1788 } elseif (isset($this->_advancedElements[$elementName])) {
1789 unset($this->_advancedElements[$elementName]);
1794 * Use this method to indicate an element to display as a sticky footer.
1796 * Only one page element can be displayed in the sticky footer. To render
1797 * more than one element use addGroup to create a named group.
1799 * @param string|null $elementname group or element name (not the element name of something inside a group).
1801 public function set_sticky_footer(?string $elementname): void {
1802 $this->_stickyfooterelement = $elementname;
1806 * Checks if a parameter was passed in the previous form submission
1808 * @param string $name the name of the page parameter we want
1809 * @param mixed $default the default value to return if nothing is found
1810 * @param string $type expected type of parameter
1811 * @return mixed
1813 public function optional_param($name, $default, $type) {
1814 if (isset($this->_ajaxformdata[$name])) {
1815 return clean_param($this->_ajaxformdata[$name], $type);
1816 } else {
1817 return optional_param($name, $default, $type);
1822 * Use this method to indicate that the fieldset should be shown as expanded.
1823 * The method is applicable to header elements only.
1825 * @param string $headername header element name
1826 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1827 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1828 * the form was submitted.
1829 * @return void
1831 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1832 if (empty($headername)) {
1833 return;
1835 $element = $this->getElement($headername);
1836 if ($element->getType() != 'header') {
1837 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1838 return;
1840 if (!$headerid = $element->getAttribute('id')) {
1841 $element->_generateId();
1842 $headerid = $element->getAttribute('id');
1844 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1845 // See if the form has been submitted already.
1846 $formexpanded = $this->optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1847 if (!$ignoreuserstate && $formexpanded != -1) {
1848 // Override expanded state with the form variable.
1849 $expanded = $formexpanded;
1851 // Create the form element for storing expanded state.
1852 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1853 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1854 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1856 $this->_collapsibleElements[$headername] = !$expanded;
1860 * Use this method to indicate that the fieldsets should be shown and expanded
1861 * and all other fieldsets should be hidden.
1862 * The method is applicable to header elements only.
1864 * @param array $shownonly array of header element names
1865 * @return void
1867 public function filter_shown_headers(array $shownonly): void {
1868 $this->_shownonlyelements = [];
1869 if (empty($shownonly)) {
1870 return;
1872 foreach ($shownonly as $headername) {
1873 $element = $this->getElement($headername);
1874 if ($element->getType() == 'header') {
1875 $this->_shownonlyelements[] = $headername;
1876 $this->setExpanded($headername);
1882 * Use this method to check if the fieldsets could be shown.
1883 * The method is applicable to header elements only.
1885 * @param string $headername header element name to check in the shown only elements array.
1886 * @return void
1888 public function is_shown(string $headername): bool {
1889 if (empty($headername)) {
1890 return true;
1892 if (empty($this->_shownonlyelements)) {
1893 return true;
1895 return in_array($headername, $this->_shownonlyelements);
1899 * Use this method to add show more/less status element required for passing
1900 * over the advanced elements visibility status on the form submission.
1902 * @param string $headerName header element name.
1903 * @param boolean $showmore default false sets the advanced elements to be hidden.
1905 function addAdvancedStatusElement($headerid, $showmore=false){
1906 // Add extra hidden element to store advanced items state for each section.
1907 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1908 // See if we the form has been submitted already.
1909 $formshowmore = $this->optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1910 if (!$showmore && $formshowmore != -1) {
1911 // Override showmore state with the form variable.
1912 $showmore = $formshowmore;
1914 // Create the form element for storing advanced items state.
1915 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1916 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1917 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1922 * This function has been deprecated. Show advanced has been replaced by
1923 * "Show more.../Show less..." in the shortforms javascript module.
1925 * @deprecated since Moodle 2.5
1926 * @param bool $showadvancedNow if true will show advanced elements.
1928 function setShowAdvanced($showadvancedNow = null){
1929 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1933 * This function has been deprecated. Show advanced has been replaced by
1934 * "Show more.../Show less..." in the shortforms javascript module.
1936 * @deprecated since Moodle 2.5
1937 * @return bool (Always false)
1939 function getShowAdvanced(){
1940 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1941 return false;
1945 * Use this method to indicate that the form will not be using shortforms.
1947 * @param boolean $disable default true, controls if the shortforms are disabled.
1949 function setDisableShortforms ($disable = true) {
1950 $this->_disableShortforms = $disable;
1954 * Set the initial 'dirty' state of the form.
1956 * @param bool $state
1957 * @since Moodle 3.7.1
1959 public function set_initial_dirty_state($state = false) {
1960 $this->_initial_form_dirty_state = $state;
1964 * Is the form currently set to dirty?
1966 * @return boolean Initial dirty state.
1967 * @since Moodle 3.7.1
1969 public function is_dirty() {
1970 return $this->_initial_form_dirty_state;
1974 * Call this method if you don't want the formchangechecker JavaScript to be
1975 * automatically initialised for this form.
1977 public function disable_form_change_checker() {
1978 $this->_use_form_change_checker = false;
1982 * If you have called {@link disable_form_change_checker()} then you can use
1983 * this method to re-enable it. It is enabled by default, so normally you don't
1984 * need to call this.
1986 public function enable_form_change_checker() {
1987 $this->_use_form_change_checker = true;
1991 * @return bool whether this form should automatically initialise
1992 * formchangechecker for itself.
1994 public function is_form_change_checker_enabled() {
1995 return $this->_use_form_change_checker;
1999 * Accepts a renderer
2001 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
2003 function accept(&$renderer) {
2004 if (method_exists($renderer, 'setAdvancedElements')){
2005 //Check for visible fieldsets where all elements are advanced
2006 //and mark these headers as advanced as well.
2007 //Also mark all elements in a advanced header as advanced.
2008 $stopFields = $renderer->getStopFieldSetElements();
2009 $lastHeader = null;
2010 $lastHeaderAdvanced = false;
2011 $anyAdvanced = false;
2012 $anyError = false;
2013 foreach (array_keys($this->_elements) as $elementIndex){
2014 $element =& $this->_elements[$elementIndex];
2016 // if closing header and any contained element was advanced then mark it as advanced
2017 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
2018 if ($anyAdvanced && !is_null($lastHeader)) {
2019 $lastHeader->_generateId();
2020 $this->setAdvanced($lastHeader->getName());
2021 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
2023 $lastHeaderAdvanced = false;
2024 unset($lastHeader);
2025 $lastHeader = null;
2026 } elseif ($lastHeaderAdvanced) {
2027 $this->setAdvanced($element->getName());
2030 if ($element->getType()=='header'){
2031 $lastHeader =& $element;
2032 $anyAdvanced = false;
2033 $anyError = false;
2034 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
2035 } elseif (isset($this->_advancedElements[$element->getName()])){
2036 $anyAdvanced = true;
2037 if (isset($this->_errors[$element->getName()])) {
2038 $anyError = true;
2042 // the last header may not be closed yet...
2043 if ($anyAdvanced && !is_null($lastHeader)){
2044 $this->setAdvanced($lastHeader->getName());
2045 $lastHeader->_generateId();
2046 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
2048 $renderer->setAdvancedElements($this->_advancedElements);
2050 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
2052 // Count the number of sections.
2053 $headerscount = 0;
2054 foreach (array_keys($this->_elements) as $elementIndex){
2055 $element =& $this->_elements[$elementIndex];
2056 if ($element->getType() == 'header') {
2057 $headerscount++;
2061 $anyrequiredorerror = false;
2062 $headercounter = 0;
2063 $headername = null;
2064 foreach (array_keys($this->_elements) as $elementIndex){
2065 $element =& $this->_elements[$elementIndex];
2067 if ($element->getType() == 'header') {
2068 $headercounter++;
2069 $element->_generateId();
2070 $headername = $element->getName();
2071 $anyrequiredorerror = false;
2072 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
2073 $anyrequiredorerror = true;
2074 } else {
2075 // Do not reset $anyrequiredorerror to false because we do not want any other element
2076 // in this header (fieldset) to possibly revert the state given.
2079 if ($element->getType() == 'header') {
2080 if (!$this->is_shown($headername)) {
2081 $this->setExpanded($headername, false);
2082 continue;
2084 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
2085 // By default the first section is always expanded, except if a state has already been set.
2086 $this->setExpanded($headername, true);
2087 } else if (
2088 ($headercounter === 2 && $headerscount === 2)
2089 && !isset($this->_collapsibleElements[$headername])
2091 // The second section is always expanded if the form only contains 2 sections),
2092 // except if a state has already been set.
2093 $this->setExpanded($headername, true);
2095 } else if ($anyrequiredorerror && (empty($headername) || $this->is_shown($headername))) {
2096 // If any error or required field are present within the header, we need to expand it.
2097 $this->setExpanded($headername, true, true);
2098 } else if (!isset($this->_collapsibleElements[$headername])) {
2099 // Define element as collapsed by default.
2100 $this->setExpanded($headername, false);
2104 // Pass the array to renderer object.
2105 $renderer->setCollapsibleElements($this->_collapsibleElements);
2108 $this->accept_set_nonvisible_elements($renderer);
2110 if (method_exists($renderer, 'set_sticky_footer') && !empty($this->_stickyfooterelement)) {
2111 $renderer->set_sticky_footer($this->_stickyfooterelement);
2113 parent::accept($renderer);
2117 * Checking non-visible elements to set when accepting a renderer.
2118 * @param HTML_QuickForm_Renderer $renderer
2120 private function accept_set_nonvisible_elements($renderer) {
2121 if (!method_exists($renderer, 'set_nonvisible_elements') || $this->_disableShortforms) {
2122 return;
2124 $nonvisibles = [];
2125 foreach (array_keys($this->_elements) as $index) {
2126 $element =& $this->_elements[$index];
2127 if ($element->getType() != 'header') {
2128 continue;
2130 $headername = $element->getName();
2131 if (!$this->is_shown($headername)) {
2132 $nonvisibles[] = $headername;
2135 // Pass the array to renderer object.
2136 $renderer->set_nonvisible_elements($nonvisibles);
2140 * Adds one or more element names that indicate the end of a fieldset
2142 * @param string $elementName name of the element
2144 function closeHeaderBefore($elementName){
2145 $renderer =& $this->defaultRenderer();
2146 $renderer->addStopFieldsetElements($elementName);
2150 * Set an element to be forced to flow LTR.
2152 * The element must exist and support this functionality. Also note that
2153 * when setting the type of a field (@link self::setType} we try to guess the
2154 * whether the field should be force to LTR or not. Make sure you're always
2155 * calling this method last.
2157 * @param string $elementname The element name.
2158 * @param bool $value When false, disables force LTR, else enables it.
2160 public function setForceLtr($elementname, $value = true) {
2161 $this->getElement($elementname)->set_force_ltr($value);
2165 * Should be used for all elements of a form except for select, radio and checkboxes which
2166 * clean their own data.
2168 * @param string $elementname
2169 * @param string $paramtype defines type of data contained in element. Use the constants PARAM_*.
2170 * {@link lib/moodlelib.php} for defined parameter types
2172 function setType($elementname, $paramtype) {
2173 $this->_types[$elementname] = $paramtype;
2175 // This will not always get it right, but it should be accurate in most cases.
2176 // When inaccurate use setForceLtr().
2177 if (!is_rtl_compatible($paramtype)
2178 && $this->elementExists($elementname)
2179 && ($element =& $this->getElement($elementname))
2180 && method_exists($element, 'set_force_ltr')) {
2182 $element->set_force_ltr(true);
2187 * This can be used to set several types at once.
2189 * @param array $paramtypes types of parameters.
2190 * @see MoodleQuickForm::setType
2192 function setTypes($paramtypes) {
2193 foreach ($paramtypes as $elementname => $paramtype) {
2194 $this->setType($elementname, $paramtype);
2199 * Return the type(s) to use to clean an element.
2201 * In the case where the element has an array as a value, we will try to obtain a
2202 * type defined for that specific key, and recursively until done.
2204 * This method does not work reverse, you cannot pass a nested element and hoping to
2205 * fallback on the clean type of a parent. This method intends to be used with the
2206 * main element, which will generate child types if needed, not the other way around.
2208 * Example scenario:
2210 * You have defined a new repeated element containing a text field called 'foo'.
2211 * By default there will always be 2 occurence of 'foo' in the form. Even though
2212 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
2213 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
2214 * $mform->setType('foo[0]', PARAM_FLOAT).
2216 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
2217 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
2218 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
2219 * get the default clean type returned (param $default).
2221 * @param string $elementname name of the element.
2222 * @param mixed $value value that should be cleaned.
2223 * @param int $default default constant value to be returned (PARAM_...)
2224 * @return string|array constant value or array of constant values (PARAM_...)
2226 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
2227 $type = $default;
2228 if (array_key_exists($elementname, $this->_types)) {
2229 $type = $this->_types[$elementname];
2231 if (is_array($value)) {
2232 $default = $type;
2233 $type = array();
2234 foreach ($value as $subkey => $subvalue) {
2235 $typekey = "$elementname" . "[$subkey]";
2236 if (array_key_exists($typekey, $this->_types)) {
2237 $subtype = $this->_types[$typekey];
2238 } else {
2239 $subtype = $default;
2241 if (is_array($subvalue)) {
2242 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
2243 } else {
2244 $type[$subkey] = $subtype;
2248 return $type;
2252 * Return the cleaned value using the passed type(s).
2254 * @param mixed $value value that has to be cleaned.
2255 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
2256 * @return mixed cleaned up value.
2258 public function getCleanedValue($value, $type) {
2259 if (is_array($type) && is_array($value)) {
2260 foreach ($type as $key => $param) {
2261 $value[$key] = $this->getCleanedValue($value[$key], $param);
2263 } else if (!is_array($type) && !is_array($value)) {
2264 $value = clean_param($value, $type);
2265 } else if (!is_array($type) && is_array($value)) {
2266 $value = clean_param_array($value, $type, true);
2267 } else {
2268 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
2270 return $value;
2274 * Updates submitted values
2276 * @param array $submission submitted values
2277 * @param array $files list of files
2279 function updateSubmission($submission, $files) {
2280 $this->_flagSubmitted = false;
2282 if (empty($submission)) {
2283 $this->_submitValues = array();
2284 } else {
2285 foreach ($submission as $key => $s) {
2286 $type = $this->getCleanType($key, $s);
2287 $submission[$key] = $this->getCleanedValue($s, $type);
2289 $this->_submitValues = $submission;
2290 $this->_flagSubmitted = true;
2293 if (empty($files)) {
2294 $this->_submitFiles = array();
2295 } else {
2296 $this->_submitFiles = $files;
2297 $this->_flagSubmitted = true;
2300 // need to tell all elements that they need to update their value attribute.
2301 foreach (array_keys($this->_elements) as $key) {
2302 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
2307 * Returns HTML for required elements
2309 * @return string
2311 function getReqHTML(){
2312 return $this->_reqHTML;
2316 * Returns HTML for advanced elements
2318 * @return string
2320 function getAdvancedHTML(){
2321 return $this->_advancedHTML;
2325 * Initializes a default form value. Used to specify the default for a new entry where
2326 * no data is loaded in using moodleform::set_data()
2328 * note: $slashed param removed
2330 * @param string $elementName element name
2331 * @param mixed $defaultValue values for that element name
2333 function setDefault($elementName, $defaultValue){
2334 $this->setDefaults(array($elementName=>$defaultValue));
2338 * Add a help button to element, only one button per element is allowed.
2340 * This is new, simplified and preferable method of setting a help icon on form elements.
2341 * It uses the new $OUTPUT->help_icon().
2343 * Typically, you will provide the same identifier and the component as you have used for the
2344 * label of the element. The string identifier with the _help suffix added is then used
2345 * as the help string.
2347 * There has to be two strings defined:
2348 * 1/ get_string($identifier, $component) - the title of the help page
2349 * 2/ get_string($identifier.'_help', $component) - the actual help page text
2351 * @since Moodle 2.0
2352 * @param string $elementname name of the element to add the item to
2353 * @param string $identifier help string identifier without _help suffix
2354 * @param string $component component name to look the help string in
2355 * @param string $linktext optional text to display next to the icon
2356 * @param bool $suppresscheck set to true if the element may not exist
2357 * @param string|object|array|int $a An object, string or number that can be used
2358 * within translation strings
2360 public function addHelpButton(
2361 $elementname,
2362 $identifier,
2363 $component = 'moodle',
2364 $linktext = '',
2365 $suppresscheck = false,
2366 $a = null
2368 global $OUTPUT;
2369 if (array_key_exists($elementname, $this->_elementIndex)) {
2370 $element = $this->_elements[$this->_elementIndex[$elementname]];
2371 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext, $a);
2372 } else if (!$suppresscheck) {
2373 debugging(get_string('nonexistentformelements', 'form', $elementname));
2378 * Set constant value not overridden by _POST or _GET
2379 * note: this does not work for complex names with [] :-(
2381 * @param string $elname name of element
2382 * @param mixed $value
2384 function setConstant($elname, $value) {
2385 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
2386 $element =& $this->getElement($elname);
2387 $element->onQuickFormEvent('updateValue', null, $this);
2391 * export submitted values
2393 * @param string $elementList list of elements in form
2394 * @return array
2396 function exportValues($elementList = null){
2397 $unfiltered = array();
2398 if (null === $elementList) {
2399 // iterate over all elements, calling their exportValue() methods
2400 foreach (array_keys($this->_elements) as $key) {
2401 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
2402 $value = '';
2403 if (isset($this->_elements[$key]->_attributes['name'])) {
2404 $varname = $this->_elements[$key]->_attributes['name'];
2405 // If we have a default value then export it.
2406 if (isset($this->_defaultValues[$varname])) {
2407 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
2410 } else {
2411 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
2414 if (is_array($value)) {
2415 // This shit throws a bogus warning in PHP 4.3.x
2416 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2419 } else {
2420 if (!is_array($elementList)) {
2421 $elementList = array_map('trim', explode(',', $elementList));
2423 foreach ($elementList as $elementName) {
2424 $value = $this->exportValue($elementName);
2425 if ((new PEAR())->isError($value)) {
2426 return $value;
2428 //oh, stock QuickFOrm was returning array of arrays!
2429 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2433 if (is_array($this->_constantValues)) {
2434 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
2436 return $unfiltered;
2440 * This is a bit of a hack, and it duplicates the code in
2441 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
2442 * reliably calling that code. (Think about date selectors, for example.)
2443 * @param string $name the element name.
2444 * @param mixed $value the fixed value to set.
2445 * @return mixed the appropriate array to add to the $unfiltered array.
2447 protected function prepare_fixed_value($name, $value) {
2448 if (null === $value) {
2449 return null;
2450 } else {
2451 if (!strpos($name, '[')) {
2452 return array($name => $value);
2453 } else {
2454 $valueAry = array();
2455 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2456 eval("\$valueAry$myIndex = \$value;");
2457 return $valueAry;
2463 * Adds a validation rule for the given field
2465 * If the element is in fact a group, it will be considered as a whole.
2466 * To validate grouped elements as separated entities,
2467 * use addGroupRule instead of addRule.
2469 * @param string $element Form element name
2470 * @param string|null $message Message to display for invalid data
2471 * @param string $type Rule type, use getRegisteredRules() to get types
2472 * @param mixed $format (optional)Required for extra rule data
2473 * @param string $validation (optional)Where to perform validation: "server", "client"
2474 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2475 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2477 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2479 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2480 if ($validation == 'client') {
2481 $this->clientvalidation = true;
2487 * Adds a validation rule for the given group of elements
2489 * Only groups with a name can be assigned a validation rule
2490 * Use addGroupRule when you need to validate elements inside the group.
2491 * Use addRule if you need to validate the group as a whole. In this case,
2492 * the same rule will be applied to all elements in the group.
2493 * Use addRule if you need to validate the group against a function.
2495 * @param string $group Form group name
2496 * @param array|string $arg1 Array for multiple elements or error message string for one element
2497 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2498 * @param string $format (optional)Required for extra rule data
2499 * @param int $howmany (optional)How many valid elements should be in the group
2500 * @param string $validation (optional)Where to perform validation: "server", "client"
2501 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2503 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2505 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2506 if (is_array($arg1)) {
2507 foreach ($arg1 as $rules) {
2508 foreach ($rules as $rule) {
2509 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2510 if ($validation == 'client') {
2511 $this->clientvalidation = true;
2515 } elseif (is_string($arg1)) {
2516 if ($validation == 'client') {
2517 $this->clientvalidation = true;
2523 * Returns the client side validation script
2525 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2526 * and slightly modified to run rules per-element
2527 * Needed to override this because of an error with client side validation of grouped elements.
2529 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2531 function getValidationScript()
2533 global $PAGE;
2535 if (empty($this->_rules) || $this->clientvalidation === false) {
2536 return '';
2539 include_once('HTML/QuickForm/RuleRegistry.php');
2540 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2541 $test = array();
2542 $js_escape = array(
2543 "\r" => '\r',
2544 "\n" => '\n',
2545 "\t" => '\t',
2546 "'" => "\\'",
2547 '"' => '\"',
2548 '\\' => '\\\\'
2551 foreach ($this->_rules as $elementName => $rules) {
2552 foreach ($rules as $rule) {
2553 if ('client' == $rule['validation']) {
2554 unset($element); //TODO: find out how to properly initialize it
2556 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2557 $rule['message'] = strtr($rule['message'], $js_escape);
2559 if (isset($rule['group'])) {
2560 $group =& $this->getElement($rule['group']);
2561 // No JavaScript validation for frozen elements
2562 if ($group->isFrozen()) {
2563 continue 2;
2565 $elements =& $group->getElements();
2566 foreach (array_keys($elements) as $key) {
2567 if ($elementName == $group->getElementName($key)) {
2568 $element =& $elements[$key];
2569 break;
2572 } elseif ($dependent) {
2573 $element = array();
2574 $element[] =& $this->getElement($elementName);
2575 foreach ($rule['dependent'] as $elName) {
2576 $element[] =& $this->getElement($elName);
2578 } else {
2579 $element =& $this->getElement($elementName);
2581 // No JavaScript validation for frozen elements
2582 if (is_object($element) && $element->isFrozen()) {
2583 continue 2;
2584 } elseif (is_array($element)) {
2585 foreach (array_keys($element) as $key) {
2586 if ($element[$key]->isFrozen()) {
2587 continue 3;
2591 //for editor element, [text] is appended to the name.
2592 $fullelementname = $elementName;
2593 if (is_object($element) && $element->getType() == 'editor') {
2594 if ($element->getType() == 'editor') {
2595 $fullelementname .= '[text]';
2596 // Add format to rule as moodleform check which format is supported by browser
2597 // it is not set anywhere... So small hack to make sure we pass it down to quickform.
2598 if (is_null($rule['format'])) {
2599 $rule['format'] = $element->getFormat();
2603 // Fix for bug displaying errors for elements in a group
2604 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2605 $test[$fullelementname][1]=$element;
2606 //end of fix
2611 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2612 // the form, and then that form field gets corrupted by the code that follows.
2613 unset($element);
2615 $js = '
2617 require([
2618 "core_form/events",
2619 "jquery",
2620 ], function(
2621 FormEvents,
2625 function qf_errorHandler(element, _qfMsg, escapedName) {
2626 const event = FormEvents.notifyFieldValidationFailure(element, _qfMsg);
2627 if (event.defaultPrevented) {
2628 return _qfMsg == \'\';
2629 } else {
2630 // Legacy mforms.
2631 var div = element.parentNode;
2633 if ((div == undefined) || (element.name == undefined)) {
2634 // No checking can be done for undefined elements so let server handle it.
2635 return true;
2638 if (_qfMsg != \'\') {
2639 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2640 if (!errorSpan) {
2641 errorSpan = document.createElement("span");
2642 errorSpan.id = \'id_error_\' + escapedName;
2643 errorSpan.className = "error";
2644 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2645 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2646 document.getElementById(errorSpan.id).focus();
2649 while (errorSpan.firstChild) {
2650 errorSpan.removeChild(errorSpan.firstChild);
2653 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2655 if (div.className.substr(div.className.length - 6, 6) != " error"
2656 && div.className != "error") {
2657 div.className += " error";
2658 linebreak = document.createElement("br");
2659 linebreak.className = "error";
2660 linebreak.id = \'id_error_break_\' + escapedName;
2661 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2664 return false;
2665 } else {
2666 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2667 if (errorSpan) {
2668 errorSpan.parentNode.removeChild(errorSpan);
2670 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2671 if (linebreak) {
2672 linebreak.parentNode.removeChild(linebreak);
2675 if (div.className.substr(div.className.length - 6, 6) == " error") {
2676 div.className = div.className.substr(0, div.className.length - 6);
2677 } else if (div.className == "error") {
2678 div.className = "";
2681 return true;
2682 } // End if.
2683 } // End if.
2684 } // End function.
2686 $validateJS = '';
2687 foreach ($test as $elementName => $jsandelement) {
2688 // Fix for bug displaying errors for elements in a group
2689 //unset($element);
2690 list($jsArr,$element)=$jsandelement;
2691 //end of fix
2692 $escapedElementName = preg_replace_callback(
2693 '/[_\[\]-]/',
2694 function($matches) {
2695 return sprintf("_%2x", ord($matches[0]));
2697 $elementName);
2698 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
2700 if (!is_array($element)) {
2701 $element = [$element];
2703 foreach ($element as $elem) {
2704 if (key_exists('id', $elem->_attributes)) {
2705 $js .= '
2706 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2707 if (undefined == element) {
2708 //required element was not found, then let form be submitted without client side validation
2709 return true;
2711 var value = \'\';
2712 var errFlag = new Array();
2713 var _qfGroups = {};
2714 var _qfMsg = \'\';
2715 var frm = element.parentNode;
2716 if ((undefined != element.name) && (frm != undefined)) {
2717 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2718 frm = frm.parentNode;
2720 ' . join("\n", $jsArr) . '
2721 return qf_errorHandler(element, _qfMsg, escapedName);
2722 } else {
2723 //element name should be defined else error msg will not be displayed.
2724 return true;
2728 document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'blur\', function(ev) {
2729 ' . $valFunc . '
2731 document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'change\', function(ev) {
2732 ' . $valFunc . '
2737 // This handles both randomised (MDL-65217) and non-randomised IDs.
2738 $errorid = preg_replace('/^id_/', 'id_error_', $elem->_attributes['id']);
2739 $validateJS .= '
2740 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2741 if (!ret && !first_focus) {
2742 first_focus = true;
2743 const element = document.getElementById("' . $errorid . '");
2744 if (element) {
2745 FormEvents.notifyFormError(element);
2746 element.focus();
2751 // Fix for bug displaying errors for elements in a group
2752 //unset($element);
2753 //$element =& $this->getElement($elementName);
2754 //end of fix
2755 //$onBlur = $element->getAttribute('onBlur');
2756 //$onChange = $element->getAttribute('onChange');
2757 //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2758 //'onChange' => $onChange . $valFunc));
2760 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2761 $js .= '
2763 function validate_' . $this->_formName . '() {
2764 if (skipClientValidation) {
2765 return true;
2767 var ret = true;
2769 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2770 var first_focus = false;
2771 ' . $validateJS . ';
2772 return ret;
2775 var form = document.getElementById(\'' . $this->_attributes['id'] . '\').closest(\'form\');
2776 form.addEventListener(FormEvents.eventTypes.formSubmittedByJavascript, () => {
2777 try {
2778 var myValidator = validate_' . $this->_formName . ';
2779 } catch(e) {
2780 return;
2782 if (myValidator) {
2783 myValidator();
2787 document.getElementById(\'' . $this->_attributes['id'] . '\').addEventListener(\'submit\', function(ev) {
2788 try {
2789 var myValidator = validate_' . $this->_formName . ';
2790 } catch(e) {
2791 return true;
2793 if (typeof window.tinyMCE !== \'undefined\') {
2794 window.tinyMCE.triggerSave();
2796 if (!myValidator()) {
2797 ev.preventDefault();
2804 $PAGE->requires->js_amd_inline($js);
2806 // Global variable used to skip the client validation.
2807 return html_writer::tag('script', 'var skipClientValidation = false;');
2808 } // end func getValidationScript
2811 * Sets default error message
2813 function _setDefaultRuleMessages(){
2814 foreach ($this->_rules as $field => $rulesarr){
2815 foreach ($rulesarr as $key => $rule){
2816 if ($rule['message']===null){
2817 $a=new stdClass();
2818 $a->format=$rule['format'];
2819 $str=get_string('err_'.$rule['type'], 'form', $a);
2820 if (strpos($str, '[[')!==0){
2821 $this->_rules[$field][$key]['message']=$str;
2829 * Get list of attributes which have dependencies
2831 * @return array
2833 function getLockOptionObject(){
2834 $result = array();
2835 foreach ($this->_dependencies as $dependentOn => $conditions){
2836 $result[$dependentOn] = array();
2837 foreach ($conditions as $condition=>$values) {
2838 $result[$dependentOn][$condition] = array();
2839 foreach ($values as $value=>$dependents) {
2840 $result[$dependentOn][$condition][$value][self::DEP_DISABLE] = array();
2841 foreach ($dependents as $dependent) {
2842 $elements = $this->_getElNamesRecursive($dependent);
2843 if (empty($elements)) {
2844 // probably element inside of some group
2845 $elements = array($dependent);
2847 foreach($elements as $element) {
2848 if ($element == $dependentOn) {
2849 continue;
2851 $result[$dependentOn][$condition][$value][self::DEP_DISABLE][] = $element;
2857 foreach ($this->_hideifs as $dependenton => $conditions) {
2858 if (!isset($result[$dependenton])) {
2859 $result[$dependenton] = array();
2861 foreach ($conditions as $condition => $values) {
2862 if (!isset($result[$dependenton][$condition])) {
2863 $result[$dependenton][$condition] = array();
2865 foreach ($values as $value => $dependents) {
2866 $result[$dependenton][$condition][$value][self::DEP_HIDE] = array();
2867 foreach ($dependents as $dependent) {
2868 $elements = $this->_getElNamesRecursive($dependent);
2869 if (!in_array($dependent, $elements)) {
2870 // Always want to hide the main element, even if it contains sub-elements as well.
2871 $elements[] = $dependent;
2873 foreach ($elements as $element) {
2874 if ($element == $dependenton) {
2875 continue;
2877 $result[$dependenton][$condition][$value][self::DEP_HIDE][] = $element;
2883 return array($this->getAttribute('id'), $result);
2887 * Get names of element or elements in a group.
2889 * @param HTML_QuickForm_group|element $element element group or element object
2890 * @return array
2892 function _getElNamesRecursive($element) {
2893 if (is_string($element)) {
2894 if (!$this->elementExists($element)) {
2895 return array();
2897 $element = $this->getElement($element);
2900 if (is_a($element, 'HTML_QuickForm_group')) {
2901 $elsInGroup = $element->getElements();
2902 $elNames = array();
2903 foreach ($elsInGroup as $elInGroup){
2904 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2905 // Groups nested in groups: append the group name to the element and then change it back.
2906 // We will be appending group name again in MoodleQuickForm_group::export_for_template().
2907 $oldname = $elInGroup->getName();
2908 if ($element->_appendName) {
2909 $elInGroup->setName($element->getName() . '[' . $oldname . ']');
2911 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2912 $elInGroup->setName($oldname);
2913 } else {
2914 $elNames[] = $element->getElementName($elInGroup->getName());
2918 } else if (is_a($element, 'HTML_QuickForm_header')) {
2919 return array();
2921 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2922 return array();
2924 } else if (method_exists($element, 'getPrivateName') &&
2925 !($element instanceof HTML_QuickForm_advcheckbox)) {
2926 // The advcheckbox element implements a method called getPrivateName,
2927 // but in a way that is not compatible with the generic API, so we
2928 // have to explicitly exclude it.
2929 return array($element->getPrivateName());
2931 } else {
2932 $elNames = array($element->getName());
2935 return $elNames;
2939 * Adds a dependency for $elementName which will be disabled if $condition is met.
2940 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2941 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2942 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2943 * of the $dependentOn element is $condition (such as equal) to $value.
2945 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2946 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2947 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2949 * @param string $elementName the name of the element which will be disabled
2950 * @param string $dependentOn the name of the element whose state will be checked for condition
2951 * @param string $condition the condition to check
2952 * @param mixed $value used in conjunction with condition.
2954 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2955 // Multiple selects allow for a multiple selection, we transform the array to string here as
2956 // an array cannot be used as a key in an associative array.
2957 if (is_array($value)) {
2958 $value = implode('|', $value);
2960 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2961 $this->_dependencies[$dependentOn] = array();
2963 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2964 $this->_dependencies[$dependentOn][$condition] = array();
2966 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2967 $this->_dependencies[$dependentOn][$condition][$value] = array();
2969 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2973 * Adds a dependency for $elementName which will be hidden if $condition is met.
2974 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2975 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2976 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2977 * of the $dependentOn element is $condition (such as equal) to $value.
2979 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2980 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2981 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2983 * @param string $elementname the name of the element which will be hidden
2984 * @param string $dependenton the name of the element whose state will be checked for condition
2985 * @param string $condition the condition to check
2986 * @param mixed $value used in conjunction with condition.
2988 public function hideIf($elementname, $dependenton, $condition = 'notchecked', $value = '1') {
2989 // Multiple selects allow for a multiple selection, we transform the array to string here as
2990 // an array cannot be used as a key in an associative array.
2991 if (is_array($value)) {
2992 $value = implode('|', $value);
2994 if (!array_key_exists($dependenton, $this->_hideifs)) {
2995 $this->_hideifs[$dependenton] = array();
2997 if (!array_key_exists($condition, $this->_hideifs[$dependenton])) {
2998 $this->_hideifs[$dependenton][$condition] = array();
3000 if (!array_key_exists($value, $this->_hideifs[$dependenton][$condition])) {
3001 $this->_hideifs[$dependenton][$condition][$value] = array();
3003 $this->_hideifs[$dependenton][$condition][$value][] = $elementname;
3007 * Registers button as no submit button
3009 * @param string $buttonname name of the button
3011 function registerNoSubmitButton($buttonname){
3012 $this->_noSubmitButtons[]=$buttonname;
3016 * Checks if button is a no submit button, i.e it doesn't submit form
3018 * @param string $buttonname name of the button to check
3019 * @return bool
3021 function isNoSubmitButton($buttonname){
3022 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
3026 * Registers a button as cancel button
3028 * @param string $addfieldsname name of the button
3030 function _registerCancelButton($addfieldsname){
3031 $this->_cancelButtons[]=$addfieldsname;
3035 * Displays elements without HTML input tags.
3036 * This method is different to freeze() in that it makes sure no hidden
3037 * elements are included in the form.
3038 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
3040 * This function also removes all previously defined rules.
3042 * @param string|array $elementList array or string of element(s) to be frozen
3043 * @return object|bool if element list is not empty then return error object, else true
3045 function hardFreeze($elementList=null)
3047 if (!isset($elementList)) {
3048 $this->_freezeAll = true;
3049 $elementList = array();
3050 } else {
3051 if (!is_array($elementList)) {
3052 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
3054 $elementList = array_flip($elementList);
3057 foreach (array_keys($this->_elements) as $key) {
3058 $name = $this->_elements[$key]->getName();
3059 if ($this->_freezeAll || isset($elementList[$name])) {
3060 $this->_elements[$key]->freeze();
3061 $this->_elements[$key]->setPersistantFreeze(false);
3062 unset($elementList[$name]);
3064 // remove all rules
3065 $this->_rules[$name] = array();
3066 // if field is required, remove the rule
3067 $unset = array_search($name, $this->_required);
3068 if ($unset !== false) {
3069 unset($this->_required[$unset]);
3074 if (!empty($elementList)) {
3075 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);
3077 return true;
3081 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
3083 * This function also removes all previously defined rules of elements it freezes.
3085 * @throws HTML_QuickForm_Error
3086 * @param array $elementList array or string of element(s) not to be frozen
3087 * @return bool returns true
3089 function hardFreezeAllVisibleExcept($elementList)
3091 $elementList = array_flip($elementList);
3092 foreach (array_keys($this->_elements) as $key) {
3093 $name = $this->_elements[$key]->getName();
3094 $type = $this->_elements[$key]->getType();
3096 if ($type == 'hidden'){
3097 // leave hidden types as they are
3098 } elseif (!isset($elementList[$name])) {
3099 $this->_elements[$key]->freeze();
3100 $this->_elements[$key]->setPersistantFreeze(false);
3102 // remove all rules
3103 $this->_rules[$name] = array();
3104 // if field is required, remove the rule
3105 $unset = array_search($name, $this->_required);
3106 if ($unset !== false) {
3107 unset($this->_required[$unset]);
3111 return true;
3115 * Tells whether the form was already submitted
3117 * This is useful since the _submitFiles and _submitValues arrays
3118 * may be completely empty after the trackSubmit value is removed.
3120 * @return bool
3122 function isSubmitted()
3124 return parent::isSubmitted() && (!$this->isFrozen());
3128 * Add the element name to the list of newly-created repeat elements
3129 * (So that elements that interpret 'no data submitted' as a valid state
3130 * can tell when they should get the default value instead).
3132 * @param string $name the name of the new element
3134 public function note_new_repeat($name) {
3135 $this->_newrepeats[] = $name;
3139 * Check if the element with the given name has just been added by clicking
3140 * on the 'Add repeating elements' button.
3142 * @param string $name the name of the element being checked
3143 * @return bool true if the element is newly added
3145 public function is_new_repeat($name) {
3146 return in_array($name, $this->_newrepeats);
3151 * MoodleQuickForm renderer
3153 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
3154 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
3156 * Stylesheet is part of standard theme and should be automatically included.
3158 * @package core_form
3159 * @copyright 2007 Jamie Pratt <me@jamiep.org>
3160 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3162 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
3164 /** @var array Element template array */
3165 var $_elementTemplates;
3168 * Template used when opening a hidden fieldset
3169 * (i.e. a fieldset that is opened when there is no header element)
3170 * @var string
3172 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
3174 /** @var string Template used when opening a fieldset */
3175 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
3177 /** @var string Template used when closing a fieldset */
3178 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
3180 /** @var string Required Note template string */
3181 var $_requiredNoteTemplate =
3182 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
3185 * Collapsible buttons string template.
3187 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
3188 * until the Javascript has been fully loaded.
3190 * @var string
3192 var $_collapseButtonsTemplate =
3193 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
3196 * Array whose keys are element names. If the key exists this is a advanced element
3198 * @var array
3200 var $_advancedElements = array();
3203 * The form element to render in the sticky footer, if any.
3204 * @var string|null $_stickyfooterelement
3206 protected $_stickyfooterelement = null;
3209 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
3211 * @var array
3213 var $_collapsibleElements = array();
3216 * @var string Contains the collapsible buttons to add to the form.
3218 var $_collapseButtons = '';
3220 /** @var string request class HTML. */
3221 protected $_reqHTML;
3223 /** @var string advanced class HTML. */
3224 protected $_advancedHTML;
3227 * Array whose keys are element names should be hidden.
3228 * If the key exists this is an invisible element.
3230 * @var array
3232 protected $_nonvisibleelements = [];
3235 * Constructor
3237 public function __construct() {
3238 // switch next two lines for ol li containers for form items.
3239 // $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>');
3240 $this->_elementTemplates = array(
3241 '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>',
3243 '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>',
3245 '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>',
3247 '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>',
3249 'warning' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}">{element}</div>',
3251 'nodisplay' => '');
3253 parent::__construct();
3257 * Old syntax of class constructor. Deprecated in PHP7.
3259 * @deprecated since Moodle 3.1
3261 public function MoodleQuickForm_Renderer() {
3262 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
3263 self::__construct();
3267 * Set element's as adavance element
3269 * @param array $elements form elements which needs to be grouped as advance elements.
3271 function setAdvancedElements($elements){
3272 $this->_advancedElements = $elements;
3276 * Set the sticky footer element if any.
3278 * @param string|null $elementname the form element name.
3280 public function set_sticky_footer(?string $elementname): void {
3281 $this->_stickyfooterelement = $elementname;
3285 * Setting collapsible elements
3287 * @param array $elements
3289 function setCollapsibleElements($elements) {
3290 $this->_collapsibleElements = $elements;
3294 * Setting non visible elements
3296 * @param array $elements
3298 public function set_nonvisible_elements($elements) {
3299 $this->_nonvisibleelements = $elements;
3303 * What to do when starting the form
3305 * @param MoodleQuickForm $form reference of the form
3307 function startForm(&$form){
3308 global $PAGE, $OUTPUT;
3309 $this->_reqHTML = $form->getReqHTML();
3310 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
3311 $this->_advancedHTML = $form->getAdvancedHTML();
3312 $this->_collapseButtons = '';
3313 $formid = $form->getAttribute('id');
3314 parent::startForm($form);
3315 if ($form->isFrozen()){
3316 $this->_formTemplate = "\n<div id=\"$formid\" class=\"mform frozen\">\n{collapsebtns}\n{content}\n</div>";
3317 } else {
3318 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
3319 $this->_hiddenHtml .= $form->_pageparams;
3322 if ($form->is_form_change_checker_enabled()) {
3323 $PAGE->requires->js_call_amd('core_form/changechecker', 'watchFormById', [$formid]);
3324 if ($form->is_dirty()) {
3325 $PAGE->requires->js_call_amd('core_form/changechecker', 'markFormAsDirtyById', [$formid]);
3328 if (!empty($this->_collapsibleElements)) {
3329 if (count($this->_collapsibleElements) > 1) {
3330 $this->_collapseButtons = $OUTPUT->render_from_template('core_form/collapsesections', (object)[]);
3332 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
3334 if (!empty($this->_advancedElements)){
3335 $PAGE->requires->js_call_amd('core_form/showadvanced', 'init', [$formid]);
3340 * Create advance group of elements
3342 * @param MoodleQuickForm_group $group Passed by reference
3343 * @param bool $required if input is required field
3344 * @param string $error error message to display
3346 function startGroup(&$group, $required, $error){
3347 global $OUTPUT;
3349 // Make sure the element has an id.
3350 $group->_generateId();
3352 // Prepend 'fgroup_' to the ID we generated.
3353 $groupid = 'fgroup_' . $group->getAttribute('id');
3355 // Update the ID.
3356 $group->updateAttributes(array('id' => $groupid));
3357 $advanced = isset($this->_advancedElements[$group->getName()]);
3359 $html = $OUTPUT->mform_element($group, $required, $advanced, $error, false);
3360 $fromtemplate = !empty($html);
3361 if (!$fromtemplate) {
3362 if (method_exists($group, 'getElementTemplateType')) {
3363 $html = $this->_elementTemplates[$group->getElementTemplateType()];
3364 } else {
3365 $html = $this->_elementTemplates['default'];
3368 if (isset($this->_advancedElements[$group->getName()])) {
3369 $html = str_replace(' {advanced}', ' advanced', $html);
3370 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
3371 } else {
3372 $html = str_replace(' {advanced}', '', $html);
3373 $html = str_replace('{advancedimg}', '', $html);
3375 if (method_exists($group, 'getHelpButton')) {
3376 $html = str_replace('{help}', $group->getHelpButton(), $html);
3377 } else {
3378 $html = str_replace('{help}', '', $html);
3380 $html = str_replace('{id}', $group->getAttribute('id'), $html);
3381 $html = str_replace('{name}', $group->getName(), $html);
3382 $html = str_replace('{groupname}', 'data-groupname="'.$group->getName().'"', $html);
3383 $html = str_replace('{typeclass}', 'fgroup', $html);
3384 $html = str_replace('{type}', 'group', $html);
3385 $html = str_replace('{class}', $group->getAttribute('class') ?? '', $html);
3386 $emptylabel = '';
3387 if ($group->getLabel() == '') {
3388 $emptylabel = 'femptylabel';
3390 $html = str_replace('{emptylabel}', $emptylabel, $html);
3392 $this->_templates[$group->getName()] = $html;
3393 // Check if the element should be displayed in the sticky footer.
3394 if ($group->getName() && ($this->_stickyfooterelement == $group->getName())) {
3395 $stickyfooter = new core\output\sticky_footer($html);
3396 $html = $OUTPUT->render($stickyfooter);
3399 // Fix for bug in tableless quickforms that didn't allow you to stop a
3400 // fieldset before a group of elements.
3401 // if the element name indicates the end of a fieldset, close the fieldset
3402 if (in_array($group->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
3403 $this->_html .= $this->_closeFieldsetTemplate;
3404 $this->_fieldsetsOpen--;
3406 if (!$fromtemplate) {
3407 parent::startGroup($group, $required, $error);
3408 } else {
3409 $this->_html .= $html;
3414 * Renders element
3416 * @param HTML_QuickForm_element $element element
3417 * @param bool $required if input is required field
3418 * @param string $error error message to display
3420 function renderElement(&$element, $required, $error){
3421 global $OUTPUT;
3423 // Make sure the element has an id.
3424 $element->_generateId();
3425 $advanced = isset($this->_advancedElements[$element->getName()]);
3427 $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
3428 $fromtemplate = !empty($html);
3429 if (!$fromtemplate) {
3430 // Adding stuff to place holders in template
3431 // check if this is a group element first.
3432 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3433 // So it gets substitutions for *each* element.
3434 $html = $this->_groupElementTemplate;
3435 } else if (method_exists($element, 'getElementTemplateType')) {
3436 $html = $this->_elementTemplates[$element->getElementTemplateType()];
3437 } else {
3438 $html = $this->_elementTemplates['default'];
3440 if (isset($this->_advancedElements[$element->getName()])) {
3441 $html = str_replace(' {advanced}', ' advanced', $html);
3442 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
3443 } else {
3444 $html = str_replace(' {advanced}', '', $html);
3445 $html = str_replace(' {aria-live}', '', $html);
3447 if (isset($this->_advancedElements[$element->getName()]) || $element->getName() == 'mform_showadvanced') {
3448 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
3449 } else {
3450 $html = str_replace('{advancedimg}', '', $html);
3452 $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
3453 $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
3454 $html = str_replace('{type}', $element->getType(), $html);
3455 $html = str_replace('{name}', $element->getName(), $html);
3456 $html = str_replace('{groupname}', '', $html);
3457 $html = str_replace('{class}', $element->getAttribute('class') ?? '', $html);
3458 $emptylabel = '';
3459 if ($element->getLabel() == '') {
3460 $emptylabel = 'femptylabel';
3462 $html = str_replace('{emptylabel}', $emptylabel, $html);
3463 if (method_exists($element, 'getHelpButton')) {
3464 $html = str_replace('{help}', $element->getHelpButton(), $html);
3465 } else {
3466 $html = str_replace('{help}', '', $html);
3468 } else {
3469 if ($this->_inGroup) {
3470 $this->_groupElementTemplate = $html;
3473 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3474 $this->_groupElementTemplate = $html;
3475 } else if (!isset($this->_templates[$element->getName()])) {
3476 $this->_templates[$element->getName()] = $html;
3479 // Check if the element should be displayed in the sticky footer.
3480 if ($element->getName() && ($this->_stickyfooterelement == $element->getName())) {
3481 $stickyfooter = new core\output\sticky_footer($html);
3482 $html = $OUTPUT->render($stickyfooter);
3485 if (!$fromtemplate) {
3486 parent::renderElement($element, $required, $error);
3487 } else {
3488 if (in_array($element->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
3489 $this->_html .= $this->_closeFieldsetTemplate;
3490 $this->_fieldsetsOpen--;
3492 $this->_html .= $html;
3497 * Called when visiting a form, after processing all form elements
3498 * Adds required note, form attributes, validation javascript and form content.
3500 * @global moodle_page $PAGE
3501 * @param MoodleQuickForm $form Passed by reference
3503 function finishForm(&$form){
3504 global $PAGE;
3505 if ($form->isFrozen()){
3506 $this->_hiddenHtml = '';
3508 parent::finishForm($form);
3509 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
3510 if (!$form->isFrozen()) {
3511 $args = $form->getLockOptionObject();
3512 if (count($args[1]) > 0) {
3513 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
3518 * Called when visiting a header element
3520 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
3521 * @global moodle_page $PAGE
3523 function renderHeader(&$header) {
3524 global $PAGE, $OUTPUT;
3526 $header->_generateId();
3527 $name = $header->getName();
3529 $collapsed = $collapseable = '';
3530 if (isset($this->_collapsibleElements[$header->getName()])) {
3531 $collapseable = true;
3532 $collapsed = $this->_collapsibleElements[$header->getName()];
3535 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
3536 if (!empty($name) && isset($this->_templates[$name])) {
3537 $headerhtml = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
3538 } else {
3539 $headerhtml = $OUTPUT->render_from_template('core_form/element-header',
3540 (object)[
3541 'header' => $header->toHtml(),
3542 'id' => $header->getAttribute('id'),
3543 'collapseable' => $collapseable,
3544 'collapsed' => $collapsed,
3545 'helpbutton' => $header->getHelpButton(),
3549 if ($this->_fieldsetsOpen > 0) {
3550 $this->_html .= $this->_closeFieldsetTemplate;
3551 $this->_fieldsetsOpen--;
3554 // Define collapsible classes for fieldsets.
3555 $arialive = '';
3556 $fieldsetclasses = array('clearfix');
3557 if (isset($this->_collapsibleElements[$header->getName()])) {
3558 $fieldsetclasses[] = 'collapsible';
3559 if ($this->_collapsibleElements[$header->getName()]) {
3560 $fieldsetclasses[] = 'collapsed';
3564 // Hide fieldsets not included in the shown only elements.
3565 if (in_array($header->getName(), $this->_nonvisibleelements)) {
3566 $fieldsetclasses[] = 'd-none';
3569 if (isset($this->_advancedElements[$name])){
3570 $fieldsetclasses[] = 'containsadvancedelements';
3573 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
3574 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
3576 $this->_html .= $openFieldsetTemplate . $headerhtml;
3577 $this->_fieldsetsOpen++;
3581 * Return Array of element names that indicate the end of a fieldset
3583 * @return array
3585 function getStopFieldsetElements(){
3586 return $this->_stopFieldsetElements;
3591 * Required elements validation
3593 * This class overrides QuickForm validation since it allowed space or empty tag as a value
3595 * @package core_form
3596 * @category form
3597 * @copyright 2006 Jamie Pratt <me@jamiep.org>
3598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3600 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
3602 * Checks if an element is not empty.
3603 * This is a server-side validation, it works for both text fields and editor fields
3605 * @param string $value Value to check
3606 * @param int|string|array $options Not used yet
3607 * @return bool true if value is not empty
3609 function validate($value, $options = null) {
3610 global $CFG;
3611 if (is_array($value) && array_key_exists('text', $value)) {
3612 $value = $value['text'];
3614 if (is_array($value)) {
3615 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
3616 $value = implode('', $value);
3618 $stripvalues = array(
3619 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
3620 '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
3622 if (!empty($CFG->strictformsrequired)) {
3623 $value = preg_replace($stripvalues, '', (string)$value);
3625 if ((string)$value == '') {
3626 return false;
3628 return true;
3632 * This function returns Javascript code used to build client-side validation.
3633 * It checks if an element is not empty.
3635 * @param int $format format of data which needs to be validated.
3636 * @return array
3638 function getValidationScript($format = null) {
3639 global $CFG;
3640 if (!empty($CFG->strictformsrequired)) {
3641 if (!empty($format) && $format == FORMAT_HTML) {
3642 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
3643 } else {
3644 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
3646 } else {
3647 return array('', "{jsVar} == ''");
3653 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
3654 * @name $_HTML_QuickForm_default_renderer
3656 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
3658 /** Please keep this list in alphabetical order. */
3659 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
3660 MoodleQuickForm::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
3661 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
3662 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3663 MoodleQuickForm::registerElementType('course', "$CFG->libdir/form/course.php", 'MoodleQuickForm_course');
3664 MoodleQuickForm::registerElementType('cohort', "$CFG->libdir/form/cohort.php", 'MoodleQuickForm_cohort');
3665 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
3666 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
3667 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
3668 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
3669 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
3670 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
3671 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
3672 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
3673 MoodleQuickForm::registerElementType('filetypes', "$CFG->libdir/form/filetypes.php", 'MoodleQuickForm_filetypes');
3674 MoodleQuickForm::registerElementType('float', "$CFG->libdir/form/float.php", 'MoodleQuickForm_float');
3675 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
3676 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
3677 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
3678 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
3679 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
3680 MoodleQuickForm::registerElementType('defaultcustom', "$CFG->libdir/form/defaultcustom.php", 'MoodleQuickForm_defaultcustom');
3681 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
3682 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
3683 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
3684 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
3685 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
3686 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
3687 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
3688 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
3689 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
3690 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
3691 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
3692 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
3693 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
3694 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
3695 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
3696 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
3697 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
3698 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
3700 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");