MDL-52619 lib: Update of ADODB to 5.20.3
[moodle.git] / lib / formslib.php
blob6307a4cb361bc7b7d6bdd8747a03143f9953f71c
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 $config = array(array(
84 'firstdayofweek' => $calendar->get_starting_weekday(),
85 'mon' => date_format_string(strtotime("Monday"), '%a', 99),
86 'tue' => date_format_string(strtotime("Tuesday"), '%a', 99),
87 'wed' => date_format_string(strtotime("Wednesday"), '%a', 99),
88 'thu' => date_format_string(strtotime("Thursday"), '%a', 99),
89 'fri' => date_format_string(strtotime("Friday"), '%a', 99),
90 'sat' => date_format_string(strtotime("Saturday"), '%a', 99),
91 'sun' => date_format_string(strtotime("Sunday"), '%a', 99),
92 'january' => date_format_string(strtotime("January 1"), '%B', 99),
93 'february' => date_format_string(strtotime("February 1"), '%B', 99),
94 'march' => date_format_string(strtotime("March 1"), '%B', 99),
95 'april' => date_format_string(strtotime("April 1"), '%B', 99),
96 'may' => date_format_string(strtotime("May 1"), '%B', 99),
97 'june' => date_format_string(strtotime("June 1"), '%B', 99),
98 'july' => date_format_string(strtotime("July 1"), '%B', 99),
99 'august' => date_format_string(strtotime("August 1"), '%B', 99),
100 'september' => date_format_string(strtotime("September 1"), '%B', 99),
101 'october' => date_format_string(strtotime("October 1"), '%B', 99),
102 'november' => date_format_string(strtotime("November 1"), '%B', 99),
103 'december' => date_format_string(strtotime("December 1"), '%B', 99)
105 $PAGE->requires->yui_module($module, $function, $config);
106 $done = true;
111 * Wrapper that separates quickforms syntax from moodle code
113 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
114 * use this class you should write a class definition which extends this class or a more specific
115 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
117 * You will write your own definition() method which performs the form set up.
119 * @package core_form
120 * @copyright 2006 Jamie Pratt <me@jamiep.org>
121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
122 * @todo MDL-19380 rethink the file scanning
124 abstract class moodleform {
125 /** @var string name of the form */
126 protected $_formname; // form name
128 /** @var MoodleQuickForm quickform object definition */
129 protected $_form;
131 /** @var array globals workaround */
132 protected $_customdata;
134 /** @var object definition_after_data executed flag */
135 protected $_definition_finalized = false;
138 * The constructor function calls the abstract function definition() and it will then
139 * process and clean and attempt to validate incoming data.
141 * It will call your custom validate method to validate data and will also check any rules
142 * you have specified in definition using addRule
144 * The name of the form (id attribute of the form) is automatically generated depending on
145 * the name you gave the class extending moodleform. You should call your class something
146 * like
148 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
149 * current url. If a moodle_url object then outputs params as hidden variables.
150 * @param mixed $customdata if your form defintion method needs access to data such as $course
151 * $cm, etc. to construct the form definition then pass it in this array. You can
152 * use globals for somethings.
153 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
154 * be merged and used as incoming data to the form.
155 * @param string $target target frame for form submission. You will rarely use this. Don't use
156 * it if you don't need to as the target attribute is deprecated in xhtml strict.
157 * @param mixed $attributes you can pass a string of html attributes here or an array.
158 * @param bool $editable
160 public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
161 global $CFG, $FULLME;
162 // no standard mform in moodle should allow autocomplete with the exception of user signup
163 if (empty($attributes)) {
164 $attributes = array('autocomplete'=>'off');
165 } else if (is_array($attributes)) {
166 $attributes['autocomplete'] = 'off';
167 } else {
168 if (strpos($attributes, 'autocomplete') === false) {
169 $attributes .= ' autocomplete="off" ';
173 if (empty($action)){
174 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
175 $action = strip_querystring($FULLME);
176 if (!empty($CFG->sslproxy)) {
177 // return only https links when using SSL proxy
178 $action = preg_replace('/^http:/', 'https:', $action, 1);
180 //TODO: use following instead of FULLME - see MDL-33015
181 //$action = strip_querystring(qualified_me());
183 // Assign custom data first, so that get_form_identifier can use it.
184 $this->_customdata = $customdata;
185 $this->_formname = $this->get_form_identifier();
187 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
188 if (!$editable){
189 $this->_form->hardFreeze();
192 // HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
193 $element = $this->_form->addElement('hidden');
194 $element->setType('password');
196 $this->definition();
198 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
199 $this->_form->setType('sesskey', PARAM_RAW);
200 $this->_form->setDefault('sesskey', sesskey());
201 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
202 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
203 $this->_form->setDefault('_qf__'.$this->_formname, 1);
204 $this->_form->_setDefaultRuleMessages();
206 // we have to know all input types before processing submission ;-)
207 $this->_process_submission($method);
211 * Old syntax of class constructor. Deprecated in PHP7.
213 * @deprecated since Moodle 3.1
215 public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
216 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
217 self::__construct($action, $customdata, $method, $target, $attributes, $editable);
221 * It should returns unique identifier for the form.
222 * Currently it will return class name, but in case two same forms have to be
223 * rendered on same page then override function to get unique form identifier.
224 * e.g This is used on multiple self enrollments page.
226 * @return string form identifier.
228 protected function get_form_identifier() {
229 $class = get_class($this);
231 return preg_replace('/[^a-z0-9_]/i', '_', $class);
235 * To autofocus on first form element or first element with error.
237 * @param string $name if this is set then the focus is forced to a field with this name
238 * @return string javascript to select form element with first error or
239 * first element if no errors. Use this as a parameter
240 * when calling print_header
242 function focus($name=NULL) {
243 $form =& $this->_form;
244 $elkeys = array_keys($form->_elementIndex);
245 $error = false;
246 if (isset($form->_errors) && 0 != count($form->_errors)){
247 $errorkeys = array_keys($form->_errors);
248 $elkeys = array_intersect($elkeys, $errorkeys);
249 $error = true;
252 if ($error or empty($name)) {
253 $names = array();
254 while (empty($names) and !empty($elkeys)) {
255 $el = array_shift($elkeys);
256 $names = $form->_getElNamesRecursive($el);
258 if (!empty($names)) {
259 $name = array_shift($names);
263 $focus = '';
264 if (!empty($name)) {
265 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
268 return $focus;
272 * Internal method. Alters submitted data to be suitable for quickforms processing.
273 * Must be called when the form is fully set up.
275 * @param string $method name of the method which alters submitted data
277 function _process_submission($method) {
278 $submission = array();
279 if ($method == 'post') {
280 if (!empty($_POST)) {
281 $submission = $_POST;
283 } else {
284 $submission = $_GET;
285 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
288 // following trick is needed to enable proper sesskey checks when using GET forms
289 // the _qf__.$this->_formname serves as a marker that form was actually submitted
290 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
291 if (!confirm_sesskey()) {
292 print_error('invalidsesskey');
294 $files = $_FILES;
295 } else {
296 $submission = array();
297 $files = array();
299 $this->detectMissingSetType();
301 $this->_form->updateSubmission($submission, $files);
305 * Internal method - should not be used anywhere.
306 * @deprecated since 2.6
307 * @return array $_POST.
309 protected function _get_post_params() {
310 return $_POST;
314 * Internal method. Validates all old-style deprecated uploaded files.
315 * The new way is to upload files via repository api.
317 * @param array $files list of files to be validated
318 * @return bool|array Success or an array of errors
320 function _validate_files(&$files) {
321 global $CFG, $COURSE;
323 $files = array();
325 if (empty($_FILES)) {
326 // we do not need to do any checks because no files were submitted
327 // note: server side rules do not work for files - use custom verification in validate() instead
328 return true;
331 $errors = array();
332 $filenames = array();
334 // now check that we really want each file
335 foreach ($_FILES as $elname=>$file) {
336 $required = $this->_form->isElementRequired($elname);
338 if ($file['error'] == 4 and $file['size'] == 0) {
339 if ($required) {
340 $errors[$elname] = get_string('required');
342 unset($_FILES[$elname]);
343 continue;
346 if (!empty($file['error'])) {
347 $errors[$elname] = file_get_upload_error($file['error']);
348 unset($_FILES[$elname]);
349 continue;
352 if (!is_uploaded_file($file['tmp_name'])) {
353 // TODO: improve error message
354 $errors[$elname] = get_string('error');
355 unset($_FILES[$elname]);
356 continue;
359 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
360 // hmm, this file was not requested
361 unset($_FILES[$elname]);
362 continue;
365 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
367 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
368 if ($filename === '') {
369 // TODO: improve error message - wrong chars
370 $errors[$elname] = get_string('error');
371 unset($_FILES[$elname]);
372 continue;
374 if (in_array($filename, $filenames)) {
375 // TODO: improve error message - duplicate name
376 $errors[$elname] = get_string('error');
377 unset($_FILES[$elname]);
378 continue;
380 $filenames[] = $filename;
381 $_FILES[$elname]['name'] = $filename;
383 $files[$elname] = $_FILES[$elname]['tmp_name'];
386 // return errors if found
387 if (count($errors) == 0){
388 return true;
390 } else {
391 $files = array();
392 return $errors;
397 * Internal method. Validates filepicker and filemanager files if they are
398 * set as required fields. Also, sets the error message if encountered one.
400 * @return bool|array with errors
402 protected function validate_draft_files() {
403 global $USER;
404 $mform =& $this->_form;
406 $errors = array();
407 //Go through all the required elements and make sure you hit filepicker or
408 //filemanager element.
409 foreach ($mform->_rules as $elementname => $rules) {
410 $elementtype = $mform->getElementType($elementname);
411 //If element is of type filepicker then do validation
412 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
413 //Check if rule defined is required rule
414 foreach ($rules as $rule) {
415 if ($rule['type'] == 'required') {
416 $draftid = (int)$mform->getSubmitValue($elementname);
417 $fs = get_file_storage();
418 $context = context_user::instance($USER->id);
419 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
420 $errors[$elementname] = $rule['message'];
426 // Check all the filemanager elements to make sure they do not have too many
427 // files in them.
428 foreach ($mform->_elements as $element) {
429 if ($element->_type == 'filemanager') {
430 $maxfiles = $element->getMaxfiles();
431 if ($maxfiles > 0) {
432 $draftid = (int)$element->getValue();
433 $fs = get_file_storage();
434 $context = context_user::instance($USER->id);
435 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
436 if (count($files) > $maxfiles) {
437 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
442 if (empty($errors)) {
443 return true;
444 } else {
445 return $errors;
450 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
451 * form definition (new entry form); this function is used to load in data where values
452 * already exist and data is being edited (edit entry form).
454 * note: $slashed param removed
456 * @param stdClass|array $default_values object or array of default values
458 function set_data($default_values) {
459 if (is_object($default_values)) {
460 $default_values = (array)$default_values;
462 $this->_form->setDefaults($default_values);
466 * Check that form was submitted. Does not check validity of submitted data.
468 * @return bool true if form properly submitted
470 function is_submitted() {
471 return $this->_form->isSubmitted();
475 * Checks if button pressed is not for submitting the form
477 * @staticvar bool $nosubmit keeps track of no submit button
478 * @return bool
480 function no_submit_button_pressed(){
481 static $nosubmit = null; // one check is enough
482 if (!is_null($nosubmit)){
483 return $nosubmit;
485 $mform =& $this->_form;
486 $nosubmit = false;
487 if (!$this->is_submitted()){
488 return false;
490 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
491 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
492 $nosubmit = true;
493 break;
496 return $nosubmit;
501 * Check that form data is valid.
502 * You should almost always use this, rather than {@link validate_defined_fields}
504 * @return bool true if form data valid
506 function is_validated() {
507 //finalize the form definition before any processing
508 if (!$this->_definition_finalized) {
509 $this->_definition_finalized = true;
510 $this->definition_after_data();
513 return $this->validate_defined_fields();
517 * Validate the form.
519 * You almost always want to call {@link is_validated} instead of this
520 * because it calls {@link definition_after_data} first, before validating the form,
521 * which is what you want in 99% of cases.
523 * This is provided as a separate function for those special cases where
524 * you want the form validated before definition_after_data is called
525 * for example, to selectively add new elements depending on a no_submit_button press,
526 * but only when the form is valid when the no_submit_button is pressed,
528 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
529 * is NOT to validate the form when a no submit button has been pressed.
530 * pass true here to override this behaviour
532 * @return bool true if form data valid
534 function validate_defined_fields($validateonnosubmit=false) {
535 static $validated = null; // one validation is enough
536 $mform =& $this->_form;
537 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
538 return false;
539 } elseif ($validated === null) {
540 $internal_val = $mform->validate();
542 $files = array();
543 $file_val = $this->_validate_files($files);
544 //check draft files for validation and flag them if required files
545 //are not in draft area.
546 $draftfilevalue = $this->validate_draft_files();
548 if ($file_val !== true && $draftfilevalue !== true) {
549 $file_val = array_merge($file_val, $draftfilevalue);
550 } else if ($draftfilevalue !== true) {
551 $file_val = $draftfilevalue;
552 } //default is file_val, so no need to assign.
554 if ($file_val !== true) {
555 if (!empty($file_val)) {
556 foreach ($file_val as $element=>$msg) {
557 $mform->setElementError($element, $msg);
560 $file_val = false;
563 $data = $mform->exportValues();
564 $moodle_val = $this->validation($data, $files);
565 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
566 // non-empty array means errors
567 foreach ($moodle_val as $element=>$msg) {
568 $mform->setElementError($element, $msg);
570 $moodle_val = false;
572 } else {
573 // anything else means validation ok
574 $moodle_val = true;
577 $validated = ($internal_val and $moodle_val and $file_val);
579 return $validated;
583 * Return true if a cancel button has been pressed resulting in the form being submitted.
585 * @return bool true if a cancel button has been pressed
587 function is_cancelled(){
588 $mform =& $this->_form;
589 if ($mform->isSubmitted()){
590 foreach ($mform->_cancelButtons as $cancelbutton){
591 if (optional_param($cancelbutton, 0, PARAM_RAW)){
592 return true;
596 return false;
600 * Return submitted data if properly submitted or returns NULL if validation fails or
601 * if there is no submitted data.
603 * note: $slashed param removed
605 * @return object submitted data; NULL if not valid or not submitted or cancelled
607 function get_data() {
608 $mform =& $this->_form;
610 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
611 $data = $mform->exportValues();
612 unset($data['sesskey']); // we do not need to return sesskey
613 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
614 if (empty($data)) {
615 return NULL;
616 } else {
617 return (object)$data;
619 } else {
620 return NULL;
625 * Return submitted data without validation or NULL if there is no submitted data.
626 * note: $slashed param removed
628 * @return object submitted data; NULL if not submitted
630 function get_submitted_data() {
631 $mform =& $this->_form;
633 if ($this->is_submitted()) {
634 $data = $mform->exportValues();
635 unset($data['sesskey']); // we do not need to return sesskey
636 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
637 if (empty($data)) {
638 return NULL;
639 } else {
640 return (object)$data;
642 } else {
643 return NULL;
648 * Save verified uploaded files into directory. Upload process can be customised from definition()
650 * @deprecated since Moodle 2.0
651 * @todo MDL-31294 remove this api
652 * @see moodleform::save_stored_file()
653 * @see moodleform::save_file()
654 * @param string $destination path where file should be stored
655 * @return bool Always false
657 function save_files($destination) {
658 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
659 return false;
663 * Returns name of uploaded file.
665 * @param string $elname first element if null
666 * @return string|bool false in case of failure, string if ok
668 function get_new_filename($elname=null) {
669 global $USER;
671 if (!$this->is_submitted() or !$this->is_validated()) {
672 return false;
675 if (is_null($elname)) {
676 if (empty($_FILES)) {
677 return false;
679 reset($_FILES);
680 $elname = key($_FILES);
683 if (empty($elname)) {
684 return false;
687 $element = $this->_form->getElement($elname);
689 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
690 $values = $this->_form->exportValues($elname);
691 if (empty($values[$elname])) {
692 return false;
694 $draftid = $values[$elname];
695 $fs = get_file_storage();
696 $context = context_user::instance($USER->id);
697 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
698 return false;
700 $file = reset($files);
701 return $file->get_filename();
704 if (!isset($_FILES[$elname])) {
705 return false;
708 return $_FILES[$elname]['name'];
712 * Save file to standard filesystem
714 * @param string $elname name of element
715 * @param string $pathname full path name of file
716 * @param bool $override override file if exists
717 * @return bool success
719 function save_file($elname, $pathname, $override=false) {
720 global $USER;
722 if (!$this->is_submitted() or !$this->is_validated()) {
723 return false;
725 if (file_exists($pathname)) {
726 if ($override) {
727 if (!@unlink($pathname)) {
728 return false;
730 } else {
731 return false;
735 $element = $this->_form->getElement($elname);
737 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
738 $values = $this->_form->exportValues($elname);
739 if (empty($values[$elname])) {
740 return false;
742 $draftid = $values[$elname];
743 $fs = get_file_storage();
744 $context = context_user::instance($USER->id);
745 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
746 return false;
748 $file = reset($files);
750 return $file->copy_content_to($pathname);
752 } else if (isset($_FILES[$elname])) {
753 return copy($_FILES[$elname]['tmp_name'], $pathname);
756 return false;
760 * Returns a temporary file, do not forget to delete after not needed any more.
762 * @param string $elname name of the elmenet
763 * @return string|bool either string or false
765 function save_temp_file($elname) {
766 if (!$this->get_new_filename($elname)) {
767 return false;
769 if (!$dir = make_temp_directory('forms')) {
770 return false;
772 if (!$tempfile = tempnam($dir, 'tempup_')) {
773 return false;
775 if (!$this->save_file($elname, $tempfile, true)) {
776 // something went wrong
777 @unlink($tempfile);
778 return false;
781 return $tempfile;
785 * Get draft files of a form element
786 * This is a protected method which will be used only inside moodleforms
788 * @param string $elname name of element
789 * @return array|bool|null
791 protected function get_draft_files($elname) {
792 global $USER;
794 if (!$this->is_submitted()) {
795 return false;
798 $element = $this->_form->getElement($elname);
800 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
801 $values = $this->_form->exportValues($elname);
802 if (empty($values[$elname])) {
803 return false;
805 $draftid = $values[$elname];
806 $fs = get_file_storage();
807 $context = context_user::instance($USER->id);
808 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
809 return null;
811 return $files;
813 return null;
817 * Save file to local filesystem pool
819 * @param string $elname name of element
820 * @param int $newcontextid id of context
821 * @param string $newcomponent name of the component
822 * @param string $newfilearea name of file area
823 * @param int $newitemid item id
824 * @param string $newfilepath path of file where it get stored
825 * @param string $newfilename use specified filename, if not specified name of uploaded file used
826 * @param bool $overwrite overwrite file if exists
827 * @param int $newuserid new userid if required
828 * @return mixed stored_file object or false if error; may throw exception if duplicate found
830 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
831 $newfilename=null, $overwrite=false, $newuserid=null) {
832 global $USER;
834 if (!$this->is_submitted() or !$this->is_validated()) {
835 return false;
838 if (empty($newuserid)) {
839 $newuserid = $USER->id;
842 $element = $this->_form->getElement($elname);
843 $fs = get_file_storage();
845 if ($element instanceof MoodleQuickForm_filepicker) {
846 $values = $this->_form->exportValues($elname);
847 if (empty($values[$elname])) {
848 return false;
850 $draftid = $values[$elname];
851 $context = context_user::instance($USER->id);
852 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
853 return false;
855 $file = reset($files);
856 if (is_null($newfilename)) {
857 $newfilename = $file->get_filename();
860 if ($overwrite) {
861 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
862 if (!$oldfile->delete()) {
863 return false;
868 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
869 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
870 return $fs->create_file_from_storedfile($file_record, $file);
872 } else if (isset($_FILES[$elname])) {
873 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
875 if ($overwrite) {
876 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
877 if (!$oldfile->delete()) {
878 return false;
883 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
884 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
885 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
888 return false;
892 * Get content of uploaded file.
894 * @param string $elname name of file upload element
895 * @return string|bool false in case of failure, string if ok
897 function get_file_content($elname) {
898 global $USER;
900 if (!$this->is_submitted() or !$this->is_validated()) {
901 return false;
904 $element = $this->_form->getElement($elname);
906 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
907 $values = $this->_form->exportValues($elname);
908 if (empty($values[$elname])) {
909 return false;
911 $draftid = $values[$elname];
912 $fs = get_file_storage();
913 $context = context_user::instance($USER->id);
914 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
915 return false;
917 $file = reset($files);
919 return $file->get_content();
921 } else if (isset($_FILES[$elname])) {
922 return file_get_contents($_FILES[$elname]['tmp_name']);
925 return false;
929 * Print html form.
931 function display() {
932 //finalize the form definition if not yet done
933 if (!$this->_definition_finalized) {
934 $this->_definition_finalized = true;
935 $this->definition_after_data();
938 $this->_form->display();
942 * Renders the html form (same as display, but returns the result).
944 * Note that you can only output this rendered result once per page, as
945 * it contains IDs which must be unique.
947 * @return string HTML code for the form
949 public function render() {
950 ob_start();
951 $this->display();
952 $out = ob_get_contents();
953 ob_end_clean();
954 return $out;
958 * Form definition. Abstract method - always override!
960 protected abstract function definition();
963 * Dummy stub method - override if you need to setup the form depending on current
964 * values. This method is called after definition(), data submission and set_data().
965 * All form setup that is dependent on form values should go in here.
967 function definition_after_data(){
971 * Dummy stub method - override if you needed to perform some extra validation.
972 * If there are errors return array of errors ("fieldname"=>"error message"),
973 * otherwise true if ok.
975 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
977 * @param array $data array of ("fieldname"=>value) of submitted data
978 * @param array $files array of uploaded files "element_name"=>tmp_file_path
979 * @return array of "element_name"=>"error_description" if there are errors,
980 * or an empty array if everything is OK (true allowed for backwards compatibility too).
982 function validation($data, $files) {
983 return array();
987 * Helper used by {@link repeat_elements()}.
989 * @param int $i the index of this element.
990 * @param HTML_QuickForm_element $elementclone
991 * @param array $namecloned array of names
993 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
994 $name = $elementclone->getName();
995 $namecloned[] = $name;
997 if (!empty($name)) {
998 $elementclone->setName($name."[$i]");
1001 if (is_a($elementclone, 'HTML_QuickForm_header')) {
1002 $value = $elementclone->_text;
1003 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1005 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1006 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1008 } else {
1009 $value=$elementclone->getLabel();
1010 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1015 * Method to add a repeating group of elements to a form.
1017 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1018 * @param int $repeats no of times to repeat elements initially
1019 * @param array $options a nested array. The first array key is the element name.
1020 * the second array key is the type of option to set, and depend on that option,
1021 * the value takes different forms.
1022 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1023 * 'type' - PARAM_* type.
1024 * 'helpbutton' - array containing the helpbutton params.
1025 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1026 * 'rule' - array containing the addRule arguments after the element name.
1027 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1028 * 'advanced' - whether this element is hidden by 'Show more ...'.
1029 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1030 * @param string $addfieldsname name for button to add more fields
1031 * @param int $addfieldsno how many fields to add at a time
1032 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1033 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1034 * @return int no of repeats of element in this page
1036 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1037 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1038 if ($addstring===null){
1039 $addstring = get_string('addfields', 'form', $addfieldsno);
1040 } else {
1041 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1043 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1044 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1045 if (!empty($addfields)){
1046 $repeats += $addfieldsno;
1048 $mform =& $this->_form;
1049 $mform->registerNoSubmitButton($addfieldsname);
1050 $mform->addElement('hidden', $repeathiddenname, $repeats);
1051 $mform->setType($repeathiddenname, PARAM_INT);
1052 //value not to be overridden by submitted value
1053 $mform->setConstants(array($repeathiddenname=>$repeats));
1054 $namecloned = array();
1055 for ($i = 0; $i < $repeats; $i++) {
1056 foreach ($elementobjs as $elementobj){
1057 $elementclone = fullclone($elementobj);
1058 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1060 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1061 foreach ($elementclone->getElements() as $el) {
1062 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1064 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1067 $mform->addElement($elementclone);
1070 for ($i=0; $i<$repeats; $i++) {
1071 foreach ($options as $elementname => $elementoptions){
1072 $pos=strpos($elementname, '[');
1073 if ($pos!==FALSE){
1074 $realelementname = substr($elementname, 0, $pos)."[$i]";
1075 $realelementname .= substr($elementname, $pos);
1076 }else {
1077 $realelementname = $elementname."[$i]";
1079 foreach ($elementoptions as $option => $params){
1081 switch ($option){
1082 case 'default' :
1083 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1084 break;
1085 case 'helpbutton' :
1086 $params = array_merge(array($realelementname), $params);
1087 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1088 break;
1089 case 'disabledif' :
1090 foreach ($namecloned as $num => $name){
1091 if ($params[0] == $name){
1092 $params[0] = $params[0]."[$i]";
1093 break;
1096 $params = array_merge(array($realelementname), $params);
1097 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1098 break;
1099 case 'rule' :
1100 if (is_string($params)){
1101 $params = array(null, $params, null, 'client');
1103 $params = array_merge(array($realelementname), $params);
1104 call_user_func_array(array(&$mform, 'addRule'), $params);
1105 break;
1107 case 'type':
1108 $mform->setType($realelementname, $params);
1109 break;
1111 case 'expanded':
1112 $mform->setExpanded($realelementname, $params);
1113 break;
1115 case 'advanced' :
1116 $mform->setAdvanced($realelementname, $params);
1117 break;
1122 $mform->addElement('submit', $addfieldsname, $addstring);
1124 if (!$addbuttoninside) {
1125 $mform->closeHeaderBefore($addfieldsname);
1128 return $repeats;
1132 * Adds a link/button that controls the checked state of a group of checkboxes.
1134 * @param int $groupid The id of the group of advcheckboxes this element controls
1135 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1136 * @param array $attributes associative array of HTML attributes
1137 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1139 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1140 global $CFG, $PAGE;
1142 // Name of the controller button
1143 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1144 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1145 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1147 // Set the default text if none was specified
1148 if (empty($text)) {
1149 $text = get_string('selectallornone', 'form');
1152 $mform = $this->_form;
1153 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1154 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1156 $newselectvalue = $selectvalue;
1157 if (is_null($selectvalue)) {
1158 $newselectvalue = $originalValue;
1159 } else if (!is_null($contollerbutton)) {
1160 $newselectvalue = (int) !$selectvalue;
1162 // set checkbox state depending on orignal/submitted value by controoler button
1163 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1164 foreach ($mform->_elements as $element) {
1165 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1166 $element->getAttribute('class') == $checkboxgroupclass &&
1167 !$element->isFrozen()) {
1168 $mform->setConstants(array($element->getName() => $newselectvalue));
1173 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1174 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1175 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1177 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1178 array(
1179 array('groupid' => $groupid,
1180 'checkboxclass' => $checkboxgroupclass,
1181 'checkboxcontroller' => $checkboxcontrollerparam,
1182 'controllerbutton' => $checkboxcontrollername)
1186 require_once("$CFG->libdir/form/submit.php");
1187 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1188 $mform->addElement($submitlink);
1189 $mform->registerNoSubmitButton($checkboxcontrollername);
1190 $mform->setDefault($checkboxcontrollername, $text);
1194 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1195 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1196 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1197 * get data with get_data().
1199 * @param bool $cancel whether to show cancel button, default true
1200 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1202 function add_action_buttons($cancel = true, $submitlabel=null){
1203 if (is_null($submitlabel)){
1204 $submitlabel = get_string('savechanges');
1206 $mform =& $this->_form;
1207 if ($cancel){
1208 //when two elements we need a group
1209 $buttonarray=array();
1210 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1211 $buttonarray[] = &$mform->createElement('cancel');
1212 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1213 $mform->closeHeaderBefore('buttonar');
1214 } else {
1215 //no group needed
1216 $mform->addElement('submit', 'submitbutton', $submitlabel);
1217 $mform->closeHeaderBefore('submitbutton');
1222 * Adds an initialisation call for a standard JavaScript enhancement.
1224 * This function is designed to add an initialisation call for a JavaScript
1225 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1227 * Current options:
1228 * - Selectboxes
1229 * - smartselect: Turns a nbsp indented select box into a custom drop down
1230 * control that supports multilevel and category selection.
1231 * $enhancement = 'smartselect';
1232 * $options = array('selectablecategories' => true|false)
1234 * @since Moodle 2.0
1235 * @param string|element $element form element for which Javascript needs to be initalized
1236 * @param string $enhancement which init function should be called
1237 * @param array $options options passed to javascript
1238 * @param array $strings strings for javascript
1240 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1241 global $PAGE;
1242 if (is_string($element)) {
1243 $element = $this->_form->getElement($element);
1245 if (is_object($element)) {
1246 $element->_generateId();
1247 $elementid = $element->getAttribute('id');
1248 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1249 if (is_array($strings)) {
1250 foreach ($strings as $string) {
1251 if (is_array($string)) {
1252 call_user_func_array(array($PAGE->requires, 'string_for_js'), $string);
1253 } else {
1254 $PAGE->requires->string_for_js($string, 'moodle');
1262 * Returns a JS module definition for the mforms JS
1264 * @return array
1266 public static function get_js_module() {
1267 global $CFG;
1268 return array(
1269 'name' => 'mform',
1270 'fullpath' => '/lib/form/form.js',
1271 'requires' => array('base', 'node')
1276 * Detects elements with missing setType() declerations.
1278 * Finds elements in the form which should a PARAM_ type set and throws a
1279 * developer debug warning for any elements without it. This is to reduce the
1280 * risk of potential security issues by developers mistakenly forgetting to set
1281 * the type.
1283 * @return void
1285 private function detectMissingSetType() {
1286 global $CFG;
1288 if (!$CFG->debugdeveloper) {
1289 // Only for devs.
1290 return;
1293 $mform = $this->_form;
1294 foreach ($mform->_elements as $element) {
1295 $group = false;
1296 $elements = array($element);
1298 if ($element->getType() == 'group') {
1299 $group = $element;
1300 $elements = $element->getElements();
1303 foreach ($elements as $index => $element) {
1304 switch ($element->getType()) {
1305 case 'hidden':
1306 case 'text':
1307 case 'url':
1308 if ($group) {
1309 $name = $group->getElementName($index);
1310 } else {
1311 $name = $element->getName();
1313 $key = $name;
1314 $found = array_key_exists($key, $mform->_types);
1315 // For repeated elements we need to look for
1316 // the "main" type, not for the one present
1317 // on each repetition. All the stuff in formslib
1318 // (repeat_elements(), updateSubmission()... seems
1319 // to work that way.
1320 while (!$found && strrpos($key, '[') !== false) {
1321 $pos = strrpos($key, '[');
1322 $key = substr($key, 0, $pos);
1323 $found = array_key_exists($key, $mform->_types);
1325 if (!$found) {
1326 debugging("Did you remember to call setType() for '$name'? ".
1327 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1329 break;
1336 * Used by tests to simulate submitted form data submission from the user.
1338 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1339 * get_data.
1341 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1342 * global arrays after each test.
1344 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1345 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1346 * @param string $method 'post' or 'get', defaults to 'post'.
1347 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1348 * a different value here for some forms that are used more than once on the
1349 * same page.
1351 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1352 $formidentifier = null) {
1353 $_FILES = $simulatedsubmittedfiles;
1354 if ($formidentifier === null) {
1355 $formidentifier = get_called_class();
1357 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1358 $simulatedsubmitteddata['sesskey'] = sesskey();
1359 if (strtolower($method) === 'get') {
1360 $_GET = $simulatedsubmitteddata;
1361 } else {
1362 $_POST = $simulatedsubmitteddata;
1368 * MoodleQuickForm implementation
1370 * You never extend this class directly. The class methods of this class are available from
1371 * the private $this->_form property on moodleform and its children. You generally only
1372 * call methods on this class from within abstract methods that you override on moodleform such
1373 * as definition and definition_after_data
1375 * @package core_form
1376 * @category form
1377 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1378 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1380 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1381 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1382 var $_types = array();
1384 /** @var array dependent state for the element/'s */
1385 var $_dependencies = array();
1387 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1388 var $_noSubmitButtons=array();
1390 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1391 var $_cancelButtons=array();
1393 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1394 var $_advancedElements = array();
1397 * Array whose keys are element names and values are the desired collapsible state.
1398 * True for collapsed, False for expanded. If not present, set to default in
1399 * {@link self::accept()}.
1401 * @var array
1403 var $_collapsibleElements = array();
1406 * Whether to enable shortforms for this form
1408 * @var boolean
1410 var $_disableShortforms = false;
1412 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1413 protected $_use_form_change_checker = true;
1416 * The form name is derived from the class name of the wrapper minus the trailing form
1417 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1418 * @var string
1420 var $_formName = '';
1423 * String with the html for hidden params passed in as part of a moodle_url
1424 * object for the action. Output in the form.
1425 * @var string
1427 var $_pageparams = '';
1430 * Whether the form contains any client-side validation or not.
1431 * @var bool
1433 protected $clientvalidation = false;
1436 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1438 * @staticvar int $formcounter counts number of forms
1439 * @param string $formName Form's name.
1440 * @param string $method Form's method defaults to 'POST'
1441 * @param string|moodle_url $action Form's action
1442 * @param string $target (optional)Form's target defaults to none
1443 * @param mixed $attributes (optional)Extra attributes for <form> tag
1445 public function __construct($formName, $method, $action, $target='', $attributes=null) {
1446 global $CFG, $OUTPUT;
1448 static $formcounter = 1;
1450 // TODO MDL-52313 Replace with the call to parent::__construct().
1451 HTML_Common::__construct($attributes);
1452 $target = empty($target) ? array() : array('target' => $target);
1453 $this->_formName = $formName;
1454 if (is_a($action, 'moodle_url')){
1455 $this->_pageparams = html_writer::input_hidden_params($action);
1456 $action = $action->out_omit_querystring();
1457 } else {
1458 $this->_pageparams = '';
1460 // No 'name' atttribute for form in xhtml strict :
1461 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1462 if (is_null($this->getAttribute('id'))) {
1463 $attributes['id'] = 'mform' . $formcounter;
1465 $formcounter++;
1466 $this->updateAttributes($attributes);
1468 // This is custom stuff for Moodle :
1469 $oldclass= $this->getAttribute('class');
1470 if (!empty($oldclass)){
1471 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1472 }else {
1473 $this->updateAttributes(array('class'=>'mform'));
1475 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1476 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1477 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1481 * Old syntax of class constructor. Deprecated in PHP7.
1483 * @deprecated since Moodle 3.1
1485 public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1486 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1487 self::__construct($formName, $method, $action, $target, $attributes);
1491 * Use this method to indicate an element in a form is an advanced field. If items in a form
1492 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1493 * form so the user can decide whether to display advanced form controls.
1495 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1497 * @param string $elementName group or element name (not the element name of something inside a group).
1498 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1500 function setAdvanced($elementName, $advanced = true) {
1501 if ($advanced){
1502 $this->_advancedElements[$elementName]='';
1503 } elseif (isset($this->_advancedElements[$elementName])) {
1504 unset($this->_advancedElements[$elementName]);
1509 * Use this method to indicate that the fieldset should be shown as expanded.
1510 * The method is applicable to header elements only.
1512 * @param string $headername header element name
1513 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1514 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1515 * the form was submitted.
1516 * @return void
1518 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1519 if (empty($headername)) {
1520 return;
1522 $element = $this->getElement($headername);
1523 if ($element->getType() != 'header') {
1524 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1525 return;
1527 if (!$headerid = $element->getAttribute('id')) {
1528 $element->_generateId();
1529 $headerid = $element->getAttribute('id');
1531 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1532 // See if the form has been submitted already.
1533 $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1534 if (!$ignoreuserstate && $formexpanded != -1) {
1535 // Override expanded state with the form variable.
1536 $expanded = $formexpanded;
1538 // Create the form element for storing expanded state.
1539 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1540 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1541 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1543 $this->_collapsibleElements[$headername] = !$expanded;
1547 * Use this method to add show more/less status element required for passing
1548 * over the advanced elements visibility status on the form submission.
1550 * @param string $headerName header element name.
1551 * @param boolean $showmore default false sets the advanced elements to be hidden.
1553 function addAdvancedStatusElement($headerid, $showmore=false){
1554 // Add extra hidden element to store advanced items state for each section.
1555 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1556 // See if we the form has been submitted already.
1557 $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1558 if (!$showmore && $formshowmore != -1) {
1559 // Override showmore state with the form variable.
1560 $showmore = $formshowmore;
1562 // Create the form element for storing advanced items state.
1563 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1564 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1565 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1570 * This function has been deprecated. Show advanced has been replaced by
1571 * "Show more.../Show less..." in the shortforms javascript module.
1573 * @deprecated since Moodle 2.5
1574 * @param bool $showadvancedNow if true will show advanced elements.
1576 function setShowAdvanced($showadvancedNow = null){
1577 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1581 * This function has been deprecated. Show advanced has been replaced by
1582 * "Show more.../Show less..." in the shortforms javascript module.
1584 * @deprecated since Moodle 2.5
1585 * @return bool (Always false)
1587 function getShowAdvanced(){
1588 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1589 return false;
1593 * Use this method to indicate that the form will not be using shortforms.
1595 * @param boolean $disable default true, controls if the shortforms are disabled.
1597 function setDisableShortforms ($disable = true) {
1598 $this->_disableShortforms = $disable;
1602 * Call this method if you don't want the formchangechecker JavaScript to be
1603 * automatically initialised for this form.
1605 public function disable_form_change_checker() {
1606 $this->_use_form_change_checker = false;
1610 * If you have called {@link disable_form_change_checker()} then you can use
1611 * this method to re-enable it. It is enabled by default, so normally you don't
1612 * need to call this.
1614 public function enable_form_change_checker() {
1615 $this->_use_form_change_checker = true;
1619 * @return bool whether this form should automatically initialise
1620 * formchangechecker for itself.
1622 public function is_form_change_checker_enabled() {
1623 return $this->_use_form_change_checker;
1627 * Accepts a renderer
1629 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1631 function accept(&$renderer) {
1632 if (method_exists($renderer, 'setAdvancedElements')){
1633 //Check for visible fieldsets where all elements are advanced
1634 //and mark these headers as advanced as well.
1635 //Also mark all elements in a advanced header as advanced.
1636 $stopFields = $renderer->getStopFieldSetElements();
1637 $lastHeader = null;
1638 $lastHeaderAdvanced = false;
1639 $anyAdvanced = false;
1640 $anyError = false;
1641 foreach (array_keys($this->_elements) as $elementIndex){
1642 $element =& $this->_elements[$elementIndex];
1644 // if closing header and any contained element was advanced then mark it as advanced
1645 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1646 if ($anyAdvanced && !is_null($lastHeader)) {
1647 $lastHeader->_generateId();
1648 $this->setAdvanced($lastHeader->getName());
1649 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1651 $lastHeaderAdvanced = false;
1652 unset($lastHeader);
1653 $lastHeader = null;
1654 } elseif ($lastHeaderAdvanced) {
1655 $this->setAdvanced($element->getName());
1658 if ($element->getType()=='header'){
1659 $lastHeader =& $element;
1660 $anyAdvanced = false;
1661 $anyError = false;
1662 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1663 } elseif (isset($this->_advancedElements[$element->getName()])){
1664 $anyAdvanced = true;
1665 if (isset($this->_errors[$element->getName()])) {
1666 $anyError = true;
1670 // the last header may not be closed yet...
1671 if ($anyAdvanced && !is_null($lastHeader)){
1672 $this->setAdvanced($lastHeader->getName());
1673 $lastHeader->_generateId();
1674 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1676 $renderer->setAdvancedElements($this->_advancedElements);
1678 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1680 // Count the number of sections.
1681 $headerscount = 0;
1682 foreach (array_keys($this->_elements) as $elementIndex){
1683 $element =& $this->_elements[$elementIndex];
1684 if ($element->getType() == 'header') {
1685 $headerscount++;
1689 $anyrequiredorerror = false;
1690 $headercounter = 0;
1691 $headername = null;
1692 foreach (array_keys($this->_elements) as $elementIndex){
1693 $element =& $this->_elements[$elementIndex];
1695 if ($element->getType() == 'header') {
1696 $headercounter++;
1697 $element->_generateId();
1698 $headername = $element->getName();
1699 $anyrequiredorerror = false;
1700 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1701 $anyrequiredorerror = true;
1702 } else {
1703 // Do not reset $anyrequiredorerror to false because we do not want any other element
1704 // in this header (fieldset) to possibly revert the state given.
1707 if ($element->getType() == 'header') {
1708 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1709 // By default the first section is always expanded, except if a state has already been set.
1710 $this->setExpanded($headername, true);
1711 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1712 // The second section is always expanded if the form only contains 2 sections),
1713 // except if a state has already been set.
1714 $this->setExpanded($headername, true);
1716 } else if ($anyrequiredorerror) {
1717 // If any error or required field are present within the header, we need to expand it.
1718 $this->setExpanded($headername, true, true);
1719 } else if (!isset($this->_collapsibleElements[$headername])) {
1720 // Define element as collapsed by default.
1721 $this->setExpanded($headername, false);
1725 // Pass the array to renderer object.
1726 $renderer->setCollapsibleElements($this->_collapsibleElements);
1728 parent::accept($renderer);
1732 * Adds one or more element names that indicate the end of a fieldset
1734 * @param string $elementName name of the element
1736 function closeHeaderBefore($elementName){
1737 $renderer =& $this->defaultRenderer();
1738 $renderer->addStopFieldsetElements($elementName);
1742 * Should be used for all elements of a form except for select, radio and checkboxes which
1743 * clean their own data.
1745 * @param string $elementname
1746 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1747 * {@link lib/moodlelib.php} for defined parameter types
1749 function setType($elementname, $paramtype) {
1750 $this->_types[$elementname] = $paramtype;
1754 * This can be used to set several types at once.
1756 * @param array $paramtypes types of parameters.
1757 * @see MoodleQuickForm::setType
1759 function setTypes($paramtypes) {
1760 $this->_types = $paramtypes + $this->_types;
1764 * Return the type(s) to use to clean an element.
1766 * In the case where the element has an array as a value, we will try to obtain a
1767 * type defined for that specific key, and recursively until done.
1769 * This method does not work reverse, you cannot pass a nested element and hoping to
1770 * fallback on the clean type of a parent. This method intends to be used with the
1771 * main element, which will generate child types if needed, not the other way around.
1773 * Example scenario:
1775 * You have defined a new repeated element containing a text field called 'foo'.
1776 * By default there will always be 2 occurence of 'foo' in the form. Even though
1777 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1778 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1779 * $mform->setType('foo[0]', PARAM_FLOAT).
1781 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1782 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1783 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1784 * get the default clean type returned (param $default).
1786 * @param string $elementname name of the element.
1787 * @param mixed $value value that should be cleaned.
1788 * @param int $default default constant value to be returned (PARAM_...)
1789 * @return string|array constant value or array of constant values (PARAM_...)
1791 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1792 $type = $default;
1793 if (array_key_exists($elementname, $this->_types)) {
1794 $type = $this->_types[$elementname];
1796 if (is_array($value)) {
1797 $default = $type;
1798 $type = array();
1799 foreach ($value as $subkey => $subvalue) {
1800 $typekey = "$elementname" . "[$subkey]";
1801 if (array_key_exists($typekey, $this->_types)) {
1802 $subtype = $this->_types[$typekey];
1803 } else {
1804 $subtype = $default;
1806 if (is_array($subvalue)) {
1807 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1808 } else {
1809 $type[$subkey] = $subtype;
1813 return $type;
1817 * Return the cleaned value using the passed type(s).
1819 * @param mixed $value value that has to be cleaned.
1820 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1821 * @return mixed cleaned up value.
1823 public function getCleanedValue($value, $type) {
1824 if (is_array($type) && is_array($value)) {
1825 foreach ($type as $key => $param) {
1826 $value[$key] = $this->getCleanedValue($value[$key], $param);
1828 } else if (!is_array($type) && !is_array($value)) {
1829 $value = clean_param($value, $type);
1830 } else if (!is_array($type) && is_array($value)) {
1831 $value = clean_param_array($value, $type, true);
1832 } else {
1833 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1835 return $value;
1839 * Updates submitted values
1841 * @param array $submission submitted values
1842 * @param array $files list of files
1844 function updateSubmission($submission, $files) {
1845 $this->_flagSubmitted = false;
1847 if (empty($submission)) {
1848 $this->_submitValues = array();
1849 } else {
1850 foreach ($submission as $key => $s) {
1851 $type = $this->getCleanType($key, $s);
1852 $submission[$key] = $this->getCleanedValue($s, $type);
1854 $this->_submitValues = $submission;
1855 $this->_flagSubmitted = true;
1858 if (empty($files)) {
1859 $this->_submitFiles = array();
1860 } else {
1861 $this->_submitFiles = $files;
1862 $this->_flagSubmitted = true;
1865 // need to tell all elements that they need to update their value attribute.
1866 foreach (array_keys($this->_elements) as $key) {
1867 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1872 * Returns HTML for required elements
1874 * @return string
1876 function getReqHTML(){
1877 return $this->_reqHTML;
1881 * Returns HTML for advanced elements
1883 * @return string
1885 function getAdvancedHTML(){
1886 return $this->_advancedHTML;
1890 * Initializes a default form value. Used to specify the default for a new entry where
1891 * no data is loaded in using moodleform::set_data()
1893 * note: $slashed param removed
1895 * @param string $elementName element name
1896 * @param mixed $defaultValue values for that element name
1898 function setDefault($elementName, $defaultValue){
1899 $this->setDefaults(array($elementName=>$defaultValue));
1903 * Add a help button to element, only one button per element is allowed.
1905 * This is new, simplified and preferable method of setting a help icon on form elements.
1906 * It uses the new $OUTPUT->help_icon().
1908 * Typically, you will provide the same identifier and the component as you have used for the
1909 * label of the element. The string identifier with the _help suffix added is then used
1910 * as the help string.
1912 * There has to be two strings defined:
1913 * 1/ get_string($identifier, $component) - the title of the help page
1914 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1916 * @since Moodle 2.0
1917 * @param string $elementname name of the element to add the item to
1918 * @param string $identifier help string identifier without _help suffix
1919 * @param string $component component name to look the help string in
1920 * @param string $linktext optional text to display next to the icon
1921 * @param bool $suppresscheck set to true if the element may not exist
1923 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1924 global $OUTPUT;
1925 if (array_key_exists($elementname, $this->_elementIndex)) {
1926 $element = $this->_elements[$this->_elementIndex[$elementname]];
1927 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1928 } else if (!$suppresscheck) {
1929 debugging(get_string('nonexistentformelements', 'form', $elementname));
1934 * Set constant value not overridden by _POST or _GET
1935 * note: this does not work for complex names with [] :-(
1937 * @param string $elname name of element
1938 * @param mixed $value
1940 function setConstant($elname, $value) {
1941 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1942 $element =& $this->getElement($elname);
1943 $element->onQuickFormEvent('updateValue', null, $this);
1947 * export submitted values
1949 * @param string $elementList list of elements in form
1950 * @return array
1952 function exportValues($elementList = null){
1953 $unfiltered = array();
1954 if (null === $elementList) {
1955 // iterate over all elements, calling their exportValue() methods
1956 foreach (array_keys($this->_elements) as $key) {
1957 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1958 $varname = $this->_elements[$key]->_attributes['name'];
1959 $value = '';
1960 // If we have a default value then export it.
1961 if (isset($this->_defaultValues[$varname])) {
1962 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
1964 } else {
1965 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1968 if (is_array($value)) {
1969 // This shit throws a bogus warning in PHP 4.3.x
1970 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1973 } else {
1974 if (!is_array($elementList)) {
1975 $elementList = array_map('trim', explode(',', $elementList));
1977 foreach ($elementList as $elementName) {
1978 $value = $this->exportValue($elementName);
1979 if (@PEAR::isError($value)) {
1980 return $value;
1982 //oh, stock QuickFOrm was returning array of arrays!
1983 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1987 if (is_array($this->_constantValues)) {
1988 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1990 return $unfiltered;
1994 * This is a bit of a hack, and it duplicates the code in
1995 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
1996 * reliably calling that code. (Think about date selectors, for example.)
1997 * @param string $name the element name.
1998 * @param mixed $value the fixed value to set.
1999 * @return mixed the appropriate array to add to the $unfiltered array.
2001 protected function prepare_fixed_value($name, $value) {
2002 if (null === $value) {
2003 return null;
2004 } else {
2005 if (!strpos($name, '[')) {
2006 return array($name => $value);
2007 } else {
2008 $valueAry = array();
2009 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2010 eval("\$valueAry$myIndex = \$value;");
2011 return $valueAry;
2017 * Adds a validation rule for the given field
2019 * If the element is in fact a group, it will be considered as a whole.
2020 * To validate grouped elements as separated entities,
2021 * use addGroupRule instead of addRule.
2023 * @param string $element Form element name
2024 * @param string $message Message to display for invalid data
2025 * @param string $type Rule type, use getRegisteredRules() to get types
2026 * @param string $format (optional)Required for extra rule data
2027 * @param string $validation (optional)Where to perform validation: "server", "client"
2028 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2029 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2031 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2033 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2034 if ($validation == 'client') {
2035 $this->clientvalidation = true;
2041 * Adds a validation rule for the given group of elements
2043 * Only groups with a name can be assigned a validation rule
2044 * Use addGroupRule when you need to validate elements inside the group.
2045 * Use addRule if you need to validate the group as a whole. In this case,
2046 * the same rule will be applied to all elements in the group.
2047 * Use addRule if you need to validate the group against a function.
2049 * @param string $group Form group name
2050 * @param array|string $arg1 Array for multiple elements or error message string for one element
2051 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2052 * @param string $format (optional)Required for extra rule data
2053 * @param int $howmany (optional)How many valid elements should be in the group
2054 * @param string $validation (optional)Where to perform validation: "server", "client"
2055 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2057 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2059 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2060 if (is_array($arg1)) {
2061 foreach ($arg1 as $rules) {
2062 foreach ($rules as $rule) {
2063 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2064 if ($validation == 'client') {
2065 $this->clientvalidation = true;
2069 } elseif (is_string($arg1)) {
2070 if ($validation == 'client') {
2071 $this->clientvalidation = true;
2077 * Returns the client side validation script
2079 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2080 * and slightly modified to run rules per-element
2081 * Needed to override this because of an error with client side validation of grouped elements.
2083 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2085 function getValidationScript()
2087 if (empty($this->_rules) || $this->clientvalidation === false) {
2088 return '';
2091 include_once('HTML/QuickForm/RuleRegistry.php');
2092 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2093 $test = array();
2094 $js_escape = array(
2095 "\r" => '\r',
2096 "\n" => '\n',
2097 "\t" => '\t',
2098 "'" => "\\'",
2099 '"' => '\"',
2100 '\\' => '\\\\'
2103 foreach ($this->_rules as $elementName => $rules) {
2104 foreach ($rules as $rule) {
2105 if ('client' == $rule['validation']) {
2106 unset($element); //TODO: find out how to properly initialize it
2108 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2109 $rule['message'] = strtr($rule['message'], $js_escape);
2111 if (isset($rule['group'])) {
2112 $group =& $this->getElement($rule['group']);
2113 // No JavaScript validation for frozen elements
2114 if ($group->isFrozen()) {
2115 continue 2;
2117 $elements =& $group->getElements();
2118 foreach (array_keys($elements) as $key) {
2119 if ($elementName == $group->getElementName($key)) {
2120 $element =& $elements[$key];
2121 break;
2124 } elseif ($dependent) {
2125 $element = array();
2126 $element[] =& $this->getElement($elementName);
2127 foreach ($rule['dependent'] as $elName) {
2128 $element[] =& $this->getElement($elName);
2130 } else {
2131 $element =& $this->getElement($elementName);
2133 // No JavaScript validation for frozen elements
2134 if (is_object($element) && $element->isFrozen()) {
2135 continue 2;
2136 } elseif (is_array($element)) {
2137 foreach (array_keys($element) as $key) {
2138 if ($element[$key]->isFrozen()) {
2139 continue 3;
2143 //for editor element, [text] is appended to the name.
2144 $fullelementname = $elementName;
2145 if ($element->getType() == 'editor') {
2146 $fullelementname .= '[text]';
2147 //Add format to rule as moodleform check which format is supported by browser
2148 //it is not set anywhere... So small hack to make sure we pass it down to quickform
2149 if (is_null($rule['format'])) {
2150 $rule['format'] = $element->getFormat();
2153 // Fix for bug displaying errors for elements in a group
2154 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2155 $test[$fullelementname][1]=$element;
2156 //end of fix
2161 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2162 // the form, and then that form field gets corrupted by the code that follows.
2163 unset($element);
2165 $js = '
2166 <script type="text/javascript">
2167 //<![CDATA[
2169 var skipClientValidation = false;
2171 (function() {
2173 function qf_errorHandler(element, _qfMsg, escapedName) {
2174 div = element.parentNode;
2176 if ((div == undefined) || (element.name == undefined)) {
2177 //no checking can be done for undefined elements so let server handle it.
2178 return true;
2181 if (_qfMsg != \'\') {
2182 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2183 if (!errorSpan) {
2184 errorSpan = document.createElement("span");
2185 errorSpan.id = \'id_error_\' + escapedName;
2186 errorSpan.className = "error";
2187 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2188 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2189 document.getElementById(errorSpan.id).focus();
2192 while (errorSpan.firstChild) {
2193 errorSpan.removeChild(errorSpan.firstChild);
2196 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2198 if (div.className.substr(div.className.length - 6, 6) != " error"
2199 && div.className != "error") {
2200 div.className += " error";
2201 linebreak = document.createElement("br");
2202 linebreak.className = "error";
2203 linebreak.id = \'id_error_break_\' + escapedName;
2204 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2207 return false;
2208 } else {
2209 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2210 if (errorSpan) {
2211 errorSpan.parentNode.removeChild(errorSpan);
2213 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2214 if (linebreak) {
2215 linebreak.parentNode.removeChild(linebreak);
2218 if (div.className.substr(div.className.length - 6, 6) == " error") {
2219 div.className = div.className.substr(0, div.className.length - 6);
2220 } else if (div.className == "error") {
2221 div.className = "";
2224 return true;
2227 $validateJS = '';
2228 foreach ($test as $elementName => $jsandelement) {
2229 // Fix for bug displaying errors for elements in a group
2230 //unset($element);
2231 list($jsArr,$element)=$jsandelement;
2232 //end of fix
2233 $escapedElementName = preg_replace_callback(
2234 '/[_\[\]-]/',
2235 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2236 $elementName);
2237 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
2239 $js .= '
2240 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2241 if (undefined == element) {
2242 //required element was not found, then let form be submitted without client side validation
2243 return true;
2245 var value = \'\';
2246 var errFlag = new Array();
2247 var _qfGroups = {};
2248 var _qfMsg = \'\';
2249 var frm = element.parentNode;
2250 if ((undefined != element.name) && (frm != undefined)) {
2251 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2252 frm = frm.parentNode;
2254 ' . join("\n", $jsArr) . '
2255 return qf_errorHandler(element, _qfMsg, escapedName);
2256 } else {
2257 //element name should be defined else error msg will not be displayed.
2258 return true;
2262 document.getElementById(\'' . $element->_attributes['id'] . '\').addEventListener(\'blur\', function(ev) {
2263 ' . $valFunc . '
2265 document.getElementById(\'' . $element->_attributes['id'] . '\').addEventListener(\'change\', function(ev) {
2266 ' . $valFunc . '
2269 $validateJS .= '
2270 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2271 if (!ret && !first_focus) {
2272 first_focus = true;
2273 Y.use(\'moodle-core-event\', function() {
2274 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes['id'] . '\',
2275 elementid: \'id_error_' . $escapedElementName . '\'});
2276 document.getElementById(\'id_error_' . $escapedElementName . '\').focus();
2281 // Fix for bug displaying errors for elements in a group
2282 //unset($element);
2283 //$element =& $this->getElement($elementName);
2284 //end of fix
2285 //$onBlur = $element->getAttribute('onBlur');
2286 //$onChange = $element->getAttribute('onChange');
2287 //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2288 //'onChange' => $onChange . $valFunc));
2290 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2291 $js .= '
2293 function validate_' . $this->_formName . '() {
2294 if (skipClientValidation) {
2295 return true;
2297 var ret = true;
2299 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2300 var first_focus = false;
2301 ' . $validateJS . ';
2302 return ret;
2306 document.getElementById(\'' . $this->_attributes['id'] . '\').addEventListener(\'submit\', function(ev) {
2307 try {
2308 var myValidator = validate_' . $this->_formName . ';
2309 } catch(e) {
2310 return true;
2312 if (!myValidator()) {
2313 ev.preventDefault();
2316 })();
2317 //]]>
2318 </script>';
2319 return $js;
2320 } // end func getValidationScript
2323 * Sets default error message
2325 function _setDefaultRuleMessages(){
2326 foreach ($this->_rules as $field => $rulesarr){
2327 foreach ($rulesarr as $key => $rule){
2328 if ($rule['message']===null){
2329 $a=new stdClass();
2330 $a->format=$rule['format'];
2331 $str=get_string('err_'.$rule['type'], 'form', $a);
2332 if (strpos($str, '[[')!==0){
2333 $this->_rules[$field][$key]['message']=$str;
2341 * Get list of attributes which have dependencies
2343 * @return array
2345 function getLockOptionObject(){
2346 $result = array();
2347 foreach ($this->_dependencies as $dependentOn => $conditions){
2348 $result[$dependentOn] = array();
2349 foreach ($conditions as $condition=>$values) {
2350 $result[$dependentOn][$condition] = array();
2351 foreach ($values as $value=>$dependents) {
2352 $result[$dependentOn][$condition][$value] = array();
2353 $i = 0;
2354 foreach ($dependents as $dependent) {
2355 $elements = $this->_getElNamesRecursive($dependent);
2356 if (empty($elements)) {
2357 // probably element inside of some group
2358 $elements = array($dependent);
2360 foreach($elements as $element) {
2361 if ($element == $dependentOn) {
2362 continue;
2364 $result[$dependentOn][$condition][$value][] = $element;
2370 return array($this->getAttribute('id'), $result);
2374 * Get names of element or elements in a group.
2376 * @param HTML_QuickForm_group|element $element element group or element object
2377 * @return array
2379 function _getElNamesRecursive($element) {
2380 if (is_string($element)) {
2381 if (!$this->elementExists($element)) {
2382 return array();
2384 $element = $this->getElement($element);
2387 if (is_a($element, 'HTML_QuickForm_group')) {
2388 $elsInGroup = $element->getElements();
2389 $elNames = array();
2390 foreach ($elsInGroup as $elInGroup){
2391 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2392 // not sure if this would work - groups nested in groups
2393 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2394 } else {
2395 $elNames[] = $element->getElementName($elInGroup->getName());
2399 } else if (is_a($element, 'HTML_QuickForm_header')) {
2400 return array();
2402 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2403 return array();
2405 } else if (method_exists($element, 'getPrivateName') &&
2406 !($element instanceof HTML_QuickForm_advcheckbox)) {
2407 // The advcheckbox element implements a method called getPrivateName,
2408 // but in a way that is not compatible with the generic API, so we
2409 // have to explicitly exclude it.
2410 return array($element->getPrivateName());
2412 } else {
2413 $elNames = array($element->getName());
2416 return $elNames;
2420 * Adds a dependency for $elementName which will be disabled if $condition is met.
2421 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2422 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2423 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2424 * of the $dependentOn element is $condition (such as equal) to $value.
2426 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2427 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2428 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2430 * @param string $elementName the name of the element which will be disabled
2431 * @param string $dependentOn the name of the element whose state will be checked for condition
2432 * @param string $condition the condition to check
2433 * @param mixed $value used in conjunction with condition.
2435 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2436 // Multiple selects allow for a multiple selection, we transform the array to string here as
2437 // an array cannot be used as a key in an associative array.
2438 if (is_array($value)) {
2439 $value = implode('|', $value);
2441 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2442 $this->_dependencies[$dependentOn] = array();
2444 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2445 $this->_dependencies[$dependentOn][$condition] = array();
2447 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2448 $this->_dependencies[$dependentOn][$condition][$value] = array();
2450 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2454 * Registers button as no submit button
2456 * @param string $buttonname name of the button
2458 function registerNoSubmitButton($buttonname){
2459 $this->_noSubmitButtons[]=$buttonname;
2463 * Checks if button is a no submit button, i.e it doesn't submit form
2465 * @param string $buttonname name of the button to check
2466 * @return bool
2468 function isNoSubmitButton($buttonname){
2469 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2473 * Registers a button as cancel button
2475 * @param string $addfieldsname name of the button
2477 function _registerCancelButton($addfieldsname){
2478 $this->_cancelButtons[]=$addfieldsname;
2482 * Displays elements without HTML input tags.
2483 * This method is different to freeze() in that it makes sure no hidden
2484 * elements are included in the form.
2485 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2487 * This function also removes all previously defined rules.
2489 * @param string|array $elementList array or string of element(s) to be frozen
2490 * @return object|bool if element list is not empty then return error object, else true
2492 function hardFreeze($elementList=null)
2494 if (!isset($elementList)) {
2495 $this->_freezeAll = true;
2496 $elementList = array();
2497 } else {
2498 if (!is_array($elementList)) {
2499 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2501 $elementList = array_flip($elementList);
2504 foreach (array_keys($this->_elements) as $key) {
2505 $name = $this->_elements[$key]->getName();
2506 if ($this->_freezeAll || isset($elementList[$name])) {
2507 $this->_elements[$key]->freeze();
2508 $this->_elements[$key]->setPersistantFreeze(false);
2509 unset($elementList[$name]);
2511 // remove all rules
2512 $this->_rules[$name] = array();
2513 // if field is required, remove the rule
2514 $unset = array_search($name, $this->_required);
2515 if ($unset !== false) {
2516 unset($this->_required[$unset]);
2521 if (!empty($elementList)) {
2522 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);
2524 return true;
2528 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2530 * This function also removes all previously defined rules of elements it freezes.
2532 * @throws HTML_QuickForm_Error
2533 * @param array $elementList array or string of element(s) not to be frozen
2534 * @return bool returns true
2536 function hardFreezeAllVisibleExcept($elementList)
2538 $elementList = array_flip($elementList);
2539 foreach (array_keys($this->_elements) as $key) {
2540 $name = $this->_elements[$key]->getName();
2541 $type = $this->_elements[$key]->getType();
2543 if ($type == 'hidden'){
2544 // leave hidden types as they are
2545 } elseif (!isset($elementList[$name])) {
2546 $this->_elements[$key]->freeze();
2547 $this->_elements[$key]->setPersistantFreeze(false);
2549 // remove all rules
2550 $this->_rules[$name] = array();
2551 // if field is required, remove the rule
2552 $unset = array_search($name, $this->_required);
2553 if ($unset !== false) {
2554 unset($this->_required[$unset]);
2558 return true;
2562 * Tells whether the form was already submitted
2564 * This is useful since the _submitFiles and _submitValues arrays
2565 * may be completely empty after the trackSubmit value is removed.
2567 * @return bool
2569 function isSubmitted()
2571 return parent::isSubmitted() && (!$this->isFrozen());
2576 * MoodleQuickForm renderer
2578 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2579 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2581 * Stylesheet is part of standard theme and should be automatically included.
2583 * @package core_form
2584 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2587 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2589 /** @var array Element template array */
2590 var $_elementTemplates;
2593 * Template used when opening a hidden fieldset
2594 * (i.e. a fieldset that is opened when there is no header element)
2595 * @var string
2597 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2599 /** @var string Header Template string */
2600 var $_headerTemplate =
2601 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2603 /** @var string Template used when opening a fieldset */
2604 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2606 /** @var string Template used when closing a fieldset */
2607 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2609 /** @var string Required Note template string */
2610 var $_requiredNoteTemplate =
2611 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2614 * Collapsible buttons string template.
2616 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2617 * until the Javascript has been fully loaded.
2619 * @var string
2621 var $_collapseButtonsTemplate =
2622 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2625 * Array whose keys are element names. If the key exists this is a advanced element
2627 * @var array
2629 var $_advancedElements = array();
2632 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2634 * @var array
2636 var $_collapsibleElements = array();
2639 * @var string Contains the collapsible buttons to add to the form.
2641 var $_collapseButtons = '';
2644 * Constructor
2646 public function __construct() {
2647 // switch next two lines for ol li containers for form items.
2648 // $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 --> {type}"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></li>');
2649 $this->_elementTemplates = array(
2650 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}" {aria-live}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2652 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2654 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced} {class}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2656 'static'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}"><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 -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2658 'warning'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}">{element}</div>',
2660 'nodisplay'=>'');
2662 parent::__construct();
2666 * Old syntax of class constructor. Deprecated in PHP7.
2668 * @deprecated since Moodle 3.1
2670 public function MoodleQuickForm_Renderer() {
2671 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2672 self::__construct();
2676 * Set element's as adavance element
2678 * @param array $elements form elements which needs to be grouped as advance elements.
2680 function setAdvancedElements($elements){
2681 $this->_advancedElements = $elements;
2685 * Setting collapsible elements
2687 * @param array $elements
2689 function setCollapsibleElements($elements) {
2690 $this->_collapsibleElements = $elements;
2694 * What to do when starting the form
2696 * @param MoodleQuickForm $form reference of the form
2698 function startForm(&$form){
2699 global $PAGE;
2700 $this->_reqHTML = $form->getReqHTML();
2701 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2702 $this->_advancedHTML = $form->getAdvancedHTML();
2703 $this->_collapseButtons = '';
2704 $formid = $form->getAttribute('id');
2705 parent::startForm($form);
2706 if ($form->isFrozen()){
2707 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2708 } else {
2709 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2710 $this->_hiddenHtml .= $form->_pageparams;
2713 if ($form->is_form_change_checker_enabled()) {
2714 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2715 'M.core_formchangechecker.init',
2716 array(array(
2717 'formid' => $formid
2720 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2722 if (!empty($this->_collapsibleElements)) {
2723 if (count($this->_collapsibleElements) > 1) {
2724 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2725 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2726 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2728 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2730 if (!empty($this->_advancedElements)){
2731 $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2732 $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2737 * Create advance group of elements
2739 * @param object $group Passed by reference
2740 * @param bool $required if input is required field
2741 * @param string $error error message to display
2743 function startGroup(&$group, $required, $error){
2744 // Make sure the element has an id.
2745 $group->_generateId();
2747 if (method_exists($group, 'getElementTemplateType')){
2748 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2749 }else{
2750 $html = $this->_elementTemplates['default'];
2754 if (isset($this->_advancedElements[$group->getName()])){
2755 $html =str_replace(' {advanced}', ' advanced', $html);
2756 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2757 } else {
2758 $html =str_replace(' {advanced}', '', $html);
2759 $html =str_replace('{advancedimg}', '', $html);
2761 if (method_exists($group, 'getHelpButton')){
2762 $html =str_replace('{help}', $group->getHelpButton(), $html);
2763 }else{
2764 $html =str_replace('{help}', '', $html);
2766 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2767 $html =str_replace('{name}', $group->getName(), $html);
2768 $html =str_replace('{type}', 'fgroup', $html);
2769 $html =str_replace('{class}', $group->getAttribute('class'), $html);
2770 $emptylabel = '';
2771 if ($group->getLabel() == '') {
2772 $emptylabel = 'femptylabel';
2774 $html = str_replace('{emptylabel}', $emptylabel, $html);
2776 $this->_templates[$group->getName()]=$html;
2777 // Fix for bug in tableless quickforms that didn't allow you to stop a
2778 // fieldset before a group of elements.
2779 // if the element name indicates the end of a fieldset, close the fieldset
2780 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2781 && $this->_fieldsetsOpen > 0
2783 $this->_html .= $this->_closeFieldsetTemplate;
2784 $this->_fieldsetsOpen--;
2786 parent::startGroup($group, $required, $error);
2790 * Renders element
2792 * @param HTML_QuickForm_element $element element
2793 * @param bool $required if input is required field
2794 * @param string $error error message to display
2796 function renderElement(&$element, $required, $error){
2797 // Make sure the element has an id.
2798 $element->_generateId();
2800 //adding stuff to place holders in template
2801 //check if this is a group element first
2802 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2803 // so it gets substitutions for *each* element
2804 $html = $this->_groupElementTemplate;
2806 elseif (method_exists($element, 'getElementTemplateType')){
2807 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2808 }else{
2809 $html = $this->_elementTemplates['default'];
2811 if (isset($this->_advancedElements[$element->getName()])){
2812 $html = str_replace(' {advanced}', ' advanced', $html);
2813 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2814 } else {
2815 $html = str_replace(' {advanced}', '', $html);
2816 $html = str_replace(' {aria-live}', '', $html);
2818 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2819 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2820 } else {
2821 $html =str_replace('{advancedimg}', '', $html);
2823 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2824 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2825 $html =str_replace('{name}', $element->getName(), $html);
2826 $emptylabel = '';
2827 if ($element->getLabel() == '') {
2828 $emptylabel = 'femptylabel';
2830 $html = str_replace('{emptylabel}', $emptylabel, $html);
2831 if (method_exists($element, 'getHelpButton')){
2832 $html = str_replace('{help}', $element->getHelpButton(), $html);
2833 }else{
2834 $html = str_replace('{help}', '', $html);
2837 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2838 $this->_groupElementTemplate = $html;
2840 elseif (!isset($this->_templates[$element->getName()])) {
2841 $this->_templates[$element->getName()] = $html;
2844 parent::renderElement($element, $required, $error);
2848 * Called when visiting a form, after processing all form elements
2849 * Adds required note, form attributes, validation javascript and form content.
2851 * @global moodle_page $PAGE
2852 * @param moodleform $form Passed by reference
2854 function finishForm(&$form){
2855 global $PAGE;
2856 if ($form->isFrozen()){
2857 $this->_hiddenHtml = '';
2859 parent::finishForm($form);
2860 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2861 if (!$form->isFrozen()) {
2862 $args = $form->getLockOptionObject();
2863 if (count($args[1]) > 0) {
2864 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2869 * Called when visiting a header element
2871 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2872 * @global moodle_page $PAGE
2874 function renderHeader(&$header) {
2875 global $PAGE;
2877 $header->_generateId();
2878 $name = $header->getName();
2880 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2881 if (is_null($header->_text)) {
2882 $header_html = '';
2883 } elseif (!empty($name) && isset($this->_templates[$name])) {
2884 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2885 } else {
2886 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2889 if ($this->_fieldsetsOpen > 0) {
2890 $this->_html .= $this->_closeFieldsetTemplate;
2891 $this->_fieldsetsOpen--;
2894 // Define collapsible classes for fieldsets.
2895 $arialive = '';
2896 $fieldsetclasses = array('clearfix');
2897 if (isset($this->_collapsibleElements[$header->getName()])) {
2898 $fieldsetclasses[] = 'collapsible';
2899 if ($this->_collapsibleElements[$header->getName()]) {
2900 $fieldsetclasses[] = 'collapsed';
2904 if (isset($this->_advancedElements[$name])){
2905 $fieldsetclasses[] = 'containsadvancedelements';
2908 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2909 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
2911 $this->_html .= $openFieldsetTemplate . $header_html;
2912 $this->_fieldsetsOpen++;
2916 * Return Array of element names that indicate the end of a fieldset
2918 * @return array
2920 function getStopFieldsetElements(){
2921 return $this->_stopFieldsetElements;
2926 * Required elements validation
2928 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2930 * @package core_form
2931 * @category form
2932 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2933 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2935 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2937 * Checks if an element is not empty.
2938 * This is a server-side validation, it works for both text fields and editor fields
2940 * @param string $value Value to check
2941 * @param int|string|array $options Not used yet
2942 * @return bool true if value is not empty
2944 function validate($value, $options = null) {
2945 global $CFG;
2946 if (is_array($value) && array_key_exists('text', $value)) {
2947 $value = $value['text'];
2949 if (is_array($value)) {
2950 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2951 $value = implode('', $value);
2953 $stripvalues = array(
2954 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2955 '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
2957 if (!empty($CFG->strictformsrequired)) {
2958 $value = preg_replace($stripvalues, '', (string)$value);
2960 if ((string)$value == '') {
2961 return false;
2963 return true;
2967 * This function returns Javascript code used to build client-side validation.
2968 * It checks if an element is not empty.
2970 * @param int $format format of data which needs to be validated.
2971 * @return array
2973 function getValidationScript($format = null) {
2974 global $CFG;
2975 if (!empty($CFG->strictformsrequired)) {
2976 if (!empty($format) && $format == FORMAT_HTML) {
2977 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
2978 } else {
2979 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2981 } else {
2982 return array('', "{jsVar} == ''");
2988 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2989 * @name $_HTML_QuickForm_default_renderer
2991 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2993 /** Please keep this list in alphabetical order. */
2994 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2995 MoodleQuickForm::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
2996 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2997 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2998 MoodleQuickForm::registerElementType('course', "$CFG->libdir/form/course.php", 'MoodleQuickForm_course');
2999 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
3000 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
3001 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
3002 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
3003 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
3004 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
3005 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
3006 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
3007 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
3008 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
3009 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
3010 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
3011 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
3012 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
3013 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
3014 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
3015 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
3016 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
3017 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
3018 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
3019 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
3020 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
3021 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
3022 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
3023 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
3024 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
3025 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
3026 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
3027 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
3028 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
3029 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
3030 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
3031 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
3033 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");