MDL-50791 forms: make server validation errors accessible
[moodle.git] / lib / formslib.php
blobfa773bd74d14f612ec5fd1b24a87335ed5b182d8
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 $module = 'moodle-form-dateselector';
81 $function = 'M.form.dateselector.init_date_selectors';
82 $config = array(array(
83 'firstdayofweek' => get_string('firstdayofweek', 'langconfig'),
84 'mon' => date_format_string(strtotime("Monday"), '%a', 99),
85 'tue' => date_format_string(strtotime("Tuesday"), '%a', 99),
86 'wed' => date_format_string(strtotime("Wednesday"), '%a', 99),
87 'thu' => date_format_string(strtotime("Thursday"), '%a', 99),
88 'fri' => date_format_string(strtotime("Friday"), '%a', 99),
89 'sat' => date_format_string(strtotime("Saturday"), '%a', 99),
90 'sun' => date_format_string(strtotime("Sunday"), '%a', 99),
91 'january' => date_format_string(strtotime("January 1"), '%B', 99),
92 'february' => date_format_string(strtotime("February 1"), '%B', 99),
93 'march' => date_format_string(strtotime("March 1"), '%B', 99),
94 'april' => date_format_string(strtotime("April 1"), '%B', 99),
95 'may' => date_format_string(strtotime("May 1"), '%B', 99),
96 'june' => date_format_string(strtotime("June 1"), '%B', 99),
97 'july' => date_format_string(strtotime("July 1"), '%B', 99),
98 'august' => date_format_string(strtotime("August 1"), '%B', 99),
99 'september' => date_format_string(strtotime("September 1"), '%B', 99),
100 'october' => date_format_string(strtotime("October 1"), '%B', 99),
101 'november' => date_format_string(strtotime("November 1"), '%B', 99),
102 'december' => date_format_string(strtotime("December 1"), '%B', 99)
104 $PAGE->requires->yui_module($module, $function, $config);
105 $done = true;
110 * Wrapper that separates quickforms syntax from moodle code
112 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
113 * use this class you should write a class definition which extends this class or a more specific
114 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
116 * You will write your own definition() method which performs the form set up.
118 * @package core_form
119 * @copyright 2006 Jamie Pratt <me@jamiep.org>
120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
121 * @todo MDL-19380 rethink the file scanning
123 abstract class moodleform {
124 /** @var string name of the form */
125 protected $_formname; // form name
127 /** @var MoodleQuickForm quickform object definition */
128 protected $_form;
130 /** @var array globals workaround */
131 protected $_customdata;
133 /** @var object definition_after_data executed flag */
134 protected $_definition_finalized = false;
137 * The constructor function calls the abstract function definition() and it will then
138 * process and clean and attempt to validate incoming data.
140 * It will call your custom validate method to validate data and will also check any rules
141 * you have specified in definition using addRule
143 * The name of the form (id attribute of the form) is automatically generated depending on
144 * the name you gave the class extending moodleform. You should call your class something
145 * like
147 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
148 * current url. If a moodle_url object then outputs params as hidden variables.
149 * @param mixed $customdata if your form defintion method needs access to data such as $course
150 * $cm, etc. to construct the form definition then pass it in this array. You can
151 * use globals for somethings.
152 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
153 * be merged and used as incoming data to the form.
154 * @param string $target target frame for form submission. You will rarely use this. Don't use
155 * it if you don't need to as the target attribute is deprecated in xhtml strict.
156 * @param mixed $attributes you can pass a string of html attributes here or an array.
157 * @param bool $editable
159 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
160 global $CFG, $FULLME;
161 // no standard mform in moodle should allow autocomplete with the exception of user signup
162 if (empty($attributes)) {
163 $attributes = array('autocomplete'=>'off');
164 } else if (is_array($attributes)) {
165 $attributes['autocomplete'] = 'off';
166 } else {
167 if (strpos($attributes, 'autocomplete') === false) {
168 $attributes .= ' autocomplete="off" ';
172 if (empty($action)){
173 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
174 $action = strip_querystring($FULLME);
175 if (!empty($CFG->sslproxy)) {
176 // return only https links when using SSL proxy
177 $action = preg_replace('/^http:/', 'https:', $action, 1);
179 //TODO: use following instead of FULLME - see MDL-33015
180 //$action = strip_querystring(qualified_me());
182 // Assign custom data first, so that get_form_identifier can use it.
183 $this->_customdata = $customdata;
184 $this->_formname = $this->get_form_identifier();
186 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
187 if (!$editable){
188 $this->_form->hardFreeze();
191 // HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
192 $element = $this->_form->addElement('hidden');
193 $element->setType('password');
195 $this->definition();
197 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
198 $this->_form->setType('sesskey', PARAM_RAW);
199 $this->_form->setDefault('sesskey', sesskey());
200 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
201 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
202 $this->_form->setDefault('_qf__'.$this->_formname, 1);
203 $this->_form->_setDefaultRuleMessages();
205 // we have to know all input types before processing submission ;-)
206 $this->_process_submission($method);
210 * It should returns unique identifier for the form.
211 * Currently it will return class name, but in case two same forms have to be
212 * rendered on same page then override function to get unique form identifier.
213 * e.g This is used on multiple self enrollments page.
215 * @return string form identifier.
217 protected function get_form_identifier() {
218 $class = get_class($this);
220 return preg_replace('/[^a-z0-9_]/i', '_', $class);
224 * To autofocus on first form element or first element with error.
226 * @param string $name if this is set then the focus is forced to a field with this name
227 * @return string javascript to select form element with first error or
228 * first element if no errors. Use this as a parameter
229 * when calling print_header
231 function focus($name=NULL) {
232 $form =& $this->_form;
233 $elkeys = array_keys($form->_elementIndex);
234 $error = false;
235 if (isset($form->_errors) && 0 != count($form->_errors)){
236 $errorkeys = array_keys($form->_errors);
237 $elkeys = array_intersect($elkeys, $errorkeys);
238 $error = true;
241 if ($error or empty($name)) {
242 $names = array();
243 while (empty($names) and !empty($elkeys)) {
244 $el = array_shift($elkeys);
245 $names = $form->_getElNamesRecursive($el);
247 if (!empty($names)) {
248 $name = array_shift($names);
252 $focus = '';
253 if (!empty($name)) {
254 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
257 return $focus;
261 * Internal method. Alters submitted data to be suitable for quickforms processing.
262 * Must be called when the form is fully set up.
264 * @param string $method name of the method which alters submitted data
266 function _process_submission($method) {
267 $submission = array();
268 if ($method == 'post') {
269 if (!empty($_POST)) {
270 $submission = $_POST;
272 } else {
273 $submission = $_GET;
274 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
277 // following trick is needed to enable proper sesskey checks when using GET forms
278 // the _qf__.$this->_formname serves as a marker that form was actually submitted
279 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
280 if (!confirm_sesskey()) {
281 print_error('invalidsesskey');
283 $files = $_FILES;
284 } else {
285 $submission = array();
286 $files = array();
288 $this->detectMissingSetType();
290 $this->_form->updateSubmission($submission, $files);
294 * Internal method - should not be used anywhere.
295 * @deprecated since 2.6
296 * @return array $_POST.
298 protected function _get_post_params() {
299 return $_POST;
303 * Internal method. Validates all old-style deprecated uploaded files.
304 * The new way is to upload files via repository api.
306 * @param array $files list of files to be validated
307 * @return bool|array Success or an array of errors
309 function _validate_files(&$files) {
310 global $CFG, $COURSE;
312 $files = array();
314 if (empty($_FILES)) {
315 // we do not need to do any checks because no files were submitted
316 // note: server side rules do not work for files - use custom verification in validate() instead
317 return true;
320 $errors = array();
321 $filenames = array();
323 // now check that we really want each file
324 foreach ($_FILES as $elname=>$file) {
325 $required = $this->_form->isElementRequired($elname);
327 if ($file['error'] == 4 and $file['size'] == 0) {
328 if ($required) {
329 $errors[$elname] = get_string('required');
331 unset($_FILES[$elname]);
332 continue;
335 if (!empty($file['error'])) {
336 $errors[$elname] = file_get_upload_error($file['error']);
337 unset($_FILES[$elname]);
338 continue;
341 if (!is_uploaded_file($file['tmp_name'])) {
342 // TODO: improve error message
343 $errors[$elname] = get_string('error');
344 unset($_FILES[$elname]);
345 continue;
348 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
349 // hmm, this file was not requested
350 unset($_FILES[$elname]);
351 continue;
354 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
356 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
357 if ($filename === '') {
358 // TODO: improve error message - wrong chars
359 $errors[$elname] = get_string('error');
360 unset($_FILES[$elname]);
361 continue;
363 if (in_array($filename, $filenames)) {
364 // TODO: improve error message - duplicate name
365 $errors[$elname] = get_string('error');
366 unset($_FILES[$elname]);
367 continue;
369 $filenames[] = $filename;
370 $_FILES[$elname]['name'] = $filename;
372 $files[$elname] = $_FILES[$elname]['tmp_name'];
375 // return errors if found
376 if (count($errors) == 0){
377 return true;
379 } else {
380 $files = array();
381 return $errors;
386 * Internal method. Validates filepicker and filemanager files if they are
387 * set as required fields. Also, sets the error message if encountered one.
389 * @return bool|array with errors
391 protected function validate_draft_files() {
392 global $USER;
393 $mform =& $this->_form;
395 $errors = array();
396 //Go through all the required elements and make sure you hit filepicker or
397 //filemanager element.
398 foreach ($mform->_rules as $elementname => $rules) {
399 $elementtype = $mform->getElementType($elementname);
400 //If element is of type filepicker then do validation
401 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
402 //Check if rule defined is required rule
403 foreach ($rules as $rule) {
404 if ($rule['type'] == 'required') {
405 $draftid = (int)$mform->getSubmitValue($elementname);
406 $fs = get_file_storage();
407 $context = context_user::instance($USER->id);
408 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
409 $errors[$elementname] = $rule['message'];
415 // Check all the filemanager elements to make sure they do not have too many
416 // files in them.
417 foreach ($mform->_elements as $element) {
418 if ($element->_type == 'filemanager') {
419 $maxfiles = $element->getMaxfiles();
420 if ($maxfiles > 0) {
421 $draftid = (int)$element->getValue();
422 $fs = get_file_storage();
423 $context = context_user::instance($USER->id);
424 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
425 if (count($files) > $maxfiles) {
426 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
431 if (empty($errors)) {
432 return true;
433 } else {
434 return $errors;
439 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
440 * form definition (new entry form); this function is used to load in data where values
441 * already exist and data is being edited (edit entry form).
443 * note: $slashed param removed
445 * @param stdClass|array $default_values object or array of default values
447 function set_data($default_values) {
448 if (is_object($default_values)) {
449 $default_values = (array)$default_values;
451 $this->_form->setDefaults($default_values);
455 * Check that form was submitted. Does not check validity of submitted data.
457 * @return bool true if form properly submitted
459 function is_submitted() {
460 return $this->_form->isSubmitted();
464 * Checks if button pressed is not for submitting the form
466 * @staticvar bool $nosubmit keeps track of no submit button
467 * @return bool
469 function no_submit_button_pressed(){
470 static $nosubmit = null; // one check is enough
471 if (!is_null($nosubmit)){
472 return $nosubmit;
474 $mform =& $this->_form;
475 $nosubmit = false;
476 if (!$this->is_submitted()){
477 return false;
479 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
480 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
481 $nosubmit = true;
482 break;
485 return $nosubmit;
490 * Check that form data is valid.
491 * You should almost always use this, rather than {@link validate_defined_fields}
493 * @return bool true if form data valid
495 function is_validated() {
496 //finalize the form definition before any processing
497 if (!$this->_definition_finalized) {
498 $this->_definition_finalized = true;
499 $this->definition_after_data();
502 return $this->validate_defined_fields();
506 * Validate the form.
508 * You almost always want to call {@link is_validated} instead of this
509 * because it calls {@link definition_after_data} first, before validating the form,
510 * which is what you want in 99% of cases.
512 * This is provided as a separate function for those special cases where
513 * you want the form validated before definition_after_data is called
514 * for example, to selectively add new elements depending on a no_submit_button press,
515 * but only when the form is valid when the no_submit_button is pressed,
517 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
518 * is NOT to validate the form when a no submit button has been pressed.
519 * pass true here to override this behaviour
521 * @return bool true if form data valid
523 function validate_defined_fields($validateonnosubmit=false) {
524 static $validated = null; // one validation is enough
525 $mform =& $this->_form;
526 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
527 return false;
528 } elseif ($validated === null) {
529 $internal_val = $mform->validate();
531 $files = array();
532 $file_val = $this->_validate_files($files);
533 //check draft files for validation and flag them if required files
534 //are not in draft area.
535 $draftfilevalue = $this->validate_draft_files();
537 if ($file_val !== true && $draftfilevalue !== true) {
538 $file_val = array_merge($file_val, $draftfilevalue);
539 } else if ($draftfilevalue !== true) {
540 $file_val = $draftfilevalue;
541 } //default is file_val, so no need to assign.
543 if ($file_val !== true) {
544 if (!empty($file_val)) {
545 foreach ($file_val as $element=>$msg) {
546 $mform->setElementError($element, $msg);
549 $file_val = false;
552 $data = $mform->exportValues();
553 $moodle_val = $this->validation($data, $files);
554 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
555 // non-empty array means errors
556 foreach ($moodle_val as $element=>$msg) {
557 $mform->setElementError($element, $msg);
559 $moodle_val = false;
561 } else {
562 // anything else means validation ok
563 $moodle_val = true;
566 $validated = ($internal_val and $moodle_val and $file_val);
568 return $validated;
572 * Return true if a cancel button has been pressed resulting in the form being submitted.
574 * @return bool true if a cancel button has been pressed
576 function is_cancelled(){
577 $mform =& $this->_form;
578 if ($mform->isSubmitted()){
579 foreach ($mform->_cancelButtons as $cancelbutton){
580 if (optional_param($cancelbutton, 0, PARAM_RAW)){
581 return true;
585 return false;
589 * Return submitted data if properly submitted or returns NULL if validation fails or
590 * if there is no submitted data.
592 * note: $slashed param removed
594 * @return object submitted data; NULL if not valid or not submitted or cancelled
596 function get_data() {
597 $mform =& $this->_form;
599 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
600 $data = $mform->exportValues();
601 unset($data['sesskey']); // we do not need to return sesskey
602 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
603 if (empty($data)) {
604 return NULL;
605 } else {
606 return (object)$data;
608 } else {
609 return NULL;
614 * Return submitted data without validation or NULL if there is no submitted data.
615 * note: $slashed param removed
617 * @return object submitted data; NULL if not submitted
619 function get_submitted_data() {
620 $mform =& $this->_form;
622 if ($this->is_submitted()) {
623 $data = $mform->exportValues();
624 unset($data['sesskey']); // we do not need to return sesskey
625 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
626 if (empty($data)) {
627 return NULL;
628 } else {
629 return (object)$data;
631 } else {
632 return NULL;
637 * Save verified uploaded files into directory. Upload process can be customised from definition()
639 * @deprecated since Moodle 2.0
640 * @todo MDL-31294 remove this api
641 * @see moodleform::save_stored_file()
642 * @see moodleform::save_file()
643 * @param string $destination path where file should be stored
644 * @return bool Always false
646 function save_files($destination) {
647 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
648 return false;
652 * Returns name of uploaded file.
654 * @param string $elname first element if null
655 * @return string|bool false in case of failure, string if ok
657 function get_new_filename($elname=null) {
658 global $USER;
660 if (!$this->is_submitted() or !$this->is_validated()) {
661 return false;
664 if (is_null($elname)) {
665 if (empty($_FILES)) {
666 return false;
668 reset($_FILES);
669 $elname = key($_FILES);
672 if (empty($elname)) {
673 return false;
676 $element = $this->_form->getElement($elname);
678 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
679 $values = $this->_form->exportValues($elname);
680 if (empty($values[$elname])) {
681 return false;
683 $draftid = $values[$elname];
684 $fs = get_file_storage();
685 $context = context_user::instance($USER->id);
686 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
687 return false;
689 $file = reset($files);
690 return $file->get_filename();
693 if (!isset($_FILES[$elname])) {
694 return false;
697 return $_FILES[$elname]['name'];
701 * Save file to standard filesystem
703 * @param string $elname name of element
704 * @param string $pathname full path name of file
705 * @param bool $override override file if exists
706 * @return bool success
708 function save_file($elname, $pathname, $override=false) {
709 global $USER;
711 if (!$this->is_submitted() or !$this->is_validated()) {
712 return false;
714 if (file_exists($pathname)) {
715 if ($override) {
716 if (!@unlink($pathname)) {
717 return false;
719 } else {
720 return false;
724 $element = $this->_form->getElement($elname);
726 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
727 $values = $this->_form->exportValues($elname);
728 if (empty($values[$elname])) {
729 return false;
731 $draftid = $values[$elname];
732 $fs = get_file_storage();
733 $context = context_user::instance($USER->id);
734 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
735 return false;
737 $file = reset($files);
739 return $file->copy_content_to($pathname);
741 } else if (isset($_FILES[$elname])) {
742 return copy($_FILES[$elname]['tmp_name'], $pathname);
745 return false;
749 * Returns a temporary file, do not forget to delete after not needed any more.
751 * @param string $elname name of the elmenet
752 * @return string|bool either string or false
754 function save_temp_file($elname) {
755 if (!$this->get_new_filename($elname)) {
756 return false;
758 if (!$dir = make_temp_directory('forms')) {
759 return false;
761 if (!$tempfile = tempnam($dir, 'tempup_')) {
762 return false;
764 if (!$this->save_file($elname, $tempfile, true)) {
765 // something went wrong
766 @unlink($tempfile);
767 return false;
770 return $tempfile;
774 * Get draft files of a form element
775 * This is a protected method which will be used only inside moodleforms
777 * @param string $elname name of element
778 * @return array|bool|null
780 protected function get_draft_files($elname) {
781 global $USER;
783 if (!$this->is_submitted()) {
784 return false;
787 $element = $this->_form->getElement($elname);
789 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
790 $values = $this->_form->exportValues($elname);
791 if (empty($values[$elname])) {
792 return false;
794 $draftid = $values[$elname];
795 $fs = get_file_storage();
796 $context = context_user::instance($USER->id);
797 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
798 return null;
800 return $files;
802 return null;
806 * Save file to local filesystem pool
808 * @param string $elname name of element
809 * @param int $newcontextid id of context
810 * @param string $newcomponent name of the component
811 * @param string $newfilearea name of file area
812 * @param int $newitemid item id
813 * @param string $newfilepath path of file where it get stored
814 * @param string $newfilename use specified filename, if not specified name of uploaded file used
815 * @param bool $overwrite overwrite file if exists
816 * @param int $newuserid new userid if required
817 * @return mixed stored_file object or false if error; may throw exception if duplicate found
819 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
820 $newfilename=null, $overwrite=false, $newuserid=null) {
821 global $USER;
823 if (!$this->is_submitted() or !$this->is_validated()) {
824 return false;
827 if (empty($newuserid)) {
828 $newuserid = $USER->id;
831 $element = $this->_form->getElement($elname);
832 $fs = get_file_storage();
834 if ($element instanceof MoodleQuickForm_filepicker) {
835 $values = $this->_form->exportValues($elname);
836 if (empty($values[$elname])) {
837 return false;
839 $draftid = $values[$elname];
840 $context = context_user::instance($USER->id);
841 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
842 return false;
844 $file = reset($files);
845 if (is_null($newfilename)) {
846 $newfilename = $file->get_filename();
849 if ($overwrite) {
850 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
851 if (!$oldfile->delete()) {
852 return false;
857 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
858 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
859 return $fs->create_file_from_storedfile($file_record, $file);
861 } else if (isset($_FILES[$elname])) {
862 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
864 if ($overwrite) {
865 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
866 if (!$oldfile->delete()) {
867 return false;
872 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
873 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
874 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
877 return false;
881 * Get content of uploaded file.
883 * @param string $elname name of file upload element
884 * @return string|bool false in case of failure, string if ok
886 function get_file_content($elname) {
887 global $USER;
889 if (!$this->is_submitted() or !$this->is_validated()) {
890 return false;
893 $element = $this->_form->getElement($elname);
895 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
896 $values = $this->_form->exportValues($elname);
897 if (empty($values[$elname])) {
898 return false;
900 $draftid = $values[$elname];
901 $fs = get_file_storage();
902 $context = context_user::instance($USER->id);
903 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
904 return false;
906 $file = reset($files);
908 return $file->get_content();
910 } else if (isset($_FILES[$elname])) {
911 return file_get_contents($_FILES[$elname]['tmp_name']);
914 return false;
918 * Print html form.
920 function display() {
921 //finalize the form definition if not yet done
922 if (!$this->_definition_finalized) {
923 $this->_definition_finalized = true;
924 $this->definition_after_data();
927 $this->_form->display();
931 * Renders the html form (same as display, but returns the result).
933 * Note that you can only output this rendered result once per page, as
934 * it contains IDs which must be unique.
936 * @return string HTML code for the form
938 public function render() {
939 ob_start();
940 $this->display();
941 $out = ob_get_contents();
942 ob_end_clean();
943 return $out;
947 * Form definition. Abstract method - always override!
949 protected abstract function definition();
952 * Dummy stub method - override if you need to setup the form depending on current
953 * values. This method is called after definition(), data submission and set_data().
954 * All form setup that is dependent on form values should go in here.
956 function definition_after_data(){
960 * Dummy stub method - override if you needed to perform some extra validation.
961 * If there are errors return array of errors ("fieldname"=>"error message"),
962 * otherwise true if ok.
964 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
966 * @param array $data array of ("fieldname"=>value) of submitted data
967 * @param array $files array of uploaded files "element_name"=>tmp_file_path
968 * @return array of "element_name"=>"error_description" if there are errors,
969 * or an empty array if everything is OK (true allowed for backwards compatibility too).
971 function validation($data, $files) {
972 return array();
976 * Helper used by {@link repeat_elements()}.
978 * @param int $i the index of this element.
979 * @param HTML_QuickForm_element $elementclone
980 * @param array $namecloned array of names
982 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
983 $name = $elementclone->getName();
984 $namecloned[] = $name;
986 if (!empty($name)) {
987 $elementclone->setName($name."[$i]");
990 if (is_a($elementclone, 'HTML_QuickForm_header')) {
991 $value = $elementclone->_text;
992 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
994 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
995 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
997 } else {
998 $value=$elementclone->getLabel();
999 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1004 * Method to add a repeating group of elements to a form.
1006 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1007 * @param int $repeats no of times to repeat elements initially
1008 * @param array $options a nested array. The first array key is the element name.
1009 * the second array key is the type of option to set, and depend on that option,
1010 * the value takes different forms.
1011 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1012 * 'type' - PARAM_* type.
1013 * 'helpbutton' - array containing the helpbutton params.
1014 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1015 * 'rule' - array containing the addRule arguments after the element name.
1016 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1017 * 'advanced' - whether this element is hidden by 'Show more ...'.
1018 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1019 * @param string $addfieldsname name for button to add more fields
1020 * @param int $addfieldsno how many fields to add at a time
1021 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1022 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1023 * @return int no of repeats of element in this page
1025 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1026 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1027 if ($addstring===null){
1028 $addstring = get_string('addfields', 'form', $addfieldsno);
1029 } else {
1030 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1032 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1033 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1034 if (!empty($addfields)){
1035 $repeats += $addfieldsno;
1037 $mform =& $this->_form;
1038 $mform->registerNoSubmitButton($addfieldsname);
1039 $mform->addElement('hidden', $repeathiddenname, $repeats);
1040 $mform->setType($repeathiddenname, PARAM_INT);
1041 //value not to be overridden by submitted value
1042 $mform->setConstants(array($repeathiddenname=>$repeats));
1043 $namecloned = array();
1044 for ($i = 0; $i < $repeats; $i++) {
1045 foreach ($elementobjs as $elementobj){
1046 $elementclone = fullclone($elementobj);
1047 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1049 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1050 foreach ($elementclone->getElements() as $el) {
1051 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1053 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1056 $mform->addElement($elementclone);
1059 for ($i=0; $i<$repeats; $i++) {
1060 foreach ($options as $elementname => $elementoptions){
1061 $pos=strpos($elementname, '[');
1062 if ($pos!==FALSE){
1063 $realelementname = substr($elementname, 0, $pos)."[$i]";
1064 $realelementname .= substr($elementname, $pos);
1065 }else {
1066 $realelementname = $elementname."[$i]";
1068 foreach ($elementoptions as $option => $params){
1070 switch ($option){
1071 case 'default' :
1072 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1073 break;
1074 case 'helpbutton' :
1075 $params = array_merge(array($realelementname), $params);
1076 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1077 break;
1078 case 'disabledif' :
1079 foreach ($namecloned as $num => $name){
1080 if ($params[0] == $name){
1081 $params[0] = $params[0]."[$i]";
1082 break;
1085 $params = array_merge(array($realelementname), $params);
1086 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1087 break;
1088 case 'rule' :
1089 if (is_string($params)){
1090 $params = array(null, $params, null, 'client');
1092 $params = array_merge(array($realelementname), $params);
1093 call_user_func_array(array(&$mform, 'addRule'), $params);
1094 break;
1096 case 'type':
1097 $mform->setType($realelementname, $params);
1098 break;
1100 case 'expanded':
1101 $mform->setExpanded($realelementname, $params);
1102 break;
1104 case 'advanced' :
1105 $mform->setAdvanced($realelementname, $params);
1106 break;
1111 $mform->addElement('submit', $addfieldsname, $addstring);
1113 if (!$addbuttoninside) {
1114 $mform->closeHeaderBefore($addfieldsname);
1117 return $repeats;
1121 * Adds a link/button that controls the checked state of a group of checkboxes.
1123 * @param int $groupid The id of the group of advcheckboxes this element controls
1124 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1125 * @param array $attributes associative array of HTML attributes
1126 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1128 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1129 global $CFG, $PAGE;
1131 // Name of the controller button
1132 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1133 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1134 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1136 // Set the default text if none was specified
1137 if (empty($text)) {
1138 $text = get_string('selectallornone', 'form');
1141 $mform = $this->_form;
1142 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1143 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1145 $newselectvalue = $selectvalue;
1146 if (is_null($selectvalue)) {
1147 $newselectvalue = $originalValue;
1148 } else if (!is_null($contollerbutton)) {
1149 $newselectvalue = (int) !$selectvalue;
1151 // set checkbox state depending on orignal/submitted value by controoler button
1152 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1153 foreach ($mform->_elements as $element) {
1154 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1155 $element->getAttribute('class') == $checkboxgroupclass &&
1156 !$element->isFrozen()) {
1157 $mform->setConstants(array($element->getName() => $newselectvalue));
1162 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1163 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1164 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1166 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1167 array(
1168 array('groupid' => $groupid,
1169 'checkboxclass' => $checkboxgroupclass,
1170 'checkboxcontroller' => $checkboxcontrollerparam,
1171 'controllerbutton' => $checkboxcontrollername)
1175 require_once("$CFG->libdir/form/submit.php");
1176 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1177 $mform->addElement($submitlink);
1178 $mform->registerNoSubmitButton($checkboxcontrollername);
1179 $mform->setDefault($checkboxcontrollername, $text);
1183 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1184 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1185 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1186 * get data with get_data().
1188 * @param bool $cancel whether to show cancel button, default true
1189 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1191 function add_action_buttons($cancel = true, $submitlabel=null){
1192 if (is_null($submitlabel)){
1193 $submitlabel = get_string('savechanges');
1195 $mform =& $this->_form;
1196 if ($cancel){
1197 //when two elements we need a group
1198 $buttonarray=array();
1199 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1200 $buttonarray[] = &$mform->createElement('cancel');
1201 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1202 $mform->closeHeaderBefore('buttonar');
1203 } else {
1204 //no group needed
1205 $mform->addElement('submit', 'submitbutton', $submitlabel);
1206 $mform->closeHeaderBefore('submitbutton');
1211 * Adds an initialisation call for a standard JavaScript enhancement.
1213 * This function is designed to add an initialisation call for a JavaScript
1214 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1216 * Current options:
1217 * - Selectboxes
1218 * - smartselect: Turns a nbsp indented select box into a custom drop down
1219 * control that supports multilevel and category selection.
1220 * $enhancement = 'smartselect';
1221 * $options = array('selectablecategories' => true|false)
1223 * @since Moodle 2.0
1224 * @param string|element $element form element for which Javascript needs to be initalized
1225 * @param string $enhancement which init function should be called
1226 * @param array $options options passed to javascript
1227 * @param array $strings strings for javascript
1229 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1230 global $PAGE;
1231 if (is_string($element)) {
1232 $element = $this->_form->getElement($element);
1234 if (is_object($element)) {
1235 $element->_generateId();
1236 $elementid = $element->getAttribute('id');
1237 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1238 if (is_array($strings)) {
1239 foreach ($strings as $string) {
1240 if (is_array($string)) {
1241 call_user_method_array('string_for_js', $PAGE->requires, $string);
1242 } else {
1243 $PAGE->requires->string_for_js($string, 'moodle');
1251 * Returns a JS module definition for the mforms JS
1253 * @return array
1255 public static function get_js_module() {
1256 global $CFG;
1257 return array(
1258 'name' => 'mform',
1259 'fullpath' => '/lib/form/form.js',
1260 'requires' => array('base', 'node')
1265 * Detects elements with missing setType() declerations.
1267 * Finds elements in the form which should a PARAM_ type set and throws a
1268 * developer debug warning for any elements without it. This is to reduce the
1269 * risk of potential security issues by developers mistakenly forgetting to set
1270 * the type.
1272 * @return void
1274 private function detectMissingSetType() {
1275 global $CFG;
1277 if (!$CFG->debugdeveloper) {
1278 // Only for devs.
1279 return;
1282 $mform = $this->_form;
1283 foreach ($mform->_elements as $element) {
1284 $group = false;
1285 $elements = array($element);
1287 if ($element->getType() == 'group') {
1288 $group = $element;
1289 $elements = $element->getElements();
1292 foreach ($elements as $index => $element) {
1293 switch ($element->getType()) {
1294 case 'hidden':
1295 case 'text':
1296 case 'url':
1297 if ($group) {
1298 $name = $group->getElementName($index);
1299 } else {
1300 $name = $element->getName();
1302 $key = $name;
1303 $found = array_key_exists($key, $mform->_types);
1304 // For repeated elements we need to look for
1305 // the "main" type, not for the one present
1306 // on each repetition. All the stuff in formslib
1307 // (repeat_elements(), updateSubmission()... seems
1308 // to work that way.
1309 while (!$found && strrpos($key, '[') !== false) {
1310 $pos = strrpos($key, '[');
1311 $key = substr($key, 0, $pos);
1312 $found = array_key_exists($key, $mform->_types);
1314 if (!$found) {
1315 debugging("Did you remember to call setType() for '$name'? ".
1316 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1318 break;
1325 * Used by tests to simulate submitted form data submission from the user.
1327 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1328 * get_data.
1330 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1331 * global arrays after each test.
1333 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1334 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1335 * @param string $method 'post' or 'get', defaults to 'post'.
1336 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1337 * a different value here for some forms that are used more than once on the
1338 * same page.
1340 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1341 $formidentifier = null) {
1342 $_FILES = $simulatedsubmittedfiles;
1343 if ($formidentifier === null) {
1344 $formidentifier = get_called_class();
1346 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1347 $simulatedsubmitteddata['sesskey'] = sesskey();
1348 if (strtolower($method) === 'get') {
1349 $_GET = $simulatedsubmitteddata;
1350 } else {
1351 $_POST = $simulatedsubmitteddata;
1357 * MoodleQuickForm implementation
1359 * You never extend this class directly. The class methods of this class are available from
1360 * the private $this->_form property on moodleform and its children. You generally only
1361 * call methods on this class from within abstract methods that you override on moodleform such
1362 * as definition and definition_after_data
1364 * @package core_form
1365 * @category form
1366 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1367 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1369 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1370 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1371 var $_types = array();
1373 /** @var array dependent state for the element/'s */
1374 var $_dependencies = array();
1376 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1377 var $_noSubmitButtons=array();
1379 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1380 var $_cancelButtons=array();
1382 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1383 var $_advancedElements = array();
1386 * Array whose keys are element names and values are the desired collapsible state.
1387 * True for collapsed, False for expanded. If not present, set to default in
1388 * {@link self::accept()}.
1390 * @var array
1392 var $_collapsibleElements = array();
1395 * Whether to enable shortforms for this form
1397 * @var boolean
1399 var $_disableShortforms = false;
1401 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1402 protected $_use_form_change_checker = true;
1405 * The form name is derived from the class name of the wrapper minus the trailing form
1406 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1407 * @var string
1409 var $_formName = '';
1412 * String with the html for hidden params passed in as part of a moodle_url
1413 * object for the action. Output in the form.
1414 * @var string
1416 var $_pageparams = '';
1419 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1421 * @staticvar int $formcounter counts number of forms
1422 * @param string $formName Form's name.
1423 * @param string $method Form's method defaults to 'POST'
1424 * @param string|moodle_url $action Form's action
1425 * @param string $target (optional)Form's target defaults to none
1426 * @param mixed $attributes (optional)Extra attributes for <form> tag
1428 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1429 global $CFG, $OUTPUT;
1431 static $formcounter = 1;
1433 HTML_Common::HTML_Common($attributes);
1434 $target = empty($target) ? array() : array('target' => $target);
1435 $this->_formName = $formName;
1436 if (is_a($action, 'moodle_url')){
1437 $this->_pageparams = html_writer::input_hidden_params($action);
1438 $action = $action->out_omit_querystring();
1439 } else {
1440 $this->_pageparams = '';
1442 // No 'name' atttribute for form in xhtml strict :
1443 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1444 if (is_null($this->getAttribute('id'))) {
1445 $attributes['id'] = 'mform' . $formcounter;
1447 $formcounter++;
1448 $this->updateAttributes($attributes);
1450 // This is custom stuff for Moodle :
1451 $oldclass= $this->getAttribute('class');
1452 if (!empty($oldclass)){
1453 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1454 }else {
1455 $this->updateAttributes(array('class'=>'mform'));
1457 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1458 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1459 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1463 * Use this method to indicate an element in a form is an advanced field. If items in a form
1464 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1465 * form so the user can decide whether to display advanced form controls.
1467 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1469 * @param string $elementName group or element name (not the element name of something inside a group).
1470 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1472 function setAdvanced($elementName, $advanced = true) {
1473 if ($advanced){
1474 $this->_advancedElements[$elementName]='';
1475 } elseif (isset($this->_advancedElements[$elementName])) {
1476 unset($this->_advancedElements[$elementName]);
1481 * Use this method to indicate that the fieldset should be shown as expanded.
1482 * The method is applicable to header elements only.
1484 * @param string $headername header element name
1485 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1486 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1487 * the form was submitted.
1488 * @return void
1490 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1491 if (empty($headername)) {
1492 return;
1494 $element = $this->getElement($headername);
1495 if ($element->getType() != 'header') {
1496 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1497 return;
1499 if (!$headerid = $element->getAttribute('id')) {
1500 $element->_generateId();
1501 $headerid = $element->getAttribute('id');
1503 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1504 // See if the form has been submitted already.
1505 $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1506 if (!$ignoreuserstate && $formexpanded != -1) {
1507 // Override expanded state with the form variable.
1508 $expanded = $formexpanded;
1510 // Create the form element for storing expanded state.
1511 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1512 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1513 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1515 $this->_collapsibleElements[$headername] = !$expanded;
1519 * Use this method to add show more/less status element required for passing
1520 * over the advanced elements visibility status on the form submission.
1522 * @param string $headerName header element name.
1523 * @param boolean $showmore default false sets the advanced elements to be hidden.
1525 function addAdvancedStatusElement($headerid, $showmore=false){
1526 // Add extra hidden element to store advanced items state for each section.
1527 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1528 // See if we the form has been submitted already.
1529 $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1530 if (!$showmore && $formshowmore != -1) {
1531 // Override showmore state with the form variable.
1532 $showmore = $formshowmore;
1534 // Create the form element for storing advanced items state.
1535 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1536 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1537 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1542 * This function has been deprecated. Show advanced has been replaced by
1543 * "Show more.../Show less..." in the shortforms javascript module.
1545 * @deprecated since Moodle 2.5
1546 * @param bool $showadvancedNow if true will show advanced elements.
1548 function setShowAdvanced($showadvancedNow = null){
1549 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1553 * This function has been deprecated. Show advanced has been replaced by
1554 * "Show more.../Show less..." in the shortforms javascript module.
1556 * @deprecated since Moodle 2.5
1557 * @return bool (Always false)
1559 function getShowAdvanced(){
1560 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1561 return false;
1565 * Use this method to indicate that the form will not be using shortforms.
1567 * @param boolean $disable default true, controls if the shortforms are disabled.
1569 function setDisableShortforms ($disable = true) {
1570 $this->_disableShortforms = $disable;
1574 * Call this method if you don't want the formchangechecker JavaScript to be
1575 * automatically initialised for this form.
1577 public function disable_form_change_checker() {
1578 $this->_use_form_change_checker = false;
1582 * If you have called {@link disable_form_change_checker()} then you can use
1583 * this method to re-enable it. It is enabled by default, so normally you don't
1584 * need to call this.
1586 public function enable_form_change_checker() {
1587 $this->_use_form_change_checker = true;
1591 * @return bool whether this form should automatically initialise
1592 * formchangechecker for itself.
1594 public function is_form_change_checker_enabled() {
1595 return $this->_use_form_change_checker;
1599 * Accepts a renderer
1601 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1603 function accept(&$renderer) {
1604 if (method_exists($renderer, 'setAdvancedElements')){
1605 //Check for visible fieldsets where all elements are advanced
1606 //and mark these headers as advanced as well.
1607 //Also mark all elements in a advanced header as advanced.
1608 $stopFields = $renderer->getStopFieldSetElements();
1609 $lastHeader = null;
1610 $lastHeaderAdvanced = false;
1611 $anyAdvanced = false;
1612 $anyError = false;
1613 foreach (array_keys($this->_elements) as $elementIndex){
1614 $element =& $this->_elements[$elementIndex];
1616 // if closing header and any contained element was advanced then mark it as advanced
1617 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1618 if ($anyAdvanced && !is_null($lastHeader)) {
1619 $lastHeader->_generateId();
1620 $this->setAdvanced($lastHeader->getName());
1621 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1623 $lastHeaderAdvanced = false;
1624 unset($lastHeader);
1625 $lastHeader = null;
1626 } elseif ($lastHeaderAdvanced) {
1627 $this->setAdvanced($element->getName());
1630 if ($element->getType()=='header'){
1631 $lastHeader =& $element;
1632 $anyAdvanced = false;
1633 $anyError = false;
1634 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1635 } elseif (isset($this->_advancedElements[$element->getName()])){
1636 $anyAdvanced = true;
1637 if (isset($this->_errors[$element->getName()])) {
1638 $anyError = true;
1642 // the last header may not be closed yet...
1643 if ($anyAdvanced && !is_null($lastHeader)){
1644 $this->setAdvanced($lastHeader->getName());
1645 $lastHeader->_generateId();
1646 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1648 $renderer->setAdvancedElements($this->_advancedElements);
1650 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1652 // Count the number of sections.
1653 $headerscount = 0;
1654 foreach (array_keys($this->_elements) as $elementIndex){
1655 $element =& $this->_elements[$elementIndex];
1656 if ($element->getType() == 'header') {
1657 $headerscount++;
1661 $anyrequiredorerror = false;
1662 $headercounter = 0;
1663 $headername = null;
1664 foreach (array_keys($this->_elements) as $elementIndex){
1665 $element =& $this->_elements[$elementIndex];
1667 if ($element->getType() == 'header') {
1668 $headercounter++;
1669 $element->_generateId();
1670 $headername = $element->getName();
1671 $anyrequiredorerror = false;
1672 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1673 $anyrequiredorerror = true;
1674 } else {
1675 // Do not reset $anyrequiredorerror to false because we do not want any other element
1676 // in this header (fieldset) to possibly revert the state given.
1679 if ($element->getType() == 'header') {
1680 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1681 // By default the first section is always expanded, except if a state has already been set.
1682 $this->setExpanded($headername, true);
1683 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1684 // The second section is always expanded if the form only contains 2 sections),
1685 // except if a state has already been set.
1686 $this->setExpanded($headername, true);
1688 } else if ($anyrequiredorerror) {
1689 // If any error or required field are present within the header, we need to expand it.
1690 $this->setExpanded($headername, true, true);
1691 } else if (!isset($this->_collapsibleElements[$headername])) {
1692 // Define element as collapsed by default.
1693 $this->setExpanded($headername, false);
1697 // Pass the array to renderer object.
1698 $renderer->setCollapsibleElements($this->_collapsibleElements);
1700 parent::accept($renderer);
1704 * Adds one or more element names that indicate the end of a fieldset
1706 * @param string $elementName name of the element
1708 function closeHeaderBefore($elementName){
1709 $renderer =& $this->defaultRenderer();
1710 $renderer->addStopFieldsetElements($elementName);
1714 * Should be used for all elements of a form except for select, radio and checkboxes which
1715 * clean their own data.
1717 * @param string $elementname
1718 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1719 * {@link lib/moodlelib.php} for defined parameter types
1721 function setType($elementname, $paramtype) {
1722 $this->_types[$elementname] = $paramtype;
1726 * This can be used to set several types at once.
1728 * @param array $paramtypes types of parameters.
1729 * @see MoodleQuickForm::setType
1731 function setTypes($paramtypes) {
1732 $this->_types = $paramtypes + $this->_types;
1736 * Return the type(s) to use to clean an element.
1738 * In the case where the element has an array as a value, we will try to obtain a
1739 * type defined for that specific key, and recursively until done.
1741 * This method does not work reverse, you cannot pass a nested element and hoping to
1742 * fallback on the clean type of a parent. This method intends to be used with the
1743 * main element, which will generate child types if needed, not the other way around.
1745 * Example scenario:
1747 * You have defined a new repeated element containing a text field called 'foo'.
1748 * By default there will always be 2 occurence of 'foo' in the form. Even though
1749 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1750 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1751 * $mform->setType('foo[0]', PARAM_FLOAT).
1753 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1754 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1755 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1756 * get the default clean type returned (param $default).
1758 * @param string $elementname name of the element.
1759 * @param mixed $value value that should be cleaned.
1760 * @param int $default default constant value to be returned (PARAM_...)
1761 * @return string|array constant value or array of constant values (PARAM_...)
1763 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1764 $type = $default;
1765 if (array_key_exists($elementname, $this->_types)) {
1766 $type = $this->_types[$elementname];
1768 if (is_array($value)) {
1769 $default = $type;
1770 $type = array();
1771 foreach ($value as $subkey => $subvalue) {
1772 $typekey = "$elementname" . "[$subkey]";
1773 if (array_key_exists($typekey, $this->_types)) {
1774 $subtype = $this->_types[$typekey];
1775 } else {
1776 $subtype = $default;
1778 if (is_array($subvalue)) {
1779 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1780 } else {
1781 $type[$subkey] = $subtype;
1785 return $type;
1789 * Return the cleaned value using the passed type(s).
1791 * @param mixed $value value that has to be cleaned.
1792 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1793 * @return mixed cleaned up value.
1795 public function getCleanedValue($value, $type) {
1796 if (is_array($type) && is_array($value)) {
1797 foreach ($type as $key => $param) {
1798 $value[$key] = $this->getCleanedValue($value[$key], $param);
1800 } else if (!is_array($type) && !is_array($value)) {
1801 $value = clean_param($value, $type);
1802 } else if (!is_array($type) && is_array($value)) {
1803 $value = clean_param_array($value, $type, true);
1804 } else {
1805 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1807 return $value;
1811 * Updates submitted values
1813 * @param array $submission submitted values
1814 * @param array $files list of files
1816 function updateSubmission($submission, $files) {
1817 $this->_flagSubmitted = false;
1819 if (empty($submission)) {
1820 $this->_submitValues = array();
1821 } else {
1822 foreach ($submission as $key => $s) {
1823 $type = $this->getCleanType($key, $s);
1824 $submission[$key] = $this->getCleanedValue($s, $type);
1826 $this->_submitValues = $submission;
1827 $this->_flagSubmitted = true;
1830 if (empty($files)) {
1831 $this->_submitFiles = array();
1832 } else {
1833 $this->_submitFiles = $files;
1834 $this->_flagSubmitted = true;
1837 // need to tell all elements that they need to update their value attribute.
1838 foreach (array_keys($this->_elements) as $key) {
1839 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1844 * Returns HTML for required elements
1846 * @return string
1848 function getReqHTML(){
1849 return $this->_reqHTML;
1853 * Returns HTML for advanced elements
1855 * @return string
1857 function getAdvancedHTML(){
1858 return $this->_advancedHTML;
1862 * Initializes a default form value. Used to specify the default for a new entry where
1863 * no data is loaded in using moodleform::set_data()
1865 * note: $slashed param removed
1867 * @param string $elementName element name
1868 * @param mixed $defaultValue values for that element name
1870 function setDefault($elementName, $defaultValue){
1871 $this->setDefaults(array($elementName=>$defaultValue));
1875 * Add a help button to element, only one button per element is allowed.
1877 * This is new, simplified and preferable method of setting a help icon on form elements.
1878 * It uses the new $OUTPUT->help_icon().
1880 * Typically, you will provide the same identifier and the component as you have used for the
1881 * label of the element. The string identifier with the _help suffix added is then used
1882 * as the help string.
1884 * There has to be two strings defined:
1885 * 1/ get_string($identifier, $component) - the title of the help page
1886 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1888 * @since Moodle 2.0
1889 * @param string $elementname name of the element to add the item to
1890 * @param string $identifier help string identifier without _help suffix
1891 * @param string $component component name to look the help string in
1892 * @param string $linktext optional text to display next to the icon
1893 * @param bool $suppresscheck set to true if the element may not exist
1895 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1896 global $OUTPUT;
1897 if (array_key_exists($elementname, $this->_elementIndex)) {
1898 $element = $this->_elements[$this->_elementIndex[$elementname]];
1899 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1900 } else if (!$suppresscheck) {
1901 debugging(get_string('nonexistentformelements', 'form', $elementname));
1906 * Set constant value not overridden by _POST or _GET
1907 * note: this does not work for complex names with [] :-(
1909 * @param string $elname name of element
1910 * @param mixed $value
1912 function setConstant($elname, $value) {
1913 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1914 $element =& $this->getElement($elname);
1915 $element->onQuickFormEvent('updateValue', null, $this);
1919 * export submitted values
1921 * @param string $elementList list of elements in form
1922 * @return array
1924 function exportValues($elementList = null){
1925 $unfiltered = array();
1926 if (null === $elementList) {
1927 // iterate over all elements, calling their exportValue() methods
1928 foreach (array_keys($this->_elements) as $key) {
1929 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1930 $varname = $this->_elements[$key]->_attributes['name'];
1931 $value = '';
1932 // If we have a default value then export it.
1933 if (isset($this->_defaultValues[$varname])) {
1934 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
1936 } else {
1937 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1940 if (is_array($value)) {
1941 // This shit throws a bogus warning in PHP 4.3.x
1942 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1945 } else {
1946 if (!is_array($elementList)) {
1947 $elementList = array_map('trim', explode(',', $elementList));
1949 foreach ($elementList as $elementName) {
1950 $value = $this->exportValue($elementName);
1951 if (@PEAR::isError($value)) {
1952 return $value;
1954 //oh, stock QuickFOrm was returning array of arrays!
1955 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1959 if (is_array($this->_constantValues)) {
1960 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1962 return $unfiltered;
1966 * This is a bit of a hack, and it duplicates the code in
1967 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
1968 * reliably calling that code. (Think about date selectors, for example.)
1969 * @param string $name the element name.
1970 * @param mixed $value the fixed value to set.
1971 * @return mixed the appropriate array to add to the $unfiltered array.
1973 protected function prepare_fixed_value($name, $value) {
1974 if (null === $value) {
1975 return null;
1976 } else {
1977 if (!strpos($name, '[')) {
1978 return array($name => $value);
1979 } else {
1980 $valueAry = array();
1981 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
1982 eval("\$valueAry$myIndex = \$value;");
1983 return $valueAry;
1989 * Adds a validation rule for the given field
1991 * If the element is in fact a group, it will be considered as a whole.
1992 * To validate grouped elements as separated entities,
1993 * use addGroupRule instead of addRule.
1995 * @param string $element Form element name
1996 * @param string $message Message to display for invalid data
1997 * @param string $type Rule type, use getRegisteredRules() to get types
1998 * @param string $format (optional)Required for extra rule data
1999 * @param string $validation (optional)Where to perform validation: "server", "client"
2000 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2001 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2003 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2005 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2006 if ($validation == 'client') {
2007 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2013 * Adds a validation rule for the given group of elements
2015 * Only groups with a name can be assigned a validation rule
2016 * Use addGroupRule when you need to validate elements inside the group.
2017 * Use addRule if you need to validate the group as a whole. In this case,
2018 * the same rule will be applied to all elements in the group.
2019 * Use addRule if you need to validate the group against a function.
2021 * @param string $group Form group name
2022 * @param array|string $arg1 Array for multiple elements or error message string for one element
2023 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2024 * @param string $format (optional)Required for extra rule data
2025 * @param int $howmany (optional)How many valid elements should be in the group
2026 * @param string $validation (optional)Where to perform validation: "server", "client"
2027 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2029 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2031 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2032 if (is_array($arg1)) {
2033 foreach ($arg1 as $rules) {
2034 foreach ($rules as $rule) {
2035 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2037 if ('client' == $validation) {
2038 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2042 } elseif (is_string($arg1)) {
2044 if ($validation == 'client') {
2045 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2051 * Returns the client side validation script
2053 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2054 * and slightly modified to run rules per-element
2055 * Needed to override this because of an error with client side validation of grouped elements.
2057 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2059 function getValidationScript()
2061 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
2062 return '';
2065 include_once('HTML/QuickForm/RuleRegistry.php');
2066 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2067 $test = array();
2068 $js_escape = array(
2069 "\r" => '\r',
2070 "\n" => '\n',
2071 "\t" => '\t',
2072 "'" => "\\'",
2073 '"' => '\"',
2074 '\\' => '\\\\'
2077 foreach ($this->_rules as $elementName => $rules) {
2078 foreach ($rules as $rule) {
2079 if ('client' == $rule['validation']) {
2080 unset($element); //TODO: find out how to properly initialize it
2082 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2083 $rule['message'] = strtr($rule['message'], $js_escape);
2085 if (isset($rule['group'])) {
2086 $group =& $this->getElement($rule['group']);
2087 // No JavaScript validation for frozen elements
2088 if ($group->isFrozen()) {
2089 continue 2;
2091 $elements =& $group->getElements();
2092 foreach (array_keys($elements) as $key) {
2093 if ($elementName == $group->getElementName($key)) {
2094 $element =& $elements[$key];
2095 break;
2098 } elseif ($dependent) {
2099 $element = array();
2100 $element[] =& $this->getElement($elementName);
2101 foreach ($rule['dependent'] as $elName) {
2102 $element[] =& $this->getElement($elName);
2104 } else {
2105 $element =& $this->getElement($elementName);
2107 // No JavaScript validation for frozen elements
2108 if (is_object($element) && $element->isFrozen()) {
2109 continue 2;
2110 } elseif (is_array($element)) {
2111 foreach (array_keys($element) as $key) {
2112 if ($element[$key]->isFrozen()) {
2113 continue 3;
2117 //for editor element, [text] is appended to the name.
2118 $fullelementname = $elementName;
2119 if ($element->getType() == 'editor') {
2120 $fullelementname .= '[text]';
2121 //Add format to rule as moodleform check which format is supported by browser
2122 //it is not set anywhere... So small hack to make sure we pass it down to quickform
2123 if (is_null($rule['format'])) {
2124 $rule['format'] = $element->getFormat();
2127 // Fix for bug displaying errors for elements in a group
2128 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2129 $test[$fullelementname][1]=$element;
2130 //end of fix
2135 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2136 // the form, and then that form field gets corrupted by the code that follows.
2137 unset($element);
2139 $js = '
2140 <script type="text/javascript">
2141 //<![CDATA[
2143 var skipClientValidation = false;
2145 function qf_errorHandler(element, _qfMsg, escapedName) {
2146 div = element.parentNode;
2148 if ((div == undefined) || (element.name == undefined)) {
2149 //no checking can be done for undefined elements so let server handle it.
2150 return true;
2153 if (_qfMsg != \'\') {
2154 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2155 if (!errorSpan) {
2156 errorSpan = document.createElement("span");
2157 errorSpan.id = \'id_error_\' + escapedName;
2158 errorSpan.className = "error";
2159 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2160 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2161 document.getElementById(errorSpan.id).focus();
2164 while (errorSpan.firstChild) {
2165 errorSpan.removeChild(errorSpan.firstChild);
2168 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2170 if (div.className.substr(div.className.length - 6, 6) != " error"
2171 && div.className != "error") {
2172 div.className += " error";
2173 linebreak = document.createElement("br");
2174 linebreak.className = "error";
2175 linebreak.id = \'id_error_break_\' + escapedName;
2176 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2179 return false;
2180 } else {
2181 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2182 if (errorSpan) {
2183 errorSpan.parentNode.removeChild(errorSpan);
2185 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2186 if (linebreak) {
2187 linebreak.parentNode.removeChild(linebreak);
2190 if (div.className.substr(div.className.length - 6, 6) == " error") {
2191 div.className = div.className.substr(0, div.className.length - 6);
2192 } else if (div.className == "error") {
2193 div.className = "";
2196 return true;
2199 $validateJS = '';
2200 foreach ($test as $elementName => $jsandelement) {
2201 // Fix for bug displaying errors for elements in a group
2202 //unset($element);
2203 list($jsArr,$element)=$jsandelement;
2204 //end of fix
2205 $escapedElementName = preg_replace_callback(
2206 '/[_\[\]-]/',
2207 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2208 $elementName);
2209 $js .= '
2210 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2211 if (undefined == element) {
2212 //required element was not found, then let form be submitted without client side validation
2213 return true;
2215 var value = \'\';
2216 var errFlag = new Array();
2217 var _qfGroups = {};
2218 var _qfMsg = \'\';
2219 var frm = element.parentNode;
2220 if ((undefined != element.name) && (frm != undefined)) {
2221 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2222 frm = frm.parentNode;
2224 ' . join("\n", $jsArr) . '
2225 return qf_errorHandler(element, _qfMsg, escapedName);
2226 } else {
2227 //element name should be defined else error msg will not be displayed.
2228 return true;
2232 $validateJS .= '
2233 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2234 if (!ret && !first_focus) {
2235 first_focus = true;
2236 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \''. $this->_attributes['id'] .'\',
2237 elementid: \'id_error_'.$escapedElementName.'\'});
2238 document.getElementById(\'id_error_'.$escapedElementName.'\').focus();
2242 // Fix for bug displaying errors for elements in a group
2243 //unset($element);
2244 //$element =& $this->getElement($elementName);
2245 //end of fix
2246 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this, \''.$escapedElementName.'\')';
2247 $onBlur = $element->getAttribute('onBlur');
2248 $onChange = $element->getAttribute('onChange');
2249 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2250 'onChange' => $onChange . $valFunc));
2252 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2253 $js .= '
2254 function validate_' . $this->_formName . '(frm) {
2255 if (skipClientValidation) {
2256 return true;
2258 var ret = true;
2260 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2261 var first_focus = false;
2262 ' . $validateJS . ';
2263 return ret;
2265 //]]>
2266 </script>';
2267 return $js;
2268 } // end func getValidationScript
2271 * Sets default error message
2273 function _setDefaultRuleMessages(){
2274 foreach ($this->_rules as $field => $rulesarr){
2275 foreach ($rulesarr as $key => $rule){
2276 if ($rule['message']===null){
2277 $a=new stdClass();
2278 $a->format=$rule['format'];
2279 $str=get_string('err_'.$rule['type'], 'form', $a);
2280 if (strpos($str, '[[')!==0){
2281 $this->_rules[$field][$key]['message']=$str;
2289 * Get list of attributes which have dependencies
2291 * @return array
2293 function getLockOptionObject(){
2294 $result = array();
2295 foreach ($this->_dependencies as $dependentOn => $conditions){
2296 $result[$dependentOn] = array();
2297 foreach ($conditions as $condition=>$values) {
2298 $result[$dependentOn][$condition] = array();
2299 foreach ($values as $value=>$dependents) {
2300 $result[$dependentOn][$condition][$value] = array();
2301 $i = 0;
2302 foreach ($dependents as $dependent) {
2303 $elements = $this->_getElNamesRecursive($dependent);
2304 if (empty($elements)) {
2305 // probably element inside of some group
2306 $elements = array($dependent);
2308 foreach($elements as $element) {
2309 if ($element == $dependentOn) {
2310 continue;
2312 $result[$dependentOn][$condition][$value][] = $element;
2318 return array($this->getAttribute('id'), $result);
2322 * Get names of element or elements in a group.
2324 * @param HTML_QuickForm_group|element $element element group or element object
2325 * @return array
2327 function _getElNamesRecursive($element) {
2328 if (is_string($element)) {
2329 if (!$this->elementExists($element)) {
2330 return array();
2332 $element = $this->getElement($element);
2335 if (is_a($element, 'HTML_QuickForm_group')) {
2336 $elsInGroup = $element->getElements();
2337 $elNames = array();
2338 foreach ($elsInGroup as $elInGroup){
2339 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2340 // not sure if this would work - groups nested in groups
2341 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2342 } else {
2343 $elNames[] = $element->getElementName($elInGroup->getName());
2347 } else if (is_a($element, 'HTML_QuickForm_header')) {
2348 return array();
2350 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2351 return array();
2353 } else if (method_exists($element, 'getPrivateName') &&
2354 !($element instanceof HTML_QuickForm_advcheckbox)) {
2355 // The advcheckbox element implements a method called getPrivateName,
2356 // but in a way that is not compatible with the generic API, so we
2357 // have to explicitly exclude it.
2358 return array($element->getPrivateName());
2360 } else {
2361 $elNames = array($element->getName());
2364 return $elNames;
2368 * Adds a dependency for $elementName which will be disabled if $condition is met.
2369 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2370 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2371 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2372 * of the $dependentOn element is $condition (such as equal) to $value.
2374 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2375 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2376 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2378 * @param string $elementName the name of the element which will be disabled
2379 * @param string $dependentOn the name of the element whose state will be checked for condition
2380 * @param string $condition the condition to check
2381 * @param mixed $value used in conjunction with condition.
2383 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2384 // Multiple selects allow for a multiple selection, we transform the array to string here as
2385 // an array cannot be used as a key in an associative array.
2386 if (is_array($value)) {
2387 $value = implode('|', $value);
2389 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2390 $this->_dependencies[$dependentOn] = array();
2392 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2393 $this->_dependencies[$dependentOn][$condition] = array();
2395 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2396 $this->_dependencies[$dependentOn][$condition][$value] = array();
2398 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2402 * Registers button as no submit button
2404 * @param string $buttonname name of the button
2406 function registerNoSubmitButton($buttonname){
2407 $this->_noSubmitButtons[]=$buttonname;
2411 * Checks if button is a no submit button, i.e it doesn't submit form
2413 * @param string $buttonname name of the button to check
2414 * @return bool
2416 function isNoSubmitButton($buttonname){
2417 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2421 * Registers a button as cancel button
2423 * @param string $addfieldsname name of the button
2425 function _registerCancelButton($addfieldsname){
2426 $this->_cancelButtons[]=$addfieldsname;
2430 * Displays elements without HTML input tags.
2431 * This method is different to freeze() in that it makes sure no hidden
2432 * elements are included in the form.
2433 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2435 * This function also removes all previously defined rules.
2437 * @param string|array $elementList array or string of element(s) to be frozen
2438 * @return object|bool if element list is not empty then return error object, else true
2440 function hardFreeze($elementList=null)
2442 if (!isset($elementList)) {
2443 $this->_freezeAll = true;
2444 $elementList = array();
2445 } else {
2446 if (!is_array($elementList)) {
2447 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2449 $elementList = array_flip($elementList);
2452 foreach (array_keys($this->_elements) as $key) {
2453 $name = $this->_elements[$key]->getName();
2454 if ($this->_freezeAll || isset($elementList[$name])) {
2455 $this->_elements[$key]->freeze();
2456 $this->_elements[$key]->setPersistantFreeze(false);
2457 unset($elementList[$name]);
2459 // remove all rules
2460 $this->_rules[$name] = array();
2461 // if field is required, remove the rule
2462 $unset = array_search($name, $this->_required);
2463 if ($unset !== false) {
2464 unset($this->_required[$unset]);
2469 if (!empty($elementList)) {
2470 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);
2472 return true;
2476 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2478 * This function also removes all previously defined rules of elements it freezes.
2480 * @throws HTML_QuickForm_Error
2481 * @param array $elementList array or string of element(s) not to be frozen
2482 * @return bool returns true
2484 function hardFreezeAllVisibleExcept($elementList)
2486 $elementList = array_flip($elementList);
2487 foreach (array_keys($this->_elements) as $key) {
2488 $name = $this->_elements[$key]->getName();
2489 $type = $this->_elements[$key]->getType();
2491 if ($type == 'hidden'){
2492 // leave hidden types as they are
2493 } elseif (!isset($elementList[$name])) {
2494 $this->_elements[$key]->freeze();
2495 $this->_elements[$key]->setPersistantFreeze(false);
2497 // remove all rules
2498 $this->_rules[$name] = array();
2499 // if field is required, remove the rule
2500 $unset = array_search($name, $this->_required);
2501 if ($unset !== false) {
2502 unset($this->_required[$unset]);
2506 return true;
2510 * Tells whether the form was already submitted
2512 * This is useful since the _submitFiles and _submitValues arrays
2513 * may be completely empty after the trackSubmit value is removed.
2515 * @return bool
2517 function isSubmitted()
2519 return parent::isSubmitted() && (!$this->isFrozen());
2524 * MoodleQuickForm renderer
2526 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2527 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2529 * Stylesheet is part of standard theme and should be automatically included.
2531 * @package core_form
2532 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2533 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2535 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2537 /** @var array Element template array */
2538 var $_elementTemplates;
2541 * Template used when opening a hidden fieldset
2542 * (i.e. a fieldset that is opened when there is no header element)
2543 * @var string
2545 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2547 /** @var string Header Template string */
2548 var $_headerTemplate =
2549 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2551 /** @var string Template used when opening a fieldset */
2552 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2554 /** @var string Template used when closing a fieldset */
2555 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2557 /** @var string Required Note template string */
2558 var $_requiredNoteTemplate =
2559 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2562 * Collapsible buttons string template.
2564 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2565 * until the Javascript has been fully loaded.
2567 * @var string
2569 var $_collapseButtonsTemplate =
2570 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2573 * Array whose keys are element names. If the key exists this is a advanced element
2575 * @var array
2577 var $_advancedElements = array();
2580 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2582 * @var array
2584 var $_collapsibleElements = array();
2587 * @var string Contains the collapsible buttons to add to the form.
2589 var $_collapseButtons = '';
2592 * Constructor
2594 function MoodleQuickForm_Renderer(){
2595 // switch next two lines for ol li containers for form items.
2596 // $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>');
2597 $this->_elementTemplates = array(
2598 '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>',
2600 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2602 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- 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>',
2604 'static'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{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>',
2606 'warning'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}">{element}</div>',
2608 'nodisplay'=>'');
2610 parent::HTML_QuickForm_Renderer_Tableless();
2614 * Set element's as adavance element
2616 * @param array $elements form elements which needs to be grouped as advance elements.
2618 function setAdvancedElements($elements){
2619 $this->_advancedElements = $elements;
2623 * Setting collapsible elements
2625 * @param array $elements
2627 function setCollapsibleElements($elements) {
2628 $this->_collapsibleElements = $elements;
2632 * What to do when starting the form
2634 * @param MoodleQuickForm $form reference of the form
2636 function startForm(&$form){
2637 global $PAGE;
2638 $this->_reqHTML = $form->getReqHTML();
2639 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2640 $this->_advancedHTML = $form->getAdvancedHTML();
2641 $this->_collapseButtons = '';
2642 $formid = $form->getAttribute('id');
2643 parent::startForm($form);
2644 if ($form->isFrozen()){
2645 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2646 } else {
2647 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2648 $this->_hiddenHtml .= $form->_pageparams;
2651 if ($form->is_form_change_checker_enabled()) {
2652 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2653 'M.core_formchangechecker.init',
2654 array(array(
2655 'formid' => $formid
2658 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2660 if (!empty($this->_collapsibleElements)) {
2661 if (count($this->_collapsibleElements) > 1) {
2662 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2663 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2664 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2666 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2668 if (!empty($this->_advancedElements)){
2669 $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2670 $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2675 * Create advance group of elements
2677 * @param object $group Passed by reference
2678 * @param bool $required if input is required field
2679 * @param string $error error message to display
2681 function startGroup(&$group, $required, $error){
2682 // Make sure the element has an id.
2683 $group->_generateId();
2685 if (method_exists($group, 'getElementTemplateType')){
2686 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2687 }else{
2688 $html = $this->_elementTemplates['default'];
2692 if (isset($this->_advancedElements[$group->getName()])){
2693 $html =str_replace(' {advanced}', ' advanced', $html);
2694 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2695 } else {
2696 $html =str_replace(' {advanced}', '', $html);
2697 $html =str_replace('{advancedimg}', '', $html);
2699 if (method_exists($group, 'getHelpButton')){
2700 $html =str_replace('{help}', $group->getHelpButton(), $html);
2701 }else{
2702 $html =str_replace('{help}', '', $html);
2704 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2705 $html =str_replace('{name}', $group->getName(), $html);
2706 $html =str_replace('{type}', 'fgroup', $html);
2707 $emptylabel = '';
2708 if ($group->getLabel() == '') {
2709 $emptylabel = 'femptylabel';
2711 $html = str_replace('{emptylabel}', $emptylabel, $html);
2713 $this->_templates[$group->getName()]=$html;
2714 // Fix for bug in tableless quickforms that didn't allow you to stop a
2715 // fieldset before a group of elements.
2716 // if the element name indicates the end of a fieldset, close the fieldset
2717 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2718 && $this->_fieldsetsOpen > 0
2720 $this->_html .= $this->_closeFieldsetTemplate;
2721 $this->_fieldsetsOpen--;
2723 parent::startGroup($group, $required, $error);
2727 * Renders element
2729 * @param HTML_QuickForm_element $element element
2730 * @param bool $required if input is required field
2731 * @param string $error error message to display
2733 function renderElement(&$element, $required, $error){
2734 // Make sure the element has an id.
2735 $element->_generateId();
2737 //adding stuff to place holders in template
2738 //check if this is a group element first
2739 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2740 // so it gets substitutions for *each* element
2741 $html = $this->_groupElementTemplate;
2743 elseif (method_exists($element, 'getElementTemplateType')){
2744 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2745 }else{
2746 $html = $this->_elementTemplates['default'];
2748 if (isset($this->_advancedElements[$element->getName()])){
2749 $html = str_replace(' {advanced}', ' advanced', $html);
2750 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2751 } else {
2752 $html = str_replace(' {advanced}', '', $html);
2753 $html = str_replace(' {aria-live}', '', $html);
2755 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2756 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2757 } else {
2758 $html =str_replace('{advancedimg}', '', $html);
2760 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2761 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2762 $html =str_replace('{name}', $element->getName(), $html);
2763 $emptylabel = '';
2764 if ($element->getLabel() == '') {
2765 $emptylabel = 'femptylabel';
2767 $html = str_replace('{emptylabel}', $emptylabel, $html);
2768 if (method_exists($element, 'getHelpButton')){
2769 $html = str_replace('{help}', $element->getHelpButton(), $html);
2770 }else{
2771 $html = str_replace('{help}', '', $html);
2774 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2775 $this->_groupElementTemplate = $html;
2777 elseif (!isset($this->_templates[$element->getName()])) {
2778 $this->_templates[$element->getName()] = $html;
2781 parent::renderElement($element, $required, $error);
2785 * Called when visiting a form, after processing all form elements
2786 * Adds required note, form attributes, validation javascript and form content.
2788 * @global moodle_page $PAGE
2789 * @param moodleform $form Passed by reference
2791 function finishForm(&$form){
2792 global $PAGE;
2793 if ($form->isFrozen()){
2794 $this->_hiddenHtml = '';
2796 parent::finishForm($form);
2797 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2798 if (!$form->isFrozen()) {
2799 $args = $form->getLockOptionObject();
2800 if (count($args[1]) > 0) {
2801 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2806 * Called when visiting a header element
2808 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2809 * @global moodle_page $PAGE
2811 function renderHeader(&$header) {
2812 global $PAGE;
2814 $header->_generateId();
2815 $name = $header->getName();
2817 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2818 if (is_null($header->_text)) {
2819 $header_html = '';
2820 } elseif (!empty($name) && isset($this->_templates[$name])) {
2821 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2822 } else {
2823 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2826 if ($this->_fieldsetsOpen > 0) {
2827 $this->_html .= $this->_closeFieldsetTemplate;
2828 $this->_fieldsetsOpen--;
2831 // Define collapsible classes for fieldsets.
2832 $arialive = '';
2833 $fieldsetclasses = array('clearfix');
2834 if (isset($this->_collapsibleElements[$header->getName()])) {
2835 $fieldsetclasses[] = 'collapsible';
2836 if ($this->_collapsibleElements[$header->getName()]) {
2837 $fieldsetclasses[] = 'collapsed';
2841 if (isset($this->_advancedElements[$name])){
2842 $fieldsetclasses[] = 'containsadvancedelements';
2845 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2846 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
2848 $this->_html .= $openFieldsetTemplate . $header_html;
2849 $this->_fieldsetsOpen++;
2853 * Return Array of element names that indicate the end of a fieldset
2855 * @return array
2857 function getStopFieldsetElements(){
2858 return $this->_stopFieldsetElements;
2863 * Required elements validation
2865 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2867 * @package core_form
2868 * @category form
2869 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2870 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2872 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2874 * Checks if an element is not empty.
2875 * This is a server-side validation, it works for both text fields and editor fields
2877 * @param string $value Value to check
2878 * @param int|string|array $options Not used yet
2879 * @return bool true if value is not empty
2881 function validate($value, $options = null) {
2882 global $CFG;
2883 if (is_array($value) && array_key_exists('text', $value)) {
2884 $value = $value['text'];
2886 if (is_array($value)) {
2887 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2888 $value = implode('', $value);
2890 $stripvalues = array(
2891 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2892 '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
2894 if (!empty($CFG->strictformsrequired)) {
2895 $value = preg_replace($stripvalues, '', (string)$value);
2897 if ((string)$value == '') {
2898 return false;
2900 return true;
2904 * This function returns Javascript code used to build client-side validation.
2905 * It checks if an element is not empty.
2907 * @param int $format format of data which needs to be validated.
2908 * @return array
2910 function getValidationScript($format = null) {
2911 global $CFG;
2912 if (!empty($CFG->strictformsrequired)) {
2913 if (!empty($format) && $format == FORMAT_HTML) {
2914 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
2915 } else {
2916 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2918 } else {
2919 return array('', "{jsVar} == ''");
2925 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2926 * @name $_HTML_QuickForm_default_renderer
2928 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2930 /** Please keep this list in alphabetical order. */
2931 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2932 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2933 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2934 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2935 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2936 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2937 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2938 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2939 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2940 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2941 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2942 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2943 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2944 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2945 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2946 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2947 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
2948 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2949 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2950 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2951 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2952 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2953 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2954 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2955 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2956 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2957 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2958 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2959 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2960 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2961 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2962 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2963 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2964 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2965 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2966 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2968 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");