MDL-64324 core_form: randomly generate id attribute on forms
[moodle.git] / lib / formslib.php
blobcaa39efdaea66f3e35c3b9da136eeca930e3bd13
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 $calendar = \core_calendar\type_factory::get_calendar_instance();
81 $module = 'moodle-form-dateselector';
82 $function = 'M.form.dateselector.init_date_selectors';
83 $defaulttimezone = date_default_timezone_get();
85 $config = array(array(
86 'firstdayofweek' => $calendar->get_starting_weekday(),
87 'mon' => date_format_string(strtotime("Monday"), '%a', $defaulttimezone),
88 'tue' => date_format_string(strtotime("Tuesday"), '%a', $defaulttimezone),
89 'wed' => date_format_string(strtotime("Wednesday"), '%a', $defaulttimezone),
90 'thu' => date_format_string(strtotime("Thursday"), '%a', $defaulttimezone),
91 'fri' => date_format_string(strtotime("Friday"), '%a', $defaulttimezone),
92 'sat' => date_format_string(strtotime("Saturday"), '%a', $defaulttimezone),
93 'sun' => date_format_string(strtotime("Sunday"), '%a', $defaulttimezone),
94 'january' => date_format_string(strtotime("January 1"), '%B', $defaulttimezone),
95 'february' => date_format_string(strtotime("February 1"), '%B', $defaulttimezone),
96 'march' => date_format_string(strtotime("March 1"), '%B', $defaulttimezone),
97 'april' => date_format_string(strtotime("April 1"), '%B', $defaulttimezone),
98 'may' => date_format_string(strtotime("May 1"), '%B', $defaulttimezone),
99 'june' => date_format_string(strtotime("June 1"), '%B', $defaulttimezone),
100 'july' => date_format_string(strtotime("July 1"), '%B', $defaulttimezone),
101 'august' => date_format_string(strtotime("August 1"), '%B', $defaulttimezone),
102 'september' => date_format_string(strtotime("September 1"), '%B', $defaulttimezone),
103 'october' => date_format_string(strtotime("October 1"), '%B', $defaulttimezone),
104 'november' => date_format_string(strtotime("November 1"), '%B', $defaulttimezone),
105 'december' => date_format_string(strtotime("December 1"), '%B', $defaulttimezone)
107 $PAGE->requires->yui_module($module, $function, $config);
108 $done = true;
113 * Wrapper that separates quickforms syntax from moodle code
115 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
116 * use this class you should write a class definition which extends this class or a more specific
117 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
119 * You will write your own definition() method which performs the form set up.
121 * @package core_form
122 * @copyright 2006 Jamie Pratt <me@jamiep.org>
123 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
124 * @todo MDL-19380 rethink the file scanning
126 abstract class moodleform {
127 /** @var string name of the form */
128 protected $_formname; // form name
130 /** @var MoodleQuickForm quickform object definition */
131 protected $_form;
133 /** @var array globals workaround */
134 protected $_customdata;
136 /** @var array submitted form data when using mforms with ajax */
137 protected $_ajaxformdata;
139 /** @var object definition_after_data executed flag */
140 protected $_definition_finalized = false;
142 /** @var bool|null stores the validation result of this form or null if not yet validated */
143 protected $_validated = null;
146 * The constructor function calls the abstract function definition() and it will then
147 * process and clean and attempt to validate incoming data.
149 * It will call your custom validate method to validate data and will also check any rules
150 * you have specified in definition using addRule
152 * The name of the form (id attribute of the form) is automatically generated depending on
153 * the name you gave the class extending moodleform. You should call your class something
154 * like
156 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
157 * current url. If a moodle_url object then outputs params as hidden variables.
158 * @param mixed $customdata if your form defintion method needs access to data such as $course
159 * $cm, etc. to construct the form definition then pass it in this array. You can
160 * use globals for somethings.
161 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
162 * be merged and used as incoming data to the form.
163 * @param string $target target frame for form submission. You will rarely use this. Don't use
164 * it if you don't need to as the target attribute is deprecated in xhtml strict.
165 * @param mixed $attributes you can pass a string of html attributes here or an array.
166 * @param bool $editable
167 * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
169 public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true,
170 $ajaxformdata=null) {
171 global $CFG, $FULLME;
172 // no standard mform in moodle should allow autocomplete with the exception of user signup
173 if (empty($attributes)) {
174 $attributes = array('autocomplete'=>'off');
175 } else if (is_array($attributes)) {
176 $attributes['autocomplete'] = 'off';
177 } else {
178 if (strpos($attributes, 'autocomplete') === false) {
179 $attributes .= ' autocomplete="off" ';
184 if (empty($action)){
185 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
186 $action = strip_querystring($FULLME);
187 if (!empty($CFG->sslproxy)) {
188 // return only https links when using SSL proxy
189 $action = preg_replace('/^http:/', 'https:', $action, 1);
191 //TODO: use following instead of FULLME - see MDL-33015
192 //$action = strip_querystring(qualified_me());
194 // Assign custom data first, so that get_form_identifier can use it.
195 $this->_customdata = $customdata;
196 $this->_formname = $this->get_form_identifier();
197 $this->_ajaxformdata = $ajaxformdata;
199 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
200 if (!$editable){
201 $this->_form->hardFreeze();
204 $this->definition();
206 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
207 $this->_form->setType('sesskey', PARAM_RAW);
208 $this->_form->setDefault('sesskey', sesskey());
209 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
210 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
211 $this->_form->setDefault('_qf__'.$this->_formname, 1);
212 $this->_form->_setDefaultRuleMessages();
214 // Hook to inject logic after the definition was provided.
215 $this->after_definition();
217 // we have to know all input types before processing submission ;-)
218 $this->_process_submission($method);
222 * Old syntax of class constructor. Deprecated in PHP7.
224 * @deprecated since Moodle 3.1
226 public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
227 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
228 self::__construct($action, $customdata, $method, $target, $attributes, $editable);
232 * It should returns unique identifier for the form.
233 * Currently it will return class name, but in case two same forms have to be
234 * rendered on same page then override function to get unique form identifier.
235 * e.g This is used on multiple self enrollments page.
237 * @return string form identifier.
239 protected function get_form_identifier() {
240 $class = get_class($this);
242 return preg_replace('/[^a-z0-9_]/i', '_', $class);
246 * To autofocus on first form element or first element with error.
248 * @param string $name if this is set then the focus is forced to a field with this name
249 * @return string javascript to select form element with first error or
250 * first element if no errors. Use this as a parameter
251 * when calling print_header
253 function focus($name=NULL) {
254 $form =& $this->_form;
255 $elkeys = array_keys($form->_elementIndex);
256 $error = false;
257 if (isset($form->_errors) && 0 != count($form->_errors)){
258 $errorkeys = array_keys($form->_errors);
259 $elkeys = array_intersect($elkeys, $errorkeys);
260 $error = true;
263 if ($error or empty($name)) {
264 $names = array();
265 while (empty($names) and !empty($elkeys)) {
266 $el = array_shift($elkeys);
267 $names = $form->_getElNamesRecursive($el);
269 if (!empty($names)) {
270 $name = array_shift($names);
274 $focus = '';
275 if (!empty($name)) {
276 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
279 return $focus;
283 * Internal method. Alters submitted data to be suitable for quickforms processing.
284 * Must be called when the form is fully set up.
286 * @param string $method name of the method which alters submitted data
288 function _process_submission($method) {
289 $submission = array();
290 if (!empty($this->_ajaxformdata)) {
291 $submission = $this->_ajaxformdata;
292 } else if ($method == 'post') {
293 if (!empty($_POST)) {
294 $submission = $_POST;
296 } else {
297 $submission = $_GET;
298 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
301 // following trick is needed to enable proper sesskey checks when using GET forms
302 // the _qf__.$this->_formname serves as a marker that form was actually submitted
303 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
304 if (!confirm_sesskey()) {
305 print_error('invalidsesskey');
307 $files = $_FILES;
308 } else {
309 $submission = array();
310 $files = array();
312 $this->detectMissingSetType();
314 $this->_form->updateSubmission($submission, $files);
318 * Internal method - should not be used anywhere.
319 * @deprecated since 2.6
320 * @return array $_POST.
322 protected function _get_post_params() {
323 return $_POST;
327 * Internal method. Validates all old-style deprecated uploaded files.
328 * The new way is to upload files via repository api.
330 * @param array $files list of files to be validated
331 * @return bool|array Success or an array of errors
333 function _validate_files(&$files) {
334 global $CFG, $COURSE;
336 $files = array();
338 if (empty($_FILES)) {
339 // we do not need to do any checks because no files were submitted
340 // note: server side rules do not work for files - use custom verification in validate() instead
341 return true;
344 $errors = array();
345 $filenames = array();
347 // now check that we really want each file
348 foreach ($_FILES as $elname=>$file) {
349 $required = $this->_form->isElementRequired($elname);
351 if ($file['error'] == 4 and $file['size'] == 0) {
352 if ($required) {
353 $errors[$elname] = get_string('required');
355 unset($_FILES[$elname]);
356 continue;
359 if (!empty($file['error'])) {
360 $errors[$elname] = file_get_upload_error($file['error']);
361 unset($_FILES[$elname]);
362 continue;
365 if (!is_uploaded_file($file['tmp_name'])) {
366 // TODO: improve error message
367 $errors[$elname] = get_string('error');
368 unset($_FILES[$elname]);
369 continue;
372 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
373 // hmm, this file was not requested
374 unset($_FILES[$elname]);
375 continue;
378 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
380 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
381 if ($filename === '') {
382 // TODO: improve error message - wrong chars
383 $errors[$elname] = get_string('error');
384 unset($_FILES[$elname]);
385 continue;
387 if (in_array($filename, $filenames)) {
388 // TODO: improve error message - duplicate name
389 $errors[$elname] = get_string('error');
390 unset($_FILES[$elname]);
391 continue;
393 $filenames[] = $filename;
394 $_FILES[$elname]['name'] = $filename;
396 $files[$elname] = $_FILES[$elname]['tmp_name'];
399 // return errors if found
400 if (count($errors) == 0){
401 return true;
403 } else {
404 $files = array();
405 return $errors;
410 * Internal method. Validates filepicker and filemanager files if they are
411 * set as required fields. Also, sets the error message if encountered one.
413 * @return bool|array with errors
415 protected function validate_draft_files() {
416 global $USER;
417 $mform =& $this->_form;
419 $errors = array();
420 //Go through all the required elements and make sure you hit filepicker or
421 //filemanager element.
422 foreach ($mform->_rules as $elementname => $rules) {
423 $elementtype = $mform->getElementType($elementname);
424 //If element is of type filepicker then do validation
425 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
426 //Check if rule defined is required rule
427 foreach ($rules as $rule) {
428 if ($rule['type'] == 'required') {
429 $draftid = (int)$mform->getSubmitValue($elementname);
430 $fs = get_file_storage();
431 $context = context_user::instance($USER->id);
432 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
433 $errors[$elementname] = $rule['message'];
439 // Check all the filemanager elements to make sure they do not have too many
440 // files in them.
441 foreach ($mform->_elements as $element) {
442 if ($element->_type == 'filemanager') {
443 $maxfiles = $element->getMaxfiles();
444 if ($maxfiles > 0) {
445 $draftid = (int)$element->getValue();
446 $fs = get_file_storage();
447 $context = context_user::instance($USER->id);
448 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
449 if (count($files) > $maxfiles) {
450 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
455 if (empty($errors)) {
456 return true;
457 } else {
458 return $errors;
463 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
464 * form definition (new entry form); this function is used to load in data where values
465 * already exist and data is being edited (edit entry form).
467 * note: $slashed param removed
469 * @param stdClass|array $default_values object or array of default values
471 function set_data($default_values) {
472 if (is_object($default_values)) {
473 $default_values = (array)$default_values;
475 $this->_form->setDefaults($default_values);
479 * Check that form was submitted. Does not check validity of submitted data.
481 * @return bool true if form properly submitted
483 function is_submitted() {
484 return $this->_form->isSubmitted();
488 * Checks if button pressed is not for submitting the form
490 * @staticvar bool $nosubmit keeps track of no submit button
491 * @return bool
493 function no_submit_button_pressed(){
494 static $nosubmit = null; // one check is enough
495 if (!is_null($nosubmit)){
496 return $nosubmit;
498 $mform =& $this->_form;
499 $nosubmit = false;
500 if (!$this->is_submitted()){
501 return false;
503 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
504 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
505 $nosubmit = true;
506 break;
509 return $nosubmit;
514 * Check that form data is valid.
515 * You should almost always use this, rather than {@link validate_defined_fields}
517 * @return bool true if form data valid
519 function is_validated() {
520 //finalize the form definition before any processing
521 if (!$this->_definition_finalized) {
522 $this->_definition_finalized = true;
523 $this->definition_after_data();
526 return $this->validate_defined_fields();
530 * Validate the form.
532 * You almost always want to call {@link is_validated} instead of this
533 * because it calls {@link definition_after_data} first, before validating the form,
534 * which is what you want in 99% of cases.
536 * This is provided as a separate function for those special cases where
537 * you want the form validated before definition_after_data is called
538 * for example, to selectively add new elements depending on a no_submit_button press,
539 * but only when the form is valid when the no_submit_button is pressed,
541 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
542 * is NOT to validate the form when a no submit button has been pressed.
543 * pass true here to override this behaviour
545 * @return bool true if form data valid
547 function validate_defined_fields($validateonnosubmit=false) {
548 $mform =& $this->_form;
549 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
550 return false;
551 } elseif ($this->_validated === null) {
552 $internal_val = $mform->validate();
554 $files = array();
555 $file_val = $this->_validate_files($files);
556 //check draft files for validation and flag them if required files
557 //are not in draft area.
558 $draftfilevalue = $this->validate_draft_files();
560 if ($file_val !== true && $draftfilevalue !== true) {
561 $file_val = array_merge($file_val, $draftfilevalue);
562 } else if ($draftfilevalue !== true) {
563 $file_val = $draftfilevalue;
564 } //default is file_val, so no need to assign.
566 if ($file_val !== true) {
567 if (!empty($file_val)) {
568 foreach ($file_val as $element=>$msg) {
569 $mform->setElementError($element, $msg);
572 $file_val = false;
575 // Give the elements a chance to perform an implicit validation.
576 $element_val = true;
577 foreach ($mform->_elements as $element) {
578 if (method_exists($element, 'validateSubmitValue')) {
579 $value = $mform->getSubmitValue($element->getName());
580 $result = $element->validateSubmitValue($value);
581 if (!empty($result) && is_string($result)) {
582 $element_val = false;
583 $mform->setElementError($element->getName(), $result);
588 // Let the form instance validate the submitted values.
589 $data = $mform->exportValues();
590 $moodle_val = $this->validation($data, $files);
591 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
592 // non-empty array means errors
593 foreach ($moodle_val as $element=>$msg) {
594 $mform->setElementError($element, $msg);
596 $moodle_val = false;
598 } else {
599 // anything else means validation ok
600 $moodle_val = true;
603 $this->_validated = ($internal_val and $element_val and $moodle_val and $file_val);
605 return $this->_validated;
609 * Return true if a cancel button has been pressed resulting in the form being submitted.
611 * @return bool true if a cancel button has been pressed
613 function is_cancelled(){
614 $mform =& $this->_form;
615 if ($mform->isSubmitted()){
616 foreach ($mform->_cancelButtons as $cancelbutton){
617 if (optional_param($cancelbutton, 0, PARAM_RAW)){
618 return true;
622 return false;
626 * Return submitted data if properly submitted or returns NULL if validation fails or
627 * if there is no submitted data.
629 * note: $slashed param removed
631 * @return object submitted data; NULL if not valid or not submitted or cancelled
633 function get_data() {
634 $mform =& $this->_form;
636 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
637 $data = $mform->exportValues();
638 unset($data['sesskey']); // we do not need to return sesskey
639 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
640 if (empty($data)) {
641 return NULL;
642 } else {
643 return (object)$data;
645 } else {
646 return NULL;
651 * Return submitted data without validation or NULL if there is no submitted data.
652 * note: $slashed param removed
654 * @return object submitted data; NULL if not submitted
656 function get_submitted_data() {
657 $mform =& $this->_form;
659 if ($this->is_submitted()) {
660 $data = $mform->exportValues();
661 unset($data['sesskey']); // we do not need to return sesskey
662 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
663 if (empty($data)) {
664 return NULL;
665 } else {
666 return (object)$data;
668 } else {
669 return NULL;
674 * Save verified uploaded files into directory. Upload process can be customised from definition()
676 * @deprecated since Moodle 2.0
677 * @todo MDL-31294 remove this api
678 * @see moodleform::save_stored_file()
679 * @see moodleform::save_file()
680 * @param string $destination path where file should be stored
681 * @return bool Always false
683 function save_files($destination) {
684 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
685 return false;
689 * Returns name of uploaded file.
691 * @param string $elname first element if null
692 * @return string|bool false in case of failure, string if ok
694 function get_new_filename($elname=null) {
695 global $USER;
697 if (!$this->is_submitted() or !$this->is_validated()) {
698 return false;
701 if (is_null($elname)) {
702 if (empty($_FILES)) {
703 return false;
705 reset($_FILES);
706 $elname = key($_FILES);
709 if (empty($elname)) {
710 return false;
713 $element = $this->_form->getElement($elname);
715 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
716 $values = $this->_form->exportValues($elname);
717 if (empty($values[$elname])) {
718 return false;
720 $draftid = $values[$elname];
721 $fs = get_file_storage();
722 $context = context_user::instance($USER->id);
723 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
724 return false;
726 $file = reset($files);
727 return $file->get_filename();
730 if (!isset($_FILES[$elname])) {
731 return false;
734 return $_FILES[$elname]['name'];
738 * Save file to standard filesystem
740 * @param string $elname name of element
741 * @param string $pathname full path name of file
742 * @param bool $override override file if exists
743 * @return bool success
745 function save_file($elname, $pathname, $override=false) {
746 global $USER;
748 if (!$this->is_submitted() or !$this->is_validated()) {
749 return false;
751 if (file_exists($pathname)) {
752 if ($override) {
753 if (!@unlink($pathname)) {
754 return false;
756 } else {
757 return false;
761 $element = $this->_form->getElement($elname);
763 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
764 $values = $this->_form->exportValues($elname);
765 if (empty($values[$elname])) {
766 return false;
768 $draftid = $values[$elname];
769 $fs = get_file_storage();
770 $context = context_user::instance($USER->id);
771 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
772 return false;
774 $file = reset($files);
776 return $file->copy_content_to($pathname);
778 } else if (isset($_FILES[$elname])) {
779 return copy($_FILES[$elname]['tmp_name'], $pathname);
782 return false;
786 * Returns a temporary file, do not forget to delete after not needed any more.
788 * @param string $elname name of the elmenet
789 * @return string|bool either string or false
791 function save_temp_file($elname) {
792 if (!$this->get_new_filename($elname)) {
793 return false;
795 if (!$dir = make_temp_directory('forms')) {
796 return false;
798 if (!$tempfile = tempnam($dir, 'tempup_')) {
799 return false;
801 if (!$this->save_file($elname, $tempfile, true)) {
802 // something went wrong
803 @unlink($tempfile);
804 return false;
807 return $tempfile;
811 * Get draft files of a form element
812 * This is a protected method which will be used only inside moodleforms
814 * @param string $elname name of element
815 * @return array|bool|null
817 protected function get_draft_files($elname) {
818 global $USER;
820 if (!$this->is_submitted()) {
821 return false;
824 $element = $this->_form->getElement($elname);
826 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
827 $values = $this->_form->exportValues($elname);
828 if (empty($values[$elname])) {
829 return false;
831 $draftid = $values[$elname];
832 $fs = get_file_storage();
833 $context = context_user::instance($USER->id);
834 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
835 return null;
837 return $files;
839 return null;
843 * Save file to local filesystem pool
845 * @param string $elname name of element
846 * @param int $newcontextid id of context
847 * @param string $newcomponent name of the component
848 * @param string $newfilearea name of file area
849 * @param int $newitemid item id
850 * @param string $newfilepath path of file where it get stored
851 * @param string $newfilename use specified filename, if not specified name of uploaded file used
852 * @param bool $overwrite overwrite file if exists
853 * @param int $newuserid new userid if required
854 * @return mixed stored_file object or false if error; may throw exception if duplicate found
856 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
857 $newfilename=null, $overwrite=false, $newuserid=null) {
858 global $USER;
860 if (!$this->is_submitted() or !$this->is_validated()) {
861 return false;
864 if (empty($newuserid)) {
865 $newuserid = $USER->id;
868 $element = $this->_form->getElement($elname);
869 $fs = get_file_storage();
871 if ($element instanceof MoodleQuickForm_filepicker) {
872 $values = $this->_form->exportValues($elname);
873 if (empty($values[$elname])) {
874 return false;
876 $draftid = $values[$elname];
877 $context = context_user::instance($USER->id);
878 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
879 return false;
881 $file = reset($files);
882 if (is_null($newfilename)) {
883 $newfilename = $file->get_filename();
886 if ($overwrite) {
887 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
888 if (!$oldfile->delete()) {
889 return false;
894 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
895 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
896 return $fs->create_file_from_storedfile($file_record, $file);
898 } else if (isset($_FILES[$elname])) {
899 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
901 if ($overwrite) {
902 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
903 if (!$oldfile->delete()) {
904 return false;
909 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
910 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
911 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
914 return false;
918 * Get content of uploaded file.
920 * @param string $elname name of file upload element
921 * @return string|bool false in case of failure, string if ok
923 function get_file_content($elname) {
924 global $USER;
926 if (!$this->is_submitted() or !$this->is_validated()) {
927 return false;
930 $element = $this->_form->getElement($elname);
932 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
933 $values = $this->_form->exportValues($elname);
934 if (empty($values[$elname])) {
935 return false;
937 $draftid = $values[$elname];
938 $fs = get_file_storage();
939 $context = context_user::instance($USER->id);
940 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
941 return false;
943 $file = reset($files);
945 return $file->get_content();
947 } else if (isset($_FILES[$elname])) {
948 return file_get_contents($_FILES[$elname]['tmp_name']);
951 return false;
955 * Print html form.
957 function display() {
958 //finalize the form definition if not yet done
959 if (!$this->_definition_finalized) {
960 $this->_definition_finalized = true;
961 $this->definition_after_data();
964 $this->_form->display();
968 * Renders the html form (same as display, but returns the result).
970 * Note that you can only output this rendered result once per page, as
971 * it contains IDs which must be unique.
973 * @return string HTML code for the form
975 public function render() {
976 ob_start();
977 $this->display();
978 $out = ob_get_contents();
979 ob_end_clean();
980 return $out;
984 * Form definition. Abstract method - always override!
986 protected abstract function definition();
989 * After definition hook.
991 * This is useful for intermediate classes to inject logic after the definition was
992 * provided without requiring developers to call the parent {{@link self::definition()}}
993 * as it's not obvious by design. The 'intermediate' class is 'MyClass extends
994 * IntermediateClass extends moodleform'.
996 * Classes overriding this method should always call the parent. We may not add
997 * anything specifically in this instance of the method, but intermediate classes
998 * are likely to do so, and so it is a good practice to always call the parent.
1000 * @return void
1002 protected function after_definition() {
1006 * Dummy stub method - override if you need to setup the form depending on current
1007 * values. This method is called after definition(), data submission and set_data().
1008 * All form setup that is dependent on form values should go in here.
1010 function definition_after_data(){
1014 * Dummy stub method - override if you needed to perform some extra validation.
1015 * If there are errors return array of errors ("fieldname"=>"error message"),
1016 * otherwise true if ok.
1018 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
1020 * @param array $data array of ("fieldname"=>value) of submitted data
1021 * @param array $files array of uploaded files "element_name"=>tmp_file_path
1022 * @return array of "element_name"=>"error_description" if there are errors,
1023 * or an empty array if everything is OK (true allowed for backwards compatibility too).
1025 function validation($data, $files) {
1026 return array();
1030 * Helper used by {@link repeat_elements()}.
1032 * @param int $i the index of this element.
1033 * @param HTML_QuickForm_element $elementclone
1034 * @param array $namecloned array of names
1036 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1037 $name = $elementclone->getName();
1038 $namecloned[] = $name;
1040 if (!empty($name)) {
1041 $elementclone->setName($name."[$i]");
1044 if (is_a($elementclone, 'HTML_QuickForm_header')) {
1045 $value = $elementclone->_text;
1046 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1048 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1049 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1051 } else {
1052 $value=$elementclone->getLabel();
1053 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1058 * Method to add a repeating group of elements to a form.
1060 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1061 * @param int $repeats no of times to repeat elements initially
1062 * @param array $options a nested array. The first array key is the element name.
1063 * the second array key is the type of option to set, and depend on that option,
1064 * the value takes different forms.
1065 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1066 * 'type' - PARAM_* type.
1067 * 'helpbutton' - array containing the helpbutton params.
1068 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1069 * 'rule' - array containing the addRule arguments after the element name.
1070 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1071 * 'advanced' - whether this element is hidden by 'Show more ...'.
1072 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1073 * @param string $addfieldsname name for button to add more fields
1074 * @param int $addfieldsno how many fields to add at a time
1075 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1076 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1077 * @return int no of repeats of element in this page
1079 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1080 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1081 if ($addstring===null){
1082 $addstring = get_string('addfields', 'form', $addfieldsno);
1083 } else {
1084 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1086 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1087 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1088 if (!empty($addfields)){
1089 $repeats += $addfieldsno;
1091 $mform =& $this->_form;
1092 $mform->registerNoSubmitButton($addfieldsname);
1093 $mform->addElement('hidden', $repeathiddenname, $repeats);
1094 $mform->setType($repeathiddenname, PARAM_INT);
1095 //value not to be overridden by submitted value
1096 $mform->setConstants(array($repeathiddenname=>$repeats));
1097 $namecloned = array();
1098 for ($i = 0; $i < $repeats; $i++) {
1099 foreach ($elementobjs as $elementobj){
1100 $elementclone = fullclone($elementobj);
1101 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1103 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1104 foreach ($elementclone->getElements() as $el) {
1105 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1107 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1110 $mform->addElement($elementclone);
1113 for ($i=0; $i<$repeats; $i++) {
1114 foreach ($options as $elementname => $elementoptions){
1115 $pos=strpos($elementname, '[');
1116 if ($pos!==FALSE){
1117 $realelementname = substr($elementname, 0, $pos)."[$i]";
1118 $realelementname .= substr($elementname, $pos);
1119 }else {
1120 $realelementname = $elementname."[$i]";
1122 foreach ($elementoptions as $option => $params){
1124 switch ($option){
1125 case 'default' :
1126 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1127 break;
1128 case 'helpbutton' :
1129 $params = array_merge(array($realelementname), $params);
1130 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1131 break;
1132 case 'disabledif' :
1133 foreach ($namecloned as $num => $name){
1134 if ($params[0] == $name){
1135 $params[0] = $params[0]."[$i]";
1136 break;
1139 $params = array_merge(array($realelementname), $params);
1140 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1141 break;
1142 case 'rule' :
1143 if (is_string($params)){
1144 $params = array(null, $params, null, 'client');
1146 $params = array_merge(array($realelementname), $params);
1147 call_user_func_array(array(&$mform, 'addRule'), $params);
1148 break;
1150 case 'type':
1151 $mform->setType($realelementname, $params);
1152 break;
1154 case 'expanded':
1155 $mform->setExpanded($realelementname, $params);
1156 break;
1158 case 'advanced' :
1159 $mform->setAdvanced($realelementname, $params);
1160 break;
1165 $mform->addElement('submit', $addfieldsname, $addstring);
1167 if (!$addbuttoninside) {
1168 $mform->closeHeaderBefore($addfieldsname);
1171 return $repeats;
1175 * Adds a link/button that controls the checked state of a group of checkboxes.
1177 * @param int $groupid The id of the group of advcheckboxes this element controls
1178 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1179 * @param array $attributes associative array of HTML attributes
1180 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1182 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1183 global $CFG, $PAGE;
1185 // Name of the controller button
1186 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1187 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1188 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1190 // Set the default text if none was specified
1191 if (empty($text)) {
1192 $text = get_string('selectallornone', 'form');
1195 $mform = $this->_form;
1196 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1197 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1199 $newselectvalue = $selectvalue;
1200 if (is_null($selectvalue)) {
1201 $newselectvalue = $originalValue;
1202 } else if (!is_null($contollerbutton)) {
1203 $newselectvalue = (int) !$selectvalue;
1205 // set checkbox state depending on orignal/submitted value by controoler button
1206 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1207 foreach ($mform->_elements as $element) {
1208 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1209 $element->getAttribute('class') == $checkboxgroupclass &&
1210 !$element->isFrozen()) {
1211 $mform->setConstants(array($element->getName() => $newselectvalue));
1216 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1217 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1218 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1220 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1221 array(
1222 array('groupid' => $groupid,
1223 'checkboxclass' => $checkboxgroupclass,
1224 'checkboxcontroller' => $checkboxcontrollerparam,
1225 'controllerbutton' => $checkboxcontrollername)
1229 require_once("$CFG->libdir/form/submit.php");
1230 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1231 $mform->addElement($submitlink);
1232 $mform->registerNoSubmitButton($checkboxcontrollername);
1233 $mform->setDefault($checkboxcontrollername, $text);
1237 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1238 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1239 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1240 * get data with get_data().
1242 * @param bool $cancel whether to show cancel button, default true
1243 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1245 function add_action_buttons($cancel = true, $submitlabel=null){
1246 if (is_null($submitlabel)){
1247 $submitlabel = get_string('savechanges');
1249 $mform =& $this->_form;
1250 if ($cancel){
1251 //when two elements we need a group
1252 $buttonarray=array();
1253 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1254 $buttonarray[] = &$mform->createElement('cancel');
1255 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1256 $mform->closeHeaderBefore('buttonar');
1257 } else {
1258 //no group needed
1259 $mform->addElement('submit', 'submitbutton', $submitlabel);
1260 $mform->closeHeaderBefore('submitbutton');
1265 * Adds an initialisation call for a standard JavaScript enhancement.
1267 * This function is designed to add an initialisation call for a JavaScript
1268 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1270 * Current options:
1271 * - Selectboxes
1272 * - smartselect: Turns a nbsp indented select box into a custom drop down
1273 * control that supports multilevel and category selection.
1274 * $enhancement = 'smartselect';
1275 * $options = array('selectablecategories' => true|false)
1277 * @param string|element $element form element for which Javascript needs to be initalized
1278 * @param string $enhancement which init function should be called
1279 * @param array $options options passed to javascript
1280 * @param array $strings strings for javascript
1281 * @deprecated since Moodle 3.3 MDL-57471
1283 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1284 debugging('$mform->init_javascript_enhancement() is deprecated and no longer does anything. '.
1285 'smartselect uses should be converted to the searchableselector form element.', DEBUG_DEVELOPER);
1289 * Returns a JS module definition for the mforms JS
1291 * @return array
1293 public static function get_js_module() {
1294 global $CFG;
1295 return array(
1296 'name' => 'mform',
1297 'fullpath' => '/lib/form/form.js',
1298 'requires' => array('base', 'node')
1303 * Detects elements with missing setType() declerations.
1305 * Finds elements in the form which should a PARAM_ type set and throws a
1306 * developer debug warning for any elements without it. This is to reduce the
1307 * risk of potential security issues by developers mistakenly forgetting to set
1308 * the type.
1310 * @return void
1312 private function detectMissingSetType() {
1313 global $CFG;
1315 if (!$CFG->debugdeveloper) {
1316 // Only for devs.
1317 return;
1320 $mform = $this->_form;
1321 foreach ($mform->_elements as $element) {
1322 $group = false;
1323 $elements = array($element);
1325 if ($element->getType() == 'group') {
1326 $group = $element;
1327 $elements = $element->getElements();
1330 foreach ($elements as $index => $element) {
1331 switch ($element->getType()) {
1332 case 'hidden':
1333 case 'text':
1334 case 'url':
1335 if ($group) {
1336 $name = $group->getElementName($index);
1337 } else {
1338 $name = $element->getName();
1340 $key = $name;
1341 $found = array_key_exists($key, $mform->_types);
1342 // For repeated elements we need to look for
1343 // the "main" type, not for the one present
1344 // on each repetition. All the stuff in formslib
1345 // (repeat_elements(), updateSubmission()... seems
1346 // to work that way.
1347 while (!$found && strrpos($key, '[') !== false) {
1348 $pos = strrpos($key, '[');
1349 $key = substr($key, 0, $pos);
1350 $found = array_key_exists($key, $mform->_types);
1352 if (!$found) {
1353 debugging("Did you remember to call setType() for '$name'? ".
1354 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1356 break;
1363 * Used by tests to simulate submitted form data submission from the user.
1365 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1366 * get_data.
1368 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1369 * global arrays after each test.
1371 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1372 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1373 * @param string $method 'post' or 'get', defaults to 'post'.
1374 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1375 * a different value here for some forms that are used more than once on the
1376 * same page.
1378 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1379 $formidentifier = null) {
1380 $_FILES = $simulatedsubmittedfiles;
1381 if ($formidentifier === null) {
1382 $formidentifier = get_called_class();
1383 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1385 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1386 $simulatedsubmitteddata['sesskey'] = sesskey();
1387 if (strtolower($method) === 'get') {
1388 $_GET = $simulatedsubmitteddata;
1389 } else {
1390 $_POST = $simulatedsubmitteddata;
1395 * Used by tests to generate valid submit keys for moodle forms that are
1396 * submitted with ajax data.
1398 * @throws \moodle_exception If called outside unit test environment
1399 * @param array $data Existing form data you wish to add the keys to.
1400 * @return array
1402 public static function mock_generate_submit_keys($data = []) {
1403 if (!defined('PHPUNIT_TEST') || !PHPUNIT_TEST) {
1404 throw new \moodle_exception("This function can only be used for unit testing.");
1407 $formidentifier = get_called_class();
1408 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1409 $data['sesskey'] = sesskey();
1410 $data['_qf__' . $formidentifier] = 1;
1412 return $data;
1416 * Set display mode for the form when labels take full width of the form and above the elements even on big screens
1418 * Useful for forms displayed inside modals or in narrow containers
1420 public function set_display_vertical() {
1421 $oldclass = $this->_form->getAttribute('class');
1422 $this->_form->updateAttributes(array('class' => $oldclass . ' full-width-labels'));
1427 * MoodleQuickForm implementation
1429 * You never extend this class directly. The class methods of this class are available from
1430 * the private $this->_form property on moodleform and its children. You generally only
1431 * call methods on this class from within abstract methods that you override on moodleform such
1432 * as definition and definition_after_data
1434 * @package core_form
1435 * @category form
1436 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1437 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1439 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1440 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1441 var $_types = array();
1443 /** @var array dependent state for the element/'s */
1444 var $_dependencies = array();
1447 * @var array elements that will become hidden based on another element
1449 protected $_hideifs = array();
1451 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1452 var $_noSubmitButtons=array();
1454 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1455 var $_cancelButtons=array();
1457 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1458 var $_advancedElements = array();
1461 * Array whose keys are element names and values are the desired collapsible state.
1462 * True for collapsed, False for expanded. If not present, set to default in
1463 * {@link self::accept()}.
1465 * @var array
1467 var $_collapsibleElements = array();
1470 * Whether to enable shortforms for this form
1472 * @var boolean
1474 var $_disableShortforms = false;
1476 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1477 protected $_use_form_change_checker = true;
1480 * The form name is derived from the class name of the wrapper minus the trailing form
1481 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1482 * @var string
1484 var $_formName = '';
1487 * String with the html for hidden params passed in as part of a moodle_url
1488 * object for the action. Output in the form.
1489 * @var string
1491 var $_pageparams = '';
1494 * Whether the form contains any client-side validation or not.
1495 * @var bool
1497 protected $clientvalidation = false;
1500 * Is this a 'disableIf' dependency ?
1502 const DEP_DISABLE = 0;
1505 * Is this a 'hideIf' dependency?
1507 const DEP_HIDE = 1;
1510 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1512 * @staticvar int $formcounter counts number of forms
1513 * @param string $formName Form's name.
1514 * @param string $method Form's method defaults to 'POST'
1515 * @param string|moodle_url $action Form's action
1516 * @param string $target (optional)Form's target defaults to none
1517 * @param mixed $attributes (optional)Extra attributes for <form> tag
1519 public function __construct($formName, $method, $action, $target='', $attributes=null) {
1520 global $CFG, $OUTPUT;
1522 static $formcounter = 1;
1524 // TODO MDL-52313 Replace with the call to parent::__construct().
1525 HTML_Common::__construct($attributes);
1526 $target = empty($target) ? array() : array('target' => $target);
1527 $this->_formName = $formName;
1528 if (is_a($action, 'moodle_url')){
1529 $this->_pageparams = html_writer::input_hidden_params($action);
1530 $action = $action->out_omit_querystring();
1531 } else {
1532 $this->_pageparams = '';
1534 // No 'name' atttribute for form in xhtml strict :
1535 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1536 if (is_null($this->getAttribute('id'))) {
1537 // Append a random id, forms can be loaded in different requests using Fragments API.
1538 $attributes['id'] = 'mform' . $formcounter . '_' . random_string();
1540 $formcounter++;
1541 $this->updateAttributes($attributes);
1543 // This is custom stuff for Moodle :
1544 $oldclass= $this->getAttribute('class');
1545 if (!empty($oldclass)){
1546 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1547 }else {
1548 $this->updateAttributes(array('class'=>'mform'));
1550 $this->_reqHTML = '<span class="req">' . $OUTPUT->pix_icon('req', get_string('requiredelement', 'form')) . '</span>';
1551 $this->_advancedHTML = '<span class="adv">' . $OUTPUT->pix_icon('adv', get_string('advancedelement', 'form')) . '</span>';
1552 $this->setRequiredNote(get_string('somefieldsrequired', 'form', $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'))));
1556 * Old syntax of class constructor. Deprecated in PHP7.
1558 * @deprecated since Moodle 3.1
1560 public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1561 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1562 self::__construct($formName, $method, $action, $target, $attributes);
1566 * Use this method to indicate an element in a form is an advanced field. If items in a form
1567 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1568 * form so the user can decide whether to display advanced form controls.
1570 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1572 * @param string $elementName group or element name (not the element name of something inside a group).
1573 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1575 function setAdvanced($elementName, $advanced = true) {
1576 if ($advanced){
1577 $this->_advancedElements[$elementName]='';
1578 } elseif (isset($this->_advancedElements[$elementName])) {
1579 unset($this->_advancedElements[$elementName]);
1584 * Use this method to indicate that the fieldset should be shown as expanded.
1585 * The method is applicable to header elements only.
1587 * @param string $headername header element name
1588 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1589 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1590 * the form was submitted.
1591 * @return void
1593 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1594 if (empty($headername)) {
1595 return;
1597 $element = $this->getElement($headername);
1598 if ($element->getType() != 'header') {
1599 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1600 return;
1602 if (!$headerid = $element->getAttribute('id')) {
1603 $element->_generateId();
1604 $headerid = $element->getAttribute('id');
1606 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1607 // See if the form has been submitted already.
1608 $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1609 if (!$ignoreuserstate && $formexpanded != -1) {
1610 // Override expanded state with the form variable.
1611 $expanded = $formexpanded;
1613 // Create the form element for storing expanded state.
1614 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1615 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1616 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1618 $this->_collapsibleElements[$headername] = !$expanded;
1622 * Use this method to add show more/less status element required for passing
1623 * over the advanced elements visibility status on the form submission.
1625 * @param string $headerName header element name.
1626 * @param boolean $showmore default false sets the advanced elements to be hidden.
1628 function addAdvancedStatusElement($headerid, $showmore=false){
1629 // Add extra hidden element to store advanced items state for each section.
1630 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1631 // See if we the form has been submitted already.
1632 $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1633 if (!$showmore && $formshowmore != -1) {
1634 // Override showmore state with the form variable.
1635 $showmore = $formshowmore;
1637 // Create the form element for storing advanced items state.
1638 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1639 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1640 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1645 * This function has been deprecated. Show advanced has been replaced by
1646 * "Show more.../Show less..." in the shortforms javascript module.
1648 * @deprecated since Moodle 2.5
1649 * @param bool $showadvancedNow if true will show advanced elements.
1651 function setShowAdvanced($showadvancedNow = null){
1652 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1656 * This function has been deprecated. Show advanced has been replaced by
1657 * "Show more.../Show less..." in the shortforms javascript module.
1659 * @deprecated since Moodle 2.5
1660 * @return bool (Always false)
1662 function getShowAdvanced(){
1663 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1664 return false;
1668 * Use this method to indicate that the form will not be using shortforms.
1670 * @param boolean $disable default true, controls if the shortforms are disabled.
1672 function setDisableShortforms ($disable = true) {
1673 $this->_disableShortforms = $disable;
1677 * Call this method if you don't want the formchangechecker JavaScript to be
1678 * automatically initialised for this form.
1680 public function disable_form_change_checker() {
1681 $this->_use_form_change_checker = false;
1685 * If you have called {@link disable_form_change_checker()} then you can use
1686 * this method to re-enable it. It is enabled by default, so normally you don't
1687 * need to call this.
1689 public function enable_form_change_checker() {
1690 $this->_use_form_change_checker = true;
1694 * @return bool whether this form should automatically initialise
1695 * formchangechecker for itself.
1697 public function is_form_change_checker_enabled() {
1698 return $this->_use_form_change_checker;
1702 * Accepts a renderer
1704 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1706 function accept(&$renderer) {
1707 if (method_exists($renderer, 'setAdvancedElements')){
1708 //Check for visible fieldsets where all elements are advanced
1709 //and mark these headers as advanced as well.
1710 //Also mark all elements in a advanced header as advanced.
1711 $stopFields = $renderer->getStopFieldSetElements();
1712 $lastHeader = null;
1713 $lastHeaderAdvanced = false;
1714 $anyAdvanced = false;
1715 $anyError = false;
1716 foreach (array_keys($this->_elements) as $elementIndex){
1717 $element =& $this->_elements[$elementIndex];
1719 // if closing header and any contained element was advanced then mark it as advanced
1720 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1721 if ($anyAdvanced && !is_null($lastHeader)) {
1722 $lastHeader->_generateId();
1723 $this->setAdvanced($lastHeader->getName());
1724 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1726 $lastHeaderAdvanced = false;
1727 unset($lastHeader);
1728 $lastHeader = null;
1729 } elseif ($lastHeaderAdvanced) {
1730 $this->setAdvanced($element->getName());
1733 if ($element->getType()=='header'){
1734 $lastHeader =& $element;
1735 $anyAdvanced = false;
1736 $anyError = false;
1737 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1738 } elseif (isset($this->_advancedElements[$element->getName()])){
1739 $anyAdvanced = true;
1740 if (isset($this->_errors[$element->getName()])) {
1741 $anyError = true;
1745 // the last header may not be closed yet...
1746 if ($anyAdvanced && !is_null($lastHeader)){
1747 $this->setAdvanced($lastHeader->getName());
1748 $lastHeader->_generateId();
1749 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1751 $renderer->setAdvancedElements($this->_advancedElements);
1753 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1755 // Count the number of sections.
1756 $headerscount = 0;
1757 foreach (array_keys($this->_elements) as $elementIndex){
1758 $element =& $this->_elements[$elementIndex];
1759 if ($element->getType() == 'header') {
1760 $headerscount++;
1764 $anyrequiredorerror = false;
1765 $headercounter = 0;
1766 $headername = null;
1767 foreach (array_keys($this->_elements) as $elementIndex){
1768 $element =& $this->_elements[$elementIndex];
1770 if ($element->getType() == 'header') {
1771 $headercounter++;
1772 $element->_generateId();
1773 $headername = $element->getName();
1774 $anyrequiredorerror = false;
1775 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1776 $anyrequiredorerror = true;
1777 } else {
1778 // Do not reset $anyrequiredorerror to false because we do not want any other element
1779 // in this header (fieldset) to possibly revert the state given.
1782 if ($element->getType() == 'header') {
1783 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1784 // By default the first section is always expanded, except if a state has already been set.
1785 $this->setExpanded($headername, true);
1786 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1787 // The second section is always expanded if the form only contains 2 sections),
1788 // except if a state has already been set.
1789 $this->setExpanded($headername, true);
1791 } else if ($anyrequiredorerror) {
1792 // If any error or required field are present within the header, we need to expand it.
1793 $this->setExpanded($headername, true, true);
1794 } else if (!isset($this->_collapsibleElements[$headername])) {
1795 // Define element as collapsed by default.
1796 $this->setExpanded($headername, false);
1800 // Pass the array to renderer object.
1801 $renderer->setCollapsibleElements($this->_collapsibleElements);
1803 parent::accept($renderer);
1807 * Adds one or more element names that indicate the end of a fieldset
1809 * @param string $elementName name of the element
1811 function closeHeaderBefore($elementName){
1812 $renderer =& $this->defaultRenderer();
1813 $renderer->addStopFieldsetElements($elementName);
1817 * Set an element to be forced to flow LTR.
1819 * The element must exist and support this functionality. Also note that
1820 * when setting the type of a field (@link self::setType} we try to guess the
1821 * whether the field should be force to LTR or not. Make sure you're always
1822 * calling this method last.
1824 * @param string $elementname The element name.
1825 * @param bool $value When false, disables force LTR, else enables it.
1827 public function setForceLtr($elementname, $value = true) {
1828 $this->getElement($elementname)->set_force_ltr($value);
1832 * Should be used for all elements of a form except for select, radio and checkboxes which
1833 * clean their own data.
1835 * @param string $elementname
1836 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1837 * {@link lib/moodlelib.php} for defined parameter types
1839 function setType($elementname, $paramtype) {
1840 $this->_types[$elementname] = $paramtype;
1842 // This will not always get it right, but it should be accurate in most cases.
1843 // When inaccurate use setForceLtr().
1844 if (!is_rtl_compatible($paramtype)
1845 && $this->elementExists($elementname)
1846 && ($element =& $this->getElement($elementname))
1847 && method_exists($element, 'set_force_ltr')) {
1849 $element->set_force_ltr(true);
1854 * This can be used to set several types at once.
1856 * @param array $paramtypes types of parameters.
1857 * @see MoodleQuickForm::setType
1859 function setTypes($paramtypes) {
1860 foreach ($paramtypes as $elementname => $paramtype) {
1861 $this->setType($elementname, $paramtype);
1866 * Return the type(s) to use to clean an element.
1868 * In the case where the element has an array as a value, we will try to obtain a
1869 * type defined for that specific key, and recursively until done.
1871 * This method does not work reverse, you cannot pass a nested element and hoping to
1872 * fallback on the clean type of a parent. This method intends to be used with the
1873 * main element, which will generate child types if needed, not the other way around.
1875 * Example scenario:
1877 * You have defined a new repeated element containing a text field called 'foo'.
1878 * By default there will always be 2 occurence of 'foo' in the form. Even though
1879 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1880 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1881 * $mform->setType('foo[0]', PARAM_FLOAT).
1883 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1884 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1885 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1886 * get the default clean type returned (param $default).
1888 * @param string $elementname name of the element.
1889 * @param mixed $value value that should be cleaned.
1890 * @param int $default default constant value to be returned (PARAM_...)
1891 * @return string|array constant value or array of constant values (PARAM_...)
1893 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1894 $type = $default;
1895 if (array_key_exists($elementname, $this->_types)) {
1896 $type = $this->_types[$elementname];
1898 if (is_array($value)) {
1899 $default = $type;
1900 $type = array();
1901 foreach ($value as $subkey => $subvalue) {
1902 $typekey = "$elementname" . "[$subkey]";
1903 if (array_key_exists($typekey, $this->_types)) {
1904 $subtype = $this->_types[$typekey];
1905 } else {
1906 $subtype = $default;
1908 if (is_array($subvalue)) {
1909 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1910 } else {
1911 $type[$subkey] = $subtype;
1915 return $type;
1919 * Return the cleaned value using the passed type(s).
1921 * @param mixed $value value that has to be cleaned.
1922 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1923 * @return mixed cleaned up value.
1925 public function getCleanedValue($value, $type) {
1926 if (is_array($type) && is_array($value)) {
1927 foreach ($type as $key => $param) {
1928 $value[$key] = $this->getCleanedValue($value[$key], $param);
1930 } else if (!is_array($type) && !is_array($value)) {
1931 $value = clean_param($value, $type);
1932 } else if (!is_array($type) && is_array($value)) {
1933 $value = clean_param_array($value, $type, true);
1934 } else {
1935 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1937 return $value;
1941 * Updates submitted values
1943 * @param array $submission submitted values
1944 * @param array $files list of files
1946 function updateSubmission($submission, $files) {
1947 $this->_flagSubmitted = false;
1949 if (empty($submission)) {
1950 $this->_submitValues = array();
1951 } else {
1952 foreach ($submission as $key => $s) {
1953 $type = $this->getCleanType($key, $s);
1954 $submission[$key] = $this->getCleanedValue($s, $type);
1956 $this->_submitValues = $submission;
1957 $this->_flagSubmitted = true;
1960 if (empty($files)) {
1961 $this->_submitFiles = array();
1962 } else {
1963 $this->_submitFiles = $files;
1964 $this->_flagSubmitted = true;
1967 // need to tell all elements that they need to update their value attribute.
1968 foreach (array_keys($this->_elements) as $key) {
1969 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1974 * Returns HTML for required elements
1976 * @return string
1978 function getReqHTML(){
1979 return $this->_reqHTML;
1983 * Returns HTML for advanced elements
1985 * @return string
1987 function getAdvancedHTML(){
1988 return $this->_advancedHTML;
1992 * Initializes a default form value. Used to specify the default for a new entry where
1993 * no data is loaded in using moodleform::set_data()
1995 * note: $slashed param removed
1997 * @param string $elementName element name
1998 * @param mixed $defaultValue values for that element name
2000 function setDefault($elementName, $defaultValue){
2001 $this->setDefaults(array($elementName=>$defaultValue));
2005 * Add a help button to element, only one button per element is allowed.
2007 * This is new, simplified and preferable method of setting a help icon on form elements.
2008 * It uses the new $OUTPUT->help_icon().
2010 * Typically, you will provide the same identifier and the component as you have used for the
2011 * label of the element. The string identifier with the _help suffix added is then used
2012 * as the help string.
2014 * There has to be two strings defined:
2015 * 1/ get_string($identifier, $component) - the title of the help page
2016 * 2/ get_string($identifier.'_help', $component) - the actual help page text
2018 * @since Moodle 2.0
2019 * @param string $elementname name of the element to add the item to
2020 * @param string $identifier help string identifier without _help suffix
2021 * @param string $component component name to look the help string in
2022 * @param string $linktext optional text to display next to the icon
2023 * @param bool $suppresscheck set to true if the element may not exist
2025 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
2026 global $OUTPUT;
2027 if (array_key_exists($elementname, $this->_elementIndex)) {
2028 $element = $this->_elements[$this->_elementIndex[$elementname]];
2029 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
2030 } else if (!$suppresscheck) {
2031 debugging(get_string('nonexistentformelements', 'form', $elementname));
2036 * Set constant value not overridden by _POST or _GET
2037 * note: this does not work for complex names with [] :-(
2039 * @param string $elname name of element
2040 * @param mixed $value
2042 function setConstant($elname, $value) {
2043 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
2044 $element =& $this->getElement($elname);
2045 $element->onQuickFormEvent('updateValue', null, $this);
2049 * export submitted values
2051 * @param string $elementList list of elements in form
2052 * @return array
2054 function exportValues($elementList = null){
2055 $unfiltered = array();
2056 if (null === $elementList) {
2057 // iterate over all elements, calling their exportValue() methods
2058 foreach (array_keys($this->_elements) as $key) {
2059 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
2060 $varname = $this->_elements[$key]->_attributes['name'];
2061 $value = '';
2062 // If we have a default value then export it.
2063 if (isset($this->_defaultValues[$varname])) {
2064 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
2066 } else {
2067 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
2070 if (is_array($value)) {
2071 // This shit throws a bogus warning in PHP 4.3.x
2072 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2075 } else {
2076 if (!is_array($elementList)) {
2077 $elementList = array_map('trim', explode(',', $elementList));
2079 foreach ($elementList as $elementName) {
2080 $value = $this->exportValue($elementName);
2081 if (@PEAR::isError($value)) {
2082 return $value;
2084 //oh, stock QuickFOrm was returning array of arrays!
2085 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2089 if (is_array($this->_constantValues)) {
2090 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
2092 return $unfiltered;
2096 * This is a bit of a hack, and it duplicates the code in
2097 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
2098 * reliably calling that code. (Think about date selectors, for example.)
2099 * @param string $name the element name.
2100 * @param mixed $value the fixed value to set.
2101 * @return mixed the appropriate array to add to the $unfiltered array.
2103 protected function prepare_fixed_value($name, $value) {
2104 if (null === $value) {
2105 return null;
2106 } else {
2107 if (!strpos($name, '[')) {
2108 return array($name => $value);
2109 } else {
2110 $valueAry = array();
2111 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2112 eval("\$valueAry$myIndex = \$value;");
2113 return $valueAry;
2119 * Adds a validation rule for the given field
2121 * If the element is in fact a group, it will be considered as a whole.
2122 * To validate grouped elements as separated entities,
2123 * use addGroupRule instead of addRule.
2125 * @param string $element Form element name
2126 * @param string $message Message to display for invalid data
2127 * @param string $type Rule type, use getRegisteredRules() to get types
2128 * @param string $format (optional)Required for extra rule data
2129 * @param string $validation (optional)Where to perform validation: "server", "client"
2130 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2131 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2133 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2135 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2136 if ($validation == 'client') {
2137 $this->clientvalidation = true;
2143 * Adds a validation rule for the given group of elements
2145 * Only groups with a name can be assigned a validation rule
2146 * Use addGroupRule when you need to validate elements inside the group.
2147 * Use addRule if you need to validate the group as a whole. In this case,
2148 * the same rule will be applied to all elements in the group.
2149 * Use addRule if you need to validate the group against a function.
2151 * @param string $group Form group name
2152 * @param array|string $arg1 Array for multiple elements or error message string for one element
2153 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2154 * @param string $format (optional)Required for extra rule data
2155 * @param int $howmany (optional)How many valid elements should be in the group
2156 * @param string $validation (optional)Where to perform validation: "server", "client"
2157 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2159 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2161 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2162 if (is_array($arg1)) {
2163 foreach ($arg1 as $rules) {
2164 foreach ($rules as $rule) {
2165 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2166 if ($validation == 'client') {
2167 $this->clientvalidation = true;
2171 } elseif (is_string($arg1)) {
2172 if ($validation == 'client') {
2173 $this->clientvalidation = true;
2179 * Returns the client side validation script
2181 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2182 * and slightly modified to run rules per-element
2183 * Needed to override this because of an error with client side validation of grouped elements.
2185 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2187 function getValidationScript()
2189 global $PAGE;
2191 if (empty($this->_rules) || $this->clientvalidation === false) {
2192 return '';
2195 include_once('HTML/QuickForm/RuleRegistry.php');
2196 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2197 $test = array();
2198 $js_escape = array(
2199 "\r" => '\r',
2200 "\n" => '\n',
2201 "\t" => '\t',
2202 "'" => "\\'",
2203 '"' => '\"',
2204 '\\' => '\\\\'
2207 foreach ($this->_rules as $elementName => $rules) {
2208 foreach ($rules as $rule) {
2209 if ('client' == $rule['validation']) {
2210 unset($element); //TODO: find out how to properly initialize it
2212 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2213 $rule['message'] = strtr($rule['message'], $js_escape);
2215 if (isset($rule['group'])) {
2216 $group =& $this->getElement($rule['group']);
2217 // No JavaScript validation for frozen elements
2218 if ($group->isFrozen()) {
2219 continue 2;
2221 $elements =& $group->getElements();
2222 foreach (array_keys($elements) as $key) {
2223 if ($elementName == $group->getElementName($key)) {
2224 $element =& $elements[$key];
2225 break;
2228 } elseif ($dependent) {
2229 $element = array();
2230 $element[] =& $this->getElement($elementName);
2231 foreach ($rule['dependent'] as $elName) {
2232 $element[] =& $this->getElement($elName);
2234 } else {
2235 $element =& $this->getElement($elementName);
2237 // No JavaScript validation for frozen elements
2238 if (is_object($element) && $element->isFrozen()) {
2239 continue 2;
2240 } elseif (is_array($element)) {
2241 foreach (array_keys($element) as $key) {
2242 if ($element[$key]->isFrozen()) {
2243 continue 3;
2247 //for editor element, [text] is appended to the name.
2248 $fullelementname = $elementName;
2249 if (is_object($element) && $element->getType() == 'editor') {
2250 if ($element->getType() == 'editor') {
2251 $fullelementname .= '[text]';
2252 // Add format to rule as moodleform check which format is supported by browser
2253 // it is not set anywhere... So small hack to make sure we pass it down to quickform.
2254 if (is_null($rule['format'])) {
2255 $rule['format'] = $element->getFormat();
2259 // Fix for bug displaying errors for elements in a group
2260 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2261 $test[$fullelementname][1]=$element;
2262 //end of fix
2267 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2268 // the form, and then that form field gets corrupted by the code that follows.
2269 unset($element);
2271 $js = '
2273 require(["core/event", "jquery"], function(Event, $) {
2275 function qf_errorHandler(element, _qfMsg, escapedName) {
2276 var event = $.Event(Event.Events.FORM_FIELD_VALIDATION);
2277 $(element).trigger(event, _qfMsg);
2278 if (event.isDefaultPrevented()) {
2279 return _qfMsg == \'\';
2280 } else {
2281 // Legacy mforms.
2282 var div = element.parentNode;
2284 if ((div == undefined) || (element.name == undefined)) {
2285 // No checking can be done for undefined elements so let server handle it.
2286 return true;
2289 if (_qfMsg != \'\') {
2290 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2291 if (!errorSpan) {
2292 errorSpan = document.createElement("span");
2293 errorSpan.id = \'id_error_\' + escapedName;
2294 errorSpan.className = "error";
2295 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2296 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2297 document.getElementById(errorSpan.id).focus();
2300 while (errorSpan.firstChild) {
2301 errorSpan.removeChild(errorSpan.firstChild);
2304 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2306 if (div.className.substr(div.className.length - 6, 6) != " error"
2307 && div.className != "error") {
2308 div.className += " error";
2309 linebreak = document.createElement("br");
2310 linebreak.className = "error";
2311 linebreak.id = \'id_error_break_\' + escapedName;
2312 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2315 return false;
2316 } else {
2317 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2318 if (errorSpan) {
2319 errorSpan.parentNode.removeChild(errorSpan);
2321 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2322 if (linebreak) {
2323 linebreak.parentNode.removeChild(linebreak);
2326 if (div.className.substr(div.className.length - 6, 6) == " error") {
2327 div.className = div.className.substr(0, div.className.length - 6);
2328 } else if (div.className == "error") {
2329 div.className = "";
2332 return true;
2333 } // End if.
2334 } // End if.
2335 } // End function.
2337 $validateJS = '';
2338 foreach ($test as $elementName => $jsandelement) {
2339 // Fix for bug displaying errors for elements in a group
2340 //unset($element);
2341 list($jsArr,$element)=$jsandelement;
2342 //end of fix
2343 $escapedElementName = preg_replace_callback(
2344 '/[_\[\]-]/',
2345 function($matches) {
2346 return sprintf("_%2x", ord($matches[0]));
2348 $elementName);
2349 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
2351 if (!is_array($element)) {
2352 $element = [$element];
2354 foreach ($element as $elem) {
2355 if (key_exists('id', $elem->_attributes)) {
2356 $js .= '
2357 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2358 if (undefined == element) {
2359 //required element was not found, then let form be submitted without client side validation
2360 return true;
2362 var value = \'\';
2363 var errFlag = new Array();
2364 var _qfGroups = {};
2365 var _qfMsg = \'\';
2366 var frm = element.parentNode;
2367 if ((undefined != element.name) && (frm != undefined)) {
2368 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2369 frm = frm.parentNode;
2371 ' . join("\n", $jsArr) . '
2372 return qf_errorHandler(element, _qfMsg, escapedName);
2373 } else {
2374 //element name should be defined else error msg will not be displayed.
2375 return true;
2379 document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'blur\', function(ev) {
2380 ' . $valFunc . '
2382 document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'change\', function(ev) {
2383 ' . $valFunc . '
2388 $validateJS .= '
2389 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2390 if (!ret && !first_focus) {
2391 first_focus = true;
2392 Y.use(\'moodle-core-event\', function() {
2393 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes['id'] . '\',
2394 elementid: \'id_error_' . $escapedElementName . '\'});
2395 document.getElementById(\'id_error_' . $escapedElementName . '\').focus();
2400 // Fix for bug displaying errors for elements in a group
2401 //unset($element);
2402 //$element =& $this->getElement($elementName);
2403 //end of fix
2404 //$onBlur = $element->getAttribute('onBlur');
2405 //$onChange = $element->getAttribute('onChange');
2406 //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2407 //'onChange' => $onChange . $valFunc));
2409 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2410 $js .= '
2412 function validate_' . $this->_formName . '() {
2413 if (skipClientValidation) {
2414 return true;
2416 var ret = true;
2418 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2419 var first_focus = false;
2420 ' . $validateJS . ';
2421 return ret;
2425 document.getElementById(\'' . $this->_attributes['id'] . '\').addEventListener(\'submit\', function(ev) {
2426 try {
2427 var myValidator = validate_' . $this->_formName . ';
2428 } catch(e) {
2429 return true;
2431 if (typeof window.tinyMCE !== \'undefined\') {
2432 window.tinyMCE.triggerSave();
2434 if (!myValidator()) {
2435 ev.preventDefault();
2442 $PAGE->requires->js_amd_inline($js);
2444 // Global variable used to skip the client validation.
2445 return html_writer::tag('script', 'var skipClientValidation = false;');
2446 } // end func getValidationScript
2449 * Sets default error message
2451 function _setDefaultRuleMessages(){
2452 foreach ($this->_rules as $field => $rulesarr){
2453 foreach ($rulesarr as $key => $rule){
2454 if ($rule['message']===null){
2455 $a=new stdClass();
2456 $a->format=$rule['format'];
2457 $str=get_string('err_'.$rule['type'], 'form', $a);
2458 if (strpos($str, '[[')!==0){
2459 $this->_rules[$field][$key]['message']=$str;
2467 * Get list of attributes which have dependencies
2469 * @return array
2471 function getLockOptionObject(){
2472 $result = array();
2473 foreach ($this->_dependencies as $dependentOn => $conditions){
2474 $result[$dependentOn] = array();
2475 foreach ($conditions as $condition=>$values) {
2476 $result[$dependentOn][$condition] = array();
2477 foreach ($values as $value=>$dependents) {
2478 $result[$dependentOn][$condition][$value][self::DEP_DISABLE] = array();
2479 foreach ($dependents as $dependent) {
2480 $elements = $this->_getElNamesRecursive($dependent);
2481 if (empty($elements)) {
2482 // probably element inside of some group
2483 $elements = array($dependent);
2485 foreach($elements as $element) {
2486 if ($element == $dependentOn) {
2487 continue;
2489 $result[$dependentOn][$condition][$value][self::DEP_DISABLE][] = $element;
2495 foreach ($this->_hideifs as $dependenton => $conditions) {
2496 if (!isset($result[$dependenton])) {
2497 $result[$dependenton] = array();
2499 foreach ($conditions as $condition => $values) {
2500 if (!isset($result[$dependenton][$condition])) {
2501 $result[$dependenton][$condition] = array();
2503 foreach ($values as $value => $dependents) {
2504 $result[$dependenton][$condition][$value][self::DEP_HIDE] = array();
2505 foreach ($dependents as $dependent) {
2506 $elements = $this->_getElNamesRecursive($dependent);
2507 if (!in_array($dependent, $elements)) {
2508 // Always want to hide the main element, even if it contains sub-elements as well.
2509 $elements[] = $dependent;
2511 foreach ($elements as $element) {
2512 if ($element == $dependenton) {
2513 continue;
2515 $result[$dependenton][$condition][$value][self::DEP_HIDE][] = $element;
2521 return array($this->getAttribute('id'), $result);
2525 * Get names of element or elements in a group.
2527 * @param HTML_QuickForm_group|element $element element group or element object
2528 * @return array
2530 function _getElNamesRecursive($element) {
2531 if (is_string($element)) {
2532 if (!$this->elementExists($element)) {
2533 return array();
2535 $element = $this->getElement($element);
2538 if (is_a($element, 'HTML_QuickForm_group')) {
2539 $elsInGroup = $element->getElements();
2540 $elNames = array();
2541 foreach ($elsInGroup as $elInGroup){
2542 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2543 // Groups nested in groups: append the group name to the element and then change it back.
2544 // We will be appending group name again in MoodleQuickForm_group::export_for_template().
2545 $oldname = $elInGroup->getName();
2546 if ($element->_appendName) {
2547 $elInGroup->setName($element->getName() . '[' . $oldname . ']');
2549 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2550 $elInGroup->setName($oldname);
2551 } else {
2552 $elNames[] = $element->getElementName($elInGroup->getName());
2556 } else if (is_a($element, 'HTML_QuickForm_header')) {
2557 return array();
2559 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2560 return array();
2562 } else if (method_exists($element, 'getPrivateName') &&
2563 !($element instanceof HTML_QuickForm_advcheckbox)) {
2564 // The advcheckbox element implements a method called getPrivateName,
2565 // but in a way that is not compatible with the generic API, so we
2566 // have to explicitly exclude it.
2567 return array($element->getPrivateName());
2569 } else {
2570 $elNames = array($element->getName());
2573 return $elNames;
2577 * Adds a dependency for $elementName which will be disabled if $condition is met.
2578 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2579 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2580 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2581 * of the $dependentOn element is $condition (such as equal) to $value.
2583 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2584 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2585 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2587 * @param string $elementName the name of the element which will be disabled
2588 * @param string $dependentOn the name of the element whose state will be checked for condition
2589 * @param string $condition the condition to check
2590 * @param mixed $value used in conjunction with condition.
2592 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2593 // Multiple selects allow for a multiple selection, we transform the array to string here as
2594 // an array cannot be used as a key in an associative array.
2595 if (is_array($value)) {
2596 $value = implode('|', $value);
2598 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2599 $this->_dependencies[$dependentOn] = array();
2601 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2602 $this->_dependencies[$dependentOn][$condition] = array();
2604 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2605 $this->_dependencies[$dependentOn][$condition][$value] = array();
2607 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2611 * Adds a dependency for $elementName which will be hidden if $condition is met.
2612 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2613 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2614 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2615 * of the $dependentOn element is $condition (such as equal) to $value.
2617 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2618 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2619 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2621 * @param string $elementname the name of the element which will be hidden
2622 * @param string $dependenton the name of the element whose state will be checked for condition
2623 * @param string $condition the condition to check
2624 * @param mixed $value used in conjunction with condition.
2626 public function hideIf($elementname, $dependenton, $condition = 'notchecked', $value = '1') {
2627 // Multiple selects allow for a multiple selection, we transform the array to string here as
2628 // an array cannot be used as a key in an associative array.
2629 if (is_array($value)) {
2630 $value = implode('|', $value);
2632 if (!array_key_exists($dependenton, $this->_hideifs)) {
2633 $this->_hideifs[$dependenton] = array();
2635 if (!array_key_exists($condition, $this->_hideifs[$dependenton])) {
2636 $this->_hideifs[$dependenton][$condition] = array();
2638 if (!array_key_exists($value, $this->_hideifs[$dependenton][$condition])) {
2639 $this->_hideifs[$dependenton][$condition][$value] = array();
2641 $this->_hideifs[$dependenton][$condition][$value][] = $elementname;
2645 * Registers button as no submit button
2647 * @param string $buttonname name of the button
2649 function registerNoSubmitButton($buttonname){
2650 $this->_noSubmitButtons[]=$buttonname;
2654 * Checks if button is a no submit button, i.e it doesn't submit form
2656 * @param string $buttonname name of the button to check
2657 * @return bool
2659 function isNoSubmitButton($buttonname){
2660 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2664 * Registers a button as cancel button
2666 * @param string $addfieldsname name of the button
2668 function _registerCancelButton($addfieldsname){
2669 $this->_cancelButtons[]=$addfieldsname;
2673 * Displays elements without HTML input tags.
2674 * This method is different to freeze() in that it makes sure no hidden
2675 * elements are included in the form.
2676 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2678 * This function also removes all previously defined rules.
2680 * @param string|array $elementList array or string of element(s) to be frozen
2681 * @return object|bool if element list is not empty then return error object, else true
2683 function hardFreeze($elementList=null)
2685 if (!isset($elementList)) {
2686 $this->_freezeAll = true;
2687 $elementList = array();
2688 } else {
2689 if (!is_array($elementList)) {
2690 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2692 $elementList = array_flip($elementList);
2695 foreach (array_keys($this->_elements) as $key) {
2696 $name = $this->_elements[$key]->getName();
2697 if ($this->_freezeAll || isset($elementList[$name])) {
2698 $this->_elements[$key]->freeze();
2699 $this->_elements[$key]->setPersistantFreeze(false);
2700 unset($elementList[$name]);
2702 // remove all rules
2703 $this->_rules[$name] = array();
2704 // if field is required, remove the rule
2705 $unset = array_search($name, $this->_required);
2706 if ($unset !== false) {
2707 unset($this->_required[$unset]);
2712 if (!empty($elementList)) {
2713 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);
2715 return true;
2719 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2721 * This function also removes all previously defined rules of elements it freezes.
2723 * @throws HTML_QuickForm_Error
2724 * @param array $elementList array or string of element(s) not to be frozen
2725 * @return bool returns true
2727 function hardFreezeAllVisibleExcept($elementList)
2729 $elementList = array_flip($elementList);
2730 foreach (array_keys($this->_elements) as $key) {
2731 $name = $this->_elements[$key]->getName();
2732 $type = $this->_elements[$key]->getType();
2734 if ($type == 'hidden'){
2735 // leave hidden types as they are
2736 } elseif (!isset($elementList[$name])) {
2737 $this->_elements[$key]->freeze();
2738 $this->_elements[$key]->setPersistantFreeze(false);
2740 // remove all rules
2741 $this->_rules[$name] = array();
2742 // if field is required, remove the rule
2743 $unset = array_search($name, $this->_required);
2744 if ($unset !== false) {
2745 unset($this->_required[$unset]);
2749 return true;
2753 * Tells whether the form was already submitted
2755 * This is useful since the _submitFiles and _submitValues arrays
2756 * may be completely empty after the trackSubmit value is removed.
2758 * @return bool
2760 function isSubmitted()
2762 return parent::isSubmitted() && (!$this->isFrozen());
2767 * MoodleQuickForm renderer
2769 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2770 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2772 * Stylesheet is part of standard theme and should be automatically included.
2774 * @package core_form
2775 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2776 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2778 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2780 /** @var array Element template array */
2781 var $_elementTemplates;
2784 * Template used when opening a hidden fieldset
2785 * (i.e. a fieldset that is opened when there is no header element)
2786 * @var string
2788 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2790 /** @var string Header Template string */
2791 var $_headerTemplate =
2792 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2794 /** @var string Template used when opening a fieldset */
2795 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2797 /** @var string Template used when closing a fieldset */
2798 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2800 /** @var string Required Note template string */
2801 var $_requiredNoteTemplate =
2802 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2805 * Collapsible buttons string template.
2807 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2808 * until the Javascript has been fully loaded.
2810 * @var string
2812 var $_collapseButtonsTemplate =
2813 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2816 * Array whose keys are element names. If the key exists this is a advanced element
2818 * @var array
2820 var $_advancedElements = array();
2823 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2825 * @var array
2827 var $_collapsibleElements = array();
2830 * @var string Contains the collapsible buttons to add to the form.
2832 var $_collapseButtons = '';
2835 * Constructor
2837 public function __construct() {
2838 // switch next two lines for ol li containers for form items.
2839 // $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>');
2840 $this->_elementTemplates = array(
2841 '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>',
2843 '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>',
2845 '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>',
2847 '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>',
2849 'warning' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}">{element}</div>',
2851 'nodisplay' => '');
2853 parent::__construct();
2857 * Old syntax of class constructor. Deprecated in PHP7.
2859 * @deprecated since Moodle 3.1
2861 public function MoodleQuickForm_Renderer() {
2862 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2863 self::__construct();
2867 * Set element's as adavance element
2869 * @param array $elements form elements which needs to be grouped as advance elements.
2871 function setAdvancedElements($elements){
2872 $this->_advancedElements = $elements;
2876 * Setting collapsible elements
2878 * @param array $elements
2880 function setCollapsibleElements($elements) {
2881 $this->_collapsibleElements = $elements;
2885 * What to do when starting the form
2887 * @param MoodleQuickForm $form reference of the form
2889 function startForm(&$form){
2890 global $PAGE;
2891 $this->_reqHTML = $form->getReqHTML();
2892 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2893 $this->_advancedHTML = $form->getAdvancedHTML();
2894 $this->_collapseButtons = '';
2895 $formid = $form->getAttribute('id');
2896 parent::startForm($form);
2897 if ($form->isFrozen()){
2898 $this->_formTemplate = "\n<div id=\"$formid\" class=\"mform frozen\">\n{collapsebtns}\n{content}\n</div>";
2899 } else {
2900 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2901 $this->_hiddenHtml .= $form->_pageparams;
2904 if ($form->is_form_change_checker_enabled()) {
2905 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2906 'M.core_formchangechecker.init',
2907 array(array(
2908 'formid' => $formid
2911 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2913 if (!empty($this->_collapsibleElements)) {
2914 if (count($this->_collapsibleElements) > 1) {
2915 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2916 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2917 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2919 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2921 if (!empty($this->_advancedElements)){
2922 $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2923 $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2928 * Create advance group of elements
2930 * @param MoodleQuickForm_group $group Passed by reference
2931 * @param bool $required if input is required field
2932 * @param string $error error message to display
2934 function startGroup(&$group, $required, $error){
2935 global $OUTPUT;
2937 // Make sure the element has an id.
2938 $group->_generateId();
2940 // Prepend 'fgroup_' to the ID we generated.
2941 $groupid = 'fgroup_' . $group->getAttribute('id');
2943 // Update the ID.
2944 $group->updateAttributes(array('id' => $groupid));
2945 $advanced = isset($this->_advancedElements[$group->getName()]);
2947 $html = $OUTPUT->mform_element($group, $required, $advanced, $error, false);
2948 $fromtemplate = !empty($html);
2949 if (!$fromtemplate) {
2950 if (method_exists($group, 'getElementTemplateType')) {
2951 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2952 } else {
2953 $html = $this->_elementTemplates['default'];
2956 if (isset($this->_advancedElements[$group->getName()])) {
2957 $html = str_replace(' {advanced}', ' advanced', $html);
2958 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
2959 } else {
2960 $html = str_replace(' {advanced}', '', $html);
2961 $html = str_replace('{advancedimg}', '', $html);
2963 if (method_exists($group, 'getHelpButton')) {
2964 $html = str_replace('{help}', $group->getHelpButton(), $html);
2965 } else {
2966 $html = str_replace('{help}', '', $html);
2968 $html = str_replace('{id}', $group->getAttribute('id'), $html);
2969 $html = str_replace('{name}', $group->getName(), $html);
2970 $html = str_replace('{groupname}', 'data-groupname="'.$group->getName().'"', $html);
2971 $html = str_replace('{typeclass}', 'fgroup', $html);
2972 $html = str_replace('{type}', 'group', $html);
2973 $html = str_replace('{class}', $group->getAttribute('class'), $html);
2974 $emptylabel = '';
2975 if ($group->getLabel() == '') {
2976 $emptylabel = 'femptylabel';
2978 $html = str_replace('{emptylabel}', $emptylabel, $html);
2980 $this->_templates[$group->getName()] = $html;
2981 // Fix for bug in tableless quickforms that didn't allow you to stop a
2982 // fieldset before a group of elements.
2983 // if the element name indicates the end of a fieldset, close the fieldset
2984 if (in_array($group->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
2985 $this->_html .= $this->_closeFieldsetTemplate;
2986 $this->_fieldsetsOpen--;
2988 if (!$fromtemplate) {
2989 parent::startGroup($group, $required, $error);
2990 } else {
2991 $this->_html .= $html;
2996 * Renders element
2998 * @param HTML_QuickForm_element $element element
2999 * @param bool $required if input is required field
3000 * @param string $error error message to display
3002 function renderElement(&$element, $required, $error){
3003 global $OUTPUT;
3005 // Make sure the element has an id.
3006 $element->_generateId();
3007 $advanced = isset($this->_advancedElements[$element->getName()]);
3009 $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
3010 $fromtemplate = !empty($html);
3011 if (!$fromtemplate) {
3012 // Adding stuff to place holders in template
3013 // check if this is a group element first.
3014 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3015 // So it gets substitutions for *each* element.
3016 $html = $this->_groupElementTemplate;
3017 } else if (method_exists($element, 'getElementTemplateType')) {
3018 $html = $this->_elementTemplates[$element->getElementTemplateType()];
3019 } else {
3020 $html = $this->_elementTemplates['default'];
3022 if (isset($this->_advancedElements[$element->getName()])) {
3023 $html = str_replace(' {advanced}', ' advanced', $html);
3024 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
3025 } else {
3026 $html = str_replace(' {advanced}', '', $html);
3027 $html = str_replace(' {aria-live}', '', $html);
3029 if (isset($this->_advancedElements[$element->getName()]) || $element->getName() == 'mform_showadvanced') {
3030 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
3031 } else {
3032 $html = str_replace('{advancedimg}', '', $html);
3034 $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
3035 $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
3036 $html = str_replace('{type}', $element->getType(), $html);
3037 $html = str_replace('{name}', $element->getName(), $html);
3038 $html = str_replace('{groupname}', '', $html);
3039 $html = str_replace('{class}', $element->getAttribute('class'), $html);
3040 $emptylabel = '';
3041 if ($element->getLabel() == '') {
3042 $emptylabel = 'femptylabel';
3044 $html = str_replace('{emptylabel}', $emptylabel, $html);
3045 if (method_exists($element, 'getHelpButton')) {
3046 $html = str_replace('{help}', $element->getHelpButton(), $html);
3047 } else {
3048 $html = str_replace('{help}', '', $html);
3050 } else {
3051 if ($this->_inGroup) {
3052 $this->_groupElementTemplate = $html;
3055 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3056 $this->_groupElementTemplate = $html;
3057 } else if (!isset($this->_templates[$element->getName()])) {
3058 $this->_templates[$element->getName()] = $html;
3061 if (!$fromtemplate) {
3062 parent::renderElement($element, $required, $error);
3063 } else {
3064 if (in_array($element->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
3065 $this->_html .= $this->_closeFieldsetTemplate;
3066 $this->_fieldsetsOpen--;
3068 $this->_html .= $html;
3073 * Called when visiting a form, after processing all form elements
3074 * Adds required note, form attributes, validation javascript and form content.
3076 * @global moodle_page $PAGE
3077 * @param moodleform $form Passed by reference
3079 function finishForm(&$form){
3080 global $PAGE;
3081 if ($form->isFrozen()){
3082 $this->_hiddenHtml = '';
3084 parent::finishForm($form);
3085 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
3086 if (!$form->isFrozen()) {
3087 $args = $form->getLockOptionObject();
3088 if (count($args[1]) > 0) {
3089 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
3094 * Called when visiting a header element
3096 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
3097 * @global moodle_page $PAGE
3099 function renderHeader(&$header) {
3100 global $PAGE;
3102 $header->_generateId();
3103 $name = $header->getName();
3105 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
3106 if (is_null($header->_text)) {
3107 $header_html = '';
3108 } elseif (!empty($name) && isset($this->_templates[$name])) {
3109 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
3110 } else {
3111 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
3114 if ($this->_fieldsetsOpen > 0) {
3115 $this->_html .= $this->_closeFieldsetTemplate;
3116 $this->_fieldsetsOpen--;
3119 // Define collapsible classes for fieldsets.
3120 $arialive = '';
3121 $fieldsetclasses = array('clearfix');
3122 if (isset($this->_collapsibleElements[$header->getName()])) {
3123 $fieldsetclasses[] = 'collapsible';
3124 if ($this->_collapsibleElements[$header->getName()]) {
3125 $fieldsetclasses[] = 'collapsed';
3129 if (isset($this->_advancedElements[$name])){
3130 $fieldsetclasses[] = 'containsadvancedelements';
3133 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
3134 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
3136 $this->_html .= $openFieldsetTemplate . $header_html;
3137 $this->_fieldsetsOpen++;
3141 * Return Array of element names that indicate the end of a fieldset
3143 * @return array
3145 function getStopFieldsetElements(){
3146 return $this->_stopFieldsetElements;
3151 * Required elements validation
3153 * This class overrides QuickForm validation since it allowed space or empty tag as a value
3155 * @package core_form
3156 * @category form
3157 * @copyright 2006 Jamie Pratt <me@jamiep.org>
3158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3160 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
3162 * Checks if an element is not empty.
3163 * This is a server-side validation, it works for both text fields and editor fields
3165 * @param string $value Value to check
3166 * @param int|string|array $options Not used yet
3167 * @return bool true if value is not empty
3169 function validate($value, $options = null) {
3170 global $CFG;
3171 if (is_array($value) && array_key_exists('text', $value)) {
3172 $value = $value['text'];
3174 if (is_array($value)) {
3175 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
3176 $value = implode('', $value);
3178 $stripvalues = array(
3179 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
3180 '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
3182 if (!empty($CFG->strictformsrequired)) {
3183 $value = preg_replace($stripvalues, '', (string)$value);
3185 if ((string)$value == '') {
3186 return false;
3188 return true;
3192 * This function returns Javascript code used to build client-side validation.
3193 * It checks if an element is not empty.
3195 * @param int $format format of data which needs to be validated.
3196 * @return array
3198 function getValidationScript($format = null) {
3199 global $CFG;
3200 if (!empty($CFG->strictformsrequired)) {
3201 if (!empty($format) && $format == FORMAT_HTML) {
3202 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
3203 } else {
3204 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
3206 } else {
3207 return array('', "{jsVar} == ''");
3213 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
3214 * @name $_HTML_QuickForm_default_renderer
3216 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
3218 /** Please keep this list in alphabetical order. */
3219 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
3220 MoodleQuickForm::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
3221 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
3222 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3223 MoodleQuickForm::registerElementType('course', "$CFG->libdir/form/course.php", 'MoodleQuickForm_course');
3224 MoodleQuickForm::registerElementType('cohort', "$CFG->libdir/form/cohort.php", 'MoodleQuickForm_cohort');
3225 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
3226 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
3227 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
3228 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
3229 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
3230 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
3231 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
3232 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
3233 MoodleQuickForm::registerElementType('filetypes', "$CFG->libdir/form/filetypes.php", 'MoodleQuickForm_filetypes');
3234 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
3235 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
3236 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
3237 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
3238 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
3239 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
3240 MoodleQuickForm::registerElementType('defaultcustom', "$CFG->libdir/form/defaultcustom.php", 'MoodleQuickForm_defaultcustom');
3241 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
3242 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
3243 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
3244 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
3245 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
3246 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
3247 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
3248 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
3249 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
3250 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
3251 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
3252 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
3253 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
3254 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
3255 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
3256 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
3257 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
3258 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
3260 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");