Merge branch 'MDL-42592_master' of https://github.com/markn86/moodle
[moodle.git] / lib / formslib.php
blob71e213a80155e7c2626497db1b79c3854f0da405
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 $this->definition();
193 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
194 $this->_form->setType('sesskey', PARAM_RAW);
195 $this->_form->setDefault('sesskey', sesskey());
196 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
197 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
198 $this->_form->setDefault('_qf__'.$this->_formname, 1);
199 $this->_form->_setDefaultRuleMessages();
201 // we have to know all input types before processing submission ;-)
202 $this->_process_submission($method);
206 * It should returns unique identifier for the form.
207 * Currently it will return class name, but in case two same forms have to be
208 * rendered on same page then override function to get unique form identifier.
209 * e.g This is used on multiple self enrollments page.
211 * @return string form identifier.
213 protected function get_form_identifier() {
214 return get_class($this);
218 * To autofocus on first form element or first element with error.
220 * @param string $name if this is set then the focus is forced to a field with this name
221 * @return string javascript to select form element with first error or
222 * first element if no errors. Use this as a parameter
223 * when calling print_header
225 function focus($name=NULL) {
226 $form =& $this->_form;
227 $elkeys = array_keys($form->_elementIndex);
228 $error = false;
229 if (isset($form->_errors) && 0 != count($form->_errors)){
230 $errorkeys = array_keys($form->_errors);
231 $elkeys = array_intersect($elkeys, $errorkeys);
232 $error = true;
235 if ($error or empty($name)) {
236 $names = array();
237 while (empty($names) and !empty($elkeys)) {
238 $el = array_shift($elkeys);
239 $names = $form->_getElNamesRecursive($el);
241 if (!empty($names)) {
242 $name = array_shift($names);
246 $focus = '';
247 if (!empty($name)) {
248 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
251 return $focus;
255 * Internal method. Alters submitted data to be suitable for quickforms processing.
256 * Must be called when the form is fully set up.
258 * @param string $method name of the method which alters submitted data
260 function _process_submission($method) {
261 $submission = array();
262 if ($method == 'post') {
263 if (!empty($_POST)) {
264 $submission = $this->_get_post_params();
266 } else {
267 $submission = array_merge_recursive($_GET, $this->_get_post_params()); // Emulate handling of parameters in xxxx_param().
270 // following trick is needed to enable proper sesskey checks when using GET forms
271 // the _qf__.$this->_formname serves as a marker that form was actually submitted
272 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
273 if (!confirm_sesskey()) {
274 print_error('invalidsesskey');
276 $files = $_FILES;
277 } else {
278 $submission = array();
279 $files = array();
281 $this->detectMissingSetType();
283 $this->_form->updateSubmission($submission, $files);
287 * Internal method. Gets all POST variables, bypassing max_input_vars limit if needed.
289 * @return array All POST variables as an array, in the same format as $_POST.
291 protected function _get_post_params() {
292 $enctype = $this->_form->getAttribute('enctype');
293 $max = (int)ini_get('max_input_vars');
295 if (empty($max) || count($_POST, COUNT_RECURSIVE) < $max || (!empty($enctype) && $enctype == 'multipart/form-data')) {
296 return $_POST;
299 // Large POST request with enctype supported by php://input.
300 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
301 $allvalues = array();
302 $values = array();
303 $str = file_get_contents("php://input");
304 $delim = '&';
306 $fun = create_function('$p', 'return implode("'.$delim.'", $p);');
307 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
309 foreach ($chunks as $chunk) {
310 parse_str($chunk, $values);
311 $allvalues = array_merge_recursive($allvalues, $values);
314 return $allvalues;
318 * Internal method. Validates all old-style deprecated uploaded files.
319 * The new way is to upload files via repository api.
321 * @param array $files list of files to be validated
322 * @return bool|array Success or an array of errors
324 function _validate_files(&$files) {
325 global $CFG, $COURSE;
327 $files = array();
329 if (empty($_FILES)) {
330 // we do not need to do any checks because no files were submitted
331 // note: server side rules do not work for files - use custom verification in validate() instead
332 return true;
335 $errors = array();
336 $filenames = array();
338 // now check that we really want each file
339 foreach ($_FILES as $elname=>$file) {
340 $required = $this->_form->isElementRequired($elname);
342 if ($file['error'] == 4 and $file['size'] == 0) {
343 if ($required) {
344 $errors[$elname] = get_string('required');
346 unset($_FILES[$elname]);
347 continue;
350 if (!empty($file['error'])) {
351 $errors[$elname] = file_get_upload_error($file['error']);
352 unset($_FILES[$elname]);
353 continue;
356 if (!is_uploaded_file($file['tmp_name'])) {
357 // TODO: improve error message
358 $errors[$elname] = get_string('error');
359 unset($_FILES[$elname]);
360 continue;
363 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
364 // hmm, this file was not requested
365 unset($_FILES[$elname]);
366 continue;
370 // TODO: rethink the file scanning MDL-19380
371 if ($CFG->runclamonupload) {
372 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
373 $errors[$elname] = $_FILES[$elname]['uploadlog'];
374 unset($_FILES[$elname]);
375 continue;
379 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
380 if ($filename === '') {
381 // TODO: improve error message - wrong chars
382 $errors[$elname] = get_string('error');
383 unset($_FILES[$elname]);
384 continue;
386 if (in_array($filename, $filenames)) {
387 // TODO: improve error message - duplicate name
388 $errors[$elname] = get_string('error');
389 unset($_FILES[$elname]);
390 continue;
392 $filenames[] = $filename;
393 $_FILES[$elname]['name'] = $filename;
395 $files[$elname] = $_FILES[$elname]['tmp_name'];
398 // return errors if found
399 if (count($errors) == 0){
400 return true;
402 } else {
403 $files = array();
404 return $errors;
409 * Internal method. Validates filepicker and filemanager files if they are
410 * set as required fields. Also, sets the error message if encountered one.
412 * @return bool|array with errors
414 protected function validate_draft_files() {
415 global $USER;
416 $mform =& $this->_form;
418 $errors = array();
419 //Go through all the required elements and make sure you hit filepicker or
420 //filemanager element.
421 foreach ($mform->_rules as $elementname => $rules) {
422 $elementtype = $mform->getElementType($elementname);
423 //If element is of type filepicker then do validation
424 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
425 //Check if rule defined is required rule
426 foreach ($rules as $rule) {
427 if ($rule['type'] == 'required') {
428 $draftid = (int)$mform->getSubmitValue($elementname);
429 $fs = get_file_storage();
430 $context = context_user::instance($USER->id);
431 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
432 $errors[$elementname] = $rule['message'];
438 // Check all the filemanager elements to make sure they do not have too many
439 // files in them.
440 foreach ($mform->_elements as $element) {
441 if ($element->_type == 'filemanager') {
442 $maxfiles = $element->getMaxfiles();
443 if ($maxfiles > 0) {
444 $draftid = (int)$element->getValue();
445 $fs = get_file_storage();
446 $context = context_user::instance($USER->id);
447 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
448 if (count($files) > $maxfiles) {
449 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
454 if (empty($errors)) {
455 return true;
456 } else {
457 return $errors;
462 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
463 * form definition (new entry form); this function is used to load in data where values
464 * already exist and data is being edited (edit entry form).
466 * note: $slashed param removed
468 * @param stdClass|array $default_values object or array of default values
470 function set_data($default_values) {
471 if (is_object($default_values)) {
472 $default_values = (array)$default_values;
474 $this->_form->setDefaults($default_values);
478 * Check that form was submitted. Does not check validity of submitted data.
480 * @return bool true if form properly submitted
482 function is_submitted() {
483 return $this->_form->isSubmitted();
487 * Checks if button pressed is not for submitting the form
489 * @staticvar bool $nosubmit keeps track of no submit button
490 * @return bool
492 function no_submit_button_pressed(){
493 static $nosubmit = null; // one check is enough
494 if (!is_null($nosubmit)){
495 return $nosubmit;
497 $mform =& $this->_form;
498 $nosubmit = false;
499 if (!$this->is_submitted()){
500 return false;
502 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
503 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
504 $nosubmit = true;
505 break;
508 return $nosubmit;
513 * Check that form data is valid.
514 * You should almost always use this, rather than {@link validate_defined_fields}
516 * @return bool true if form data valid
518 function is_validated() {
519 //finalize the form definition before any processing
520 if (!$this->_definition_finalized) {
521 $this->_definition_finalized = true;
522 $this->definition_after_data();
525 return $this->validate_defined_fields();
529 * Validate the form.
531 * You almost always want to call {@link is_validated} instead of this
532 * because it calls {@link definition_after_data} first, before validating the form,
533 * which is what you want in 99% of cases.
535 * This is provided as a separate function for those special cases where
536 * you want the form validated before definition_after_data is called
537 * for example, to selectively add new elements depending on a no_submit_button press,
538 * but only when the form is valid when the no_submit_button is pressed,
540 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
541 * is NOT to validate the form when a no submit button has been pressed.
542 * pass true here to override this behaviour
544 * @return bool true if form data valid
546 function validate_defined_fields($validateonnosubmit=false) {
547 static $validated = null; // one validation is enough
548 $mform =& $this->_form;
549 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
550 return false;
551 } elseif ($validated === null) {
552 $internal_val = $mform->validate();
554 $files = array();
555 $file_val = $this->_validate_files($files);
556 //check draft files for validation and flag them if required files
557 //are not in draft area.
558 $draftfilevalue = $this->validate_draft_files();
560 if ($file_val !== true && $draftfilevalue !== true) {
561 $file_val = array_merge($file_val, $draftfilevalue);
562 } else if ($draftfilevalue !== true) {
563 $file_val = $draftfilevalue;
564 } //default is file_val, so no need to assign.
566 if ($file_val !== true) {
567 if (!empty($file_val)) {
568 foreach ($file_val as $element=>$msg) {
569 $mform->setElementError($element, $msg);
572 $file_val = false;
575 $data = $mform->exportValues();
576 $moodle_val = $this->validation($data, $files);
577 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
578 // non-empty array means errors
579 foreach ($moodle_val as $element=>$msg) {
580 $mform->setElementError($element, $msg);
582 $moodle_val = false;
584 } else {
585 // anything else means validation ok
586 $moodle_val = true;
589 $validated = ($internal_val and $moodle_val and $file_val);
591 return $validated;
595 * Return true if a cancel button has been pressed resulting in the form being submitted.
597 * @return bool true if a cancel button has been pressed
599 function is_cancelled(){
600 $mform =& $this->_form;
601 if ($mform->isSubmitted()){
602 foreach ($mform->_cancelButtons as $cancelbutton){
603 if (optional_param($cancelbutton, 0, PARAM_RAW)){
604 return true;
608 return false;
612 * Return submitted data if properly submitted or returns NULL if validation fails or
613 * if there is no submitted data.
615 * note: $slashed param removed
617 * @return object submitted data; NULL if not valid or not submitted or cancelled
619 function get_data() {
620 $mform =& $this->_form;
622 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
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 * Return submitted data without validation or NULL if there is no submitted data.
638 * note: $slashed param removed
640 * @return object submitted data; NULL if not submitted
642 function get_submitted_data() {
643 $mform =& $this->_form;
645 if ($this->is_submitted()) {
646 $data = $mform->exportValues();
647 unset($data['sesskey']); // we do not need to return sesskey
648 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
649 if (empty($data)) {
650 return NULL;
651 } else {
652 return (object)$data;
654 } else {
655 return NULL;
660 * Save verified uploaded files into directory. Upload process can be customised from definition()
662 * @deprecated since Moodle 2.0
663 * @todo MDL-31294 remove this api
664 * @see moodleform::save_stored_file()
665 * @see moodleform::save_file()
666 * @param string $destination path where file should be stored
667 * @return bool Always false
669 function save_files($destination) {
670 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
671 return false;
675 * Returns name of uploaded file.
677 * @param string $elname first element if null
678 * @return string|bool false in case of failure, string if ok
680 function get_new_filename($elname=null) {
681 global $USER;
683 if (!$this->is_submitted() or !$this->is_validated()) {
684 return false;
687 if (is_null($elname)) {
688 if (empty($_FILES)) {
689 return false;
691 reset($_FILES);
692 $elname = key($_FILES);
695 if (empty($elname)) {
696 return false;
699 $element = $this->_form->getElement($elname);
701 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
702 $values = $this->_form->exportValues($elname);
703 if (empty($values[$elname])) {
704 return false;
706 $draftid = $values[$elname];
707 $fs = get_file_storage();
708 $context = context_user::instance($USER->id);
709 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
710 return false;
712 $file = reset($files);
713 return $file->get_filename();
716 if (!isset($_FILES[$elname])) {
717 return false;
720 return $_FILES[$elname]['name'];
724 * Save file to standard filesystem
726 * @param string $elname name of element
727 * @param string $pathname full path name of file
728 * @param bool $override override file if exists
729 * @return bool success
731 function save_file($elname, $pathname, $override=false) {
732 global $USER;
734 if (!$this->is_submitted() or !$this->is_validated()) {
735 return false;
737 if (file_exists($pathname)) {
738 if ($override) {
739 if (!@unlink($pathname)) {
740 return false;
742 } else {
743 return false;
747 $element = $this->_form->getElement($elname);
749 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
750 $values = $this->_form->exportValues($elname);
751 if (empty($values[$elname])) {
752 return false;
754 $draftid = $values[$elname];
755 $fs = get_file_storage();
756 $context = context_user::instance($USER->id);
757 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
758 return false;
760 $file = reset($files);
762 return $file->copy_content_to($pathname);
764 } else if (isset($_FILES[$elname])) {
765 return copy($_FILES[$elname]['tmp_name'], $pathname);
768 return false;
772 * Returns a temporary file, do not forget to delete after not needed any more.
774 * @param string $elname name of the elmenet
775 * @return string|bool either string or false
777 function save_temp_file($elname) {
778 if (!$this->get_new_filename($elname)) {
779 return false;
781 if (!$dir = make_temp_directory('forms')) {
782 return false;
784 if (!$tempfile = tempnam($dir, 'tempup_')) {
785 return false;
787 if (!$this->save_file($elname, $tempfile, true)) {
788 // something went wrong
789 @unlink($tempfile);
790 return false;
793 return $tempfile;
797 * Get draft files of a form element
798 * This is a protected method which will be used only inside moodleforms
800 * @param string $elname name of element
801 * @return array|bool|null
803 protected function get_draft_files($elname) {
804 global $USER;
806 if (!$this->is_submitted()) {
807 return false;
810 $element = $this->_form->getElement($elname);
812 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
813 $values = $this->_form->exportValues($elname);
814 if (empty($values[$elname])) {
815 return false;
817 $draftid = $values[$elname];
818 $fs = get_file_storage();
819 $context = context_user::instance($USER->id);
820 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
821 return null;
823 return $files;
825 return null;
829 * Save file to local filesystem pool
831 * @param string $elname name of element
832 * @param int $newcontextid id of context
833 * @param string $newcomponent name of the component
834 * @param string $newfilearea name of file area
835 * @param int $newitemid item id
836 * @param string $newfilepath path of file where it get stored
837 * @param string $newfilename use specified filename, if not specified name of uploaded file used
838 * @param bool $overwrite overwrite file if exists
839 * @param int $newuserid new userid if required
840 * @return mixed stored_file object or false if error; may throw exception if duplicate found
842 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
843 $newfilename=null, $overwrite=false, $newuserid=null) {
844 global $USER;
846 if (!$this->is_submitted() or !$this->is_validated()) {
847 return false;
850 if (empty($newuserid)) {
851 $newuserid = $USER->id;
854 $element = $this->_form->getElement($elname);
855 $fs = get_file_storage();
857 if ($element instanceof MoodleQuickForm_filepicker) {
858 $values = $this->_form->exportValues($elname);
859 if (empty($values[$elname])) {
860 return false;
862 $draftid = $values[$elname];
863 $context = context_user::instance($USER->id);
864 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
865 return false;
867 $file = reset($files);
868 if (is_null($newfilename)) {
869 $newfilename = $file->get_filename();
872 if ($overwrite) {
873 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
874 if (!$oldfile->delete()) {
875 return false;
880 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
881 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
882 return $fs->create_file_from_storedfile($file_record, $file);
884 } else if (isset($_FILES[$elname])) {
885 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
887 if ($overwrite) {
888 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
889 if (!$oldfile->delete()) {
890 return false;
895 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
896 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
897 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
900 return false;
904 * Get content of uploaded file.
906 * @param string $elname name of file upload element
907 * @return string|bool false in case of failure, string if ok
909 function get_file_content($elname) {
910 global $USER;
912 if (!$this->is_submitted() or !$this->is_validated()) {
913 return false;
916 $element = $this->_form->getElement($elname);
918 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
919 $values = $this->_form->exportValues($elname);
920 if (empty($values[$elname])) {
921 return false;
923 $draftid = $values[$elname];
924 $fs = get_file_storage();
925 $context = context_user::instance($USER->id);
926 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
927 return false;
929 $file = reset($files);
931 return $file->get_content();
933 } else if (isset($_FILES[$elname])) {
934 return file_get_contents($_FILES[$elname]['tmp_name']);
937 return false;
941 * Print html form.
943 function display() {
944 //finalize the form definition if not yet done
945 if (!$this->_definition_finalized) {
946 $this->_definition_finalized = true;
947 $this->definition_after_data();
950 $this->_form->display();
954 * Renders the html form (same as display, but returns the result).
956 * Note that you can only output this rendered result once per page, as
957 * it contains IDs which must be unique.
959 * @return string HTML code for the form
961 public function render() {
962 ob_start();
963 $this->display();
964 $out = ob_get_contents();
965 ob_end_clean();
966 return $out;
970 * Form definition. Abstract method - always override!
972 protected abstract function definition();
975 * Dummy stub method - override if you need to setup the form depending on current
976 * values. This method is called after definition(), data submission and set_data().
977 * All form setup that is dependent on form values should go in here.
979 function definition_after_data(){
983 * Dummy stub method - override if you needed to perform some extra validation.
984 * If there are errors return array of errors ("fieldname"=>"error message"),
985 * otherwise true if ok.
987 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
989 * @param array $data array of ("fieldname"=>value) of submitted data
990 * @param array $files array of uploaded files "element_name"=>tmp_file_path
991 * @return array of "element_name"=>"error_description" if there are errors,
992 * or an empty array if everything is OK (true allowed for backwards compatibility too).
994 function validation($data, $files) {
995 return array();
999 * Helper used by {@link repeat_elements()}.
1001 * @param int $i the index of this element.
1002 * @param HTML_QuickForm_element $elementclone
1003 * @param array $namecloned array of names
1005 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1006 $name = $elementclone->getName();
1007 $namecloned[] = $name;
1009 if (!empty($name)) {
1010 $elementclone->setName($name."[$i]");
1013 if (is_a($elementclone, 'HTML_QuickForm_header')) {
1014 $value = $elementclone->_text;
1015 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1017 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1018 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1020 } else {
1021 $value=$elementclone->getLabel();
1022 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1027 * Method to add a repeating group of elements to a form.
1029 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1030 * @param int $repeats no of times to repeat elements initially
1031 * @param array $options Array of options to apply to elements. Array keys are element names.
1032 * This is an array of arrays. The second sets of keys are the option types for the elements :
1033 * 'default' - default value is value
1034 * 'type' - PARAM_* constant is value
1035 * 'helpbutton' - helpbutton params array is value
1036 * 'disabledif' - last three moodleform::disabledIf()
1037 * params are value as an array
1038 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1039 * @param string $addfieldsname name for button to add more fields
1040 * @param int $addfieldsno how many fields to add at a time
1041 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1042 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1043 * @return int no of repeats of element in this page
1045 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1046 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1047 if ($addstring===null){
1048 $addstring = get_string('addfields', 'form', $addfieldsno);
1049 } else {
1050 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1052 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1053 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1054 if (!empty($addfields)){
1055 $repeats += $addfieldsno;
1057 $mform =& $this->_form;
1058 $mform->registerNoSubmitButton($addfieldsname);
1059 $mform->addElement('hidden', $repeathiddenname, $repeats);
1060 $mform->setType($repeathiddenname, PARAM_INT);
1061 //value not to be overridden by submitted value
1062 $mform->setConstants(array($repeathiddenname=>$repeats));
1063 $namecloned = array();
1064 for ($i = 0; $i < $repeats; $i++) {
1065 foreach ($elementobjs as $elementobj){
1066 $elementclone = fullclone($elementobj);
1067 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1069 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1070 foreach ($elementclone->getElements() as $el) {
1071 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1073 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1076 $mform->addElement($elementclone);
1079 for ($i=0; $i<$repeats; $i++) {
1080 foreach ($options as $elementname => $elementoptions){
1081 $pos=strpos($elementname, '[');
1082 if ($pos!==FALSE){
1083 $realelementname = substr($elementname, 0, $pos)."[$i]";
1084 $realelementname .= substr($elementname, $pos);
1085 }else {
1086 $realelementname = $elementname."[$i]";
1088 foreach ($elementoptions as $option => $params){
1090 switch ($option){
1091 case 'default' :
1092 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1093 break;
1094 case 'helpbutton' :
1095 $params = array_merge(array($realelementname), $params);
1096 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1097 break;
1098 case 'disabledif' :
1099 foreach ($namecloned as $num => $name){
1100 if ($params[0] == $name){
1101 $params[0] = $params[0]."[$i]";
1102 break;
1105 $params = array_merge(array($realelementname), $params);
1106 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1107 break;
1108 case 'rule' :
1109 if (is_string($params)){
1110 $params = array(null, $params, null, 'client');
1112 $params = array_merge(array($realelementname), $params);
1113 call_user_func_array(array(&$mform, 'addRule'), $params);
1114 break;
1116 case 'type':
1117 $mform->setType($realelementname, $params);
1118 break;
1120 case 'expanded':
1121 $mform->setExpanded($realelementname, $params);
1122 break;
1124 case 'advanced' :
1125 $mform->setAdvanced($realelementname, $params);
1126 break;
1131 $mform->addElement('submit', $addfieldsname, $addstring);
1133 if (!$addbuttoninside) {
1134 $mform->closeHeaderBefore($addfieldsname);
1137 return $repeats;
1141 * Adds a link/button that controls the checked state of a group of checkboxes.
1143 * @param int $groupid The id of the group of advcheckboxes this element controls
1144 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1145 * @param array $attributes associative array of HTML attributes
1146 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1148 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1149 global $CFG, $PAGE;
1151 // Name of the controller button
1152 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1153 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1154 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1156 // Set the default text if none was specified
1157 if (empty($text)) {
1158 $text = get_string('selectallornone', 'form');
1161 $mform = $this->_form;
1162 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1163 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1165 $newselectvalue = $selectvalue;
1166 if (is_null($selectvalue)) {
1167 $newselectvalue = $originalValue;
1168 } else if (!is_null($contollerbutton)) {
1169 $newselectvalue = (int) !$selectvalue;
1171 // set checkbox state depending on orignal/submitted value by controoler button
1172 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1173 foreach ($mform->_elements as $element) {
1174 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1175 $element->getAttribute('class') == $checkboxgroupclass &&
1176 !$element->isFrozen()) {
1177 $mform->setConstants(array($element->getName() => $newselectvalue));
1182 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1183 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1184 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1186 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1187 array(
1188 array('groupid' => $groupid,
1189 'checkboxclass' => $checkboxgroupclass,
1190 'checkboxcontroller' => $checkboxcontrollerparam,
1191 'controllerbutton' => $checkboxcontrollername)
1195 require_once("$CFG->libdir/form/submit.php");
1196 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1197 $mform->addElement($submitlink);
1198 $mform->registerNoSubmitButton($checkboxcontrollername);
1199 $mform->setDefault($checkboxcontrollername, $text);
1203 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1204 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1205 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1206 * get data with get_data().
1208 * @param bool $cancel whether to show cancel button, default true
1209 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1211 function add_action_buttons($cancel = true, $submitlabel=null){
1212 if (is_null($submitlabel)){
1213 $submitlabel = get_string('savechanges');
1215 $mform =& $this->_form;
1216 if ($cancel){
1217 //when two elements we need a group
1218 $buttonarray=array();
1219 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1220 $buttonarray[] = &$mform->createElement('cancel');
1221 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1222 $mform->closeHeaderBefore('buttonar');
1223 } else {
1224 //no group needed
1225 $mform->addElement('submit', 'submitbutton', $submitlabel);
1226 $mform->closeHeaderBefore('submitbutton');
1231 * Adds an initialisation call for a standard JavaScript enhancement.
1233 * This function is designed to add an initialisation call for a JavaScript
1234 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1236 * Current options:
1237 * - Selectboxes
1238 * - smartselect: Turns a nbsp indented select box into a custom drop down
1239 * control that supports multilevel and category selection.
1240 * $enhancement = 'smartselect';
1241 * $options = array('selectablecategories' => true|false)
1243 * @since Moodle 2.0
1244 * @param string|element $element form element for which Javascript needs to be initalized
1245 * @param string $enhancement which init function should be called
1246 * @param array $options options passed to javascript
1247 * @param array $strings strings for javascript
1249 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1250 global $PAGE;
1251 if (is_string($element)) {
1252 $element = $this->_form->getElement($element);
1254 if (is_object($element)) {
1255 $element->_generateId();
1256 $elementid = $element->getAttribute('id');
1257 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1258 if (is_array($strings)) {
1259 foreach ($strings as $string) {
1260 if (is_array($string)) {
1261 call_user_method_array('string_for_js', $PAGE->requires, $string);
1262 } else {
1263 $PAGE->requires->string_for_js($string, 'moodle');
1271 * Returns a JS module definition for the mforms JS
1273 * @return array
1275 public static function get_js_module() {
1276 global $CFG;
1277 return array(
1278 'name' => 'mform',
1279 'fullpath' => '/lib/form/form.js',
1280 'requires' => array('base', 'node')
1285 * Detects elements with missing setType() declerations.
1287 * Finds elements in the form which should a PARAM_ type set and throws a
1288 * developer debug warning for any elements without it. This is to reduce the
1289 * risk of potential security issues by developers mistakenly forgetting to set
1290 * the type.
1292 * @return void
1294 private function detectMissingSetType() {
1295 global $CFG;
1297 if (!$CFG->debugdeveloper) {
1298 // Only for devs.
1299 return;
1302 $mform = $this->_form;
1303 foreach ($mform->_elements as $element) {
1304 $group = false;
1305 $elements = array($element);
1307 if ($element->getType() == 'group') {
1308 $group = $element;
1309 $elements = $element->getElements();
1312 foreach ($elements as $index => $element) {
1313 switch ($element->getType()) {
1314 case 'hidden':
1315 case 'text':
1316 case 'url':
1317 if ($group) {
1318 $name = $group->getElementName($index);
1319 } else {
1320 $name = $element->getName();
1322 $key = $name;
1323 $found = array_key_exists($key, $mform->_types);
1324 // For repeated elements we need to look for
1325 // the "main" type, not for the one present
1326 // on each repetition. All the stuff in formslib
1327 // (repeat_elements(), updateSubmission()... seems
1328 // to work that way.
1329 while (!$found && strrpos($key, '[') !== false) {
1330 $pos = strrpos($key, '[');
1331 $key = substr($key, 0, $pos);
1332 $found = array_key_exists($key, $mform->_types);
1334 if (!$found) {
1335 debugging("Did you remember to call setType() for '$name'? ".
1336 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1338 break;
1345 * Used by tests to simulate submitted form data submission from the user.
1347 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1348 * get_data.
1350 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1351 * global arrays after each test.
1353 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1354 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1355 * @param string $method 'post' or 'get', defaults to 'post'.
1356 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1357 * a different value here for some forms that are used more than once on the
1358 * same page.
1360 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1361 $formidentifier = null) {
1362 $_FILES = $simulatedsubmittedfiles;
1363 if ($formidentifier === null) {
1364 $formidentifier = get_called_class();
1366 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1367 $simulatedsubmitteddata['sesskey'] = sesskey();
1368 if (strtolower($method) === 'get') {
1369 $_GET = $simulatedsubmitteddata;
1370 } else {
1371 $_POST = $simulatedsubmitteddata;
1377 * MoodleQuickForm implementation
1379 * You never extend this class directly. The class methods of this class are available from
1380 * the private $this->_form property on moodleform and its children. You generally only
1381 * call methods on this class from within abstract methods that you override on moodleform such
1382 * as definition and definition_after_data
1384 * @package core_form
1385 * @category form
1386 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1387 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1389 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1390 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1391 var $_types = array();
1393 /** @var array dependent state for the element/'s */
1394 var $_dependencies = array();
1396 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1397 var $_noSubmitButtons=array();
1399 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1400 var $_cancelButtons=array();
1402 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1403 var $_advancedElements = array();
1406 * Array whose keys are element names and values are the desired collapsible state.
1407 * True for collapsed, False for expanded. If not present, set to default in
1408 * {@link self::accept()}.
1410 * @var array
1412 var $_collapsibleElements = array();
1415 * Whether to enable shortforms for this form
1417 * @var boolean
1419 var $_disableShortforms = false;
1421 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1422 protected $_use_form_change_checker = true;
1425 * The form name is derived from the class name of the wrapper minus the trailing form
1426 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1427 * @var string
1429 var $_formName = '';
1432 * String with the html for hidden params passed in as part of a moodle_url
1433 * object for the action. Output in the form.
1434 * @var string
1436 var $_pageparams = '';
1439 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1441 * @staticvar int $formcounter counts number of forms
1442 * @param string $formName Form's name.
1443 * @param string $method Form's method defaults to 'POST'
1444 * @param string|moodle_url $action Form's action
1445 * @param string $target (optional)Form's target defaults to none
1446 * @param mixed $attributes (optional)Extra attributes for <form> tag
1448 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1449 global $CFG, $OUTPUT;
1451 static $formcounter = 1;
1453 HTML_Common::HTML_Common($attributes);
1454 $target = empty($target) ? array() : array('target' => $target);
1455 $this->_formName = $formName;
1456 if (is_a($action, 'moodle_url')){
1457 $this->_pageparams = html_writer::input_hidden_params($action);
1458 $action = $action->out_omit_querystring();
1459 } else {
1460 $this->_pageparams = '';
1462 // No 'name' atttribute for form in xhtml strict :
1463 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1464 if (is_null($this->getAttribute('id'))) {
1465 $attributes['id'] = 'mform' . $formcounter;
1467 $formcounter++;
1468 $this->updateAttributes($attributes);
1470 // This is custom stuff for Moodle :
1471 $oldclass= $this->getAttribute('class');
1472 if (!empty($oldclass)){
1473 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1474 }else {
1475 $this->updateAttributes(array('class'=>'mform'));
1477 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1478 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1479 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1483 * Use this method to indicate an element in a form is an advanced field. If items in a form
1484 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1485 * form so the user can decide whether to display advanced form controls.
1487 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1489 * @param string $elementName group or element name (not the element name of something inside a group).
1490 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1492 function setAdvanced($elementName, $advanced = true) {
1493 if ($advanced){
1494 $this->_advancedElements[$elementName]='';
1495 } elseif (isset($this->_advancedElements[$elementName])) {
1496 unset($this->_advancedElements[$elementName]);
1501 * Use this method to indicate that the fieldset should be shown as expanded.
1502 * The method is applicable to header elements only.
1504 * @param string $headername header element name
1505 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1506 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1507 * the form was submitted.
1508 * @return void
1510 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1511 if (empty($headername)) {
1512 return;
1514 $element = $this->getElement($headername);
1515 if ($element->getType() != 'header') {
1516 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1517 return;
1519 if (!$headerid = $element->getAttribute('id')) {
1520 $element->_generateId();
1521 $headerid = $element->getAttribute('id');
1523 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1524 // See if the form has been submitted already.
1525 $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1526 if (!$ignoreuserstate && $formexpanded != -1) {
1527 // Override expanded state with the form variable.
1528 $expanded = $formexpanded;
1530 // Create the form element for storing expanded state.
1531 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1532 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1533 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1535 $this->_collapsibleElements[$headername] = !$expanded;
1539 * Use this method to add show more/less status element required for passing
1540 * over the advanced elements visibility status on the form submission.
1542 * @param string $headerName header element name.
1543 * @param boolean $showmore default false sets the advanced elements to be hidden.
1545 function addAdvancedStatusElement($headerid, $showmore=false){
1546 // Add extra hidden element to store advanced items state for each section.
1547 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1548 // See if we the form has been submitted already.
1549 $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1550 if (!$showmore && $formshowmore != -1) {
1551 // Override showmore state with the form variable.
1552 $showmore = $formshowmore;
1554 // Create the form element for storing advanced items state.
1555 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1556 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1557 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1562 * This function has been deprecated. Show advanced has been replaced by
1563 * "Show more.../Show less..." in the shortforms javascript module.
1565 * @deprecated since Moodle 2.5
1566 * @param bool $showadvancedNow if true will show advanced elements.
1568 function setShowAdvanced($showadvancedNow = null){
1569 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1573 * This function has been deprecated. Show advanced has been replaced by
1574 * "Show more.../Show less..." in the shortforms javascript module.
1576 * @deprecated since Moodle 2.5
1577 * @return bool (Always false)
1579 function getShowAdvanced(){
1580 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1581 return false;
1585 * Use this method to indicate that the form will not be using shortforms.
1587 * @param boolean $disable default true, controls if the shortforms are disabled.
1589 function setDisableShortforms ($disable = true) {
1590 $this->_disableShortforms = $disable;
1594 * Call this method if you don't want the formchangechecker JavaScript to be
1595 * automatically initialised for this form.
1597 public function disable_form_change_checker() {
1598 $this->_use_form_change_checker = false;
1602 * If you have called {@link disable_form_change_checker()} then you can use
1603 * this method to re-enable it. It is enabled by default, so normally you don't
1604 * need to call this.
1606 public function enable_form_change_checker() {
1607 $this->_use_form_change_checker = true;
1611 * @return bool whether this form should automatically initialise
1612 * formchangechecker for itself.
1614 public function is_form_change_checker_enabled() {
1615 return $this->_use_form_change_checker;
1619 * Accepts a renderer
1621 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1623 function accept(&$renderer) {
1624 if (method_exists($renderer, 'setAdvancedElements')){
1625 //Check for visible fieldsets where all elements are advanced
1626 //and mark these headers as advanced as well.
1627 //Also mark all elements in a advanced header as advanced.
1628 $stopFields = $renderer->getStopFieldSetElements();
1629 $lastHeader = null;
1630 $lastHeaderAdvanced = false;
1631 $anyAdvanced = false;
1632 $anyError = false;
1633 foreach (array_keys($this->_elements) as $elementIndex){
1634 $element =& $this->_elements[$elementIndex];
1636 // if closing header and any contained element was advanced then mark it as advanced
1637 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1638 if ($anyAdvanced && !is_null($lastHeader)) {
1639 $lastHeader->_generateId();
1640 $this->setAdvanced($lastHeader->getName());
1641 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1643 $lastHeaderAdvanced = false;
1644 unset($lastHeader);
1645 $lastHeader = null;
1646 } elseif ($lastHeaderAdvanced) {
1647 $this->setAdvanced($element->getName());
1650 if ($element->getType()=='header'){
1651 $lastHeader =& $element;
1652 $anyAdvanced = false;
1653 $anyError = false;
1654 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1655 } elseif (isset($this->_advancedElements[$element->getName()])){
1656 $anyAdvanced = true;
1657 if (isset($this->_errors[$element->getName()])) {
1658 $anyError = true;
1662 // the last header may not be closed yet...
1663 if ($anyAdvanced && !is_null($lastHeader)){
1664 $this->setAdvanced($lastHeader->getName());
1665 $lastHeader->_generateId();
1666 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1668 $renderer->setAdvancedElements($this->_advancedElements);
1670 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1672 // Count the number of sections.
1673 $headerscount = 0;
1674 foreach (array_keys($this->_elements) as $elementIndex){
1675 $element =& $this->_elements[$elementIndex];
1676 if ($element->getType() == 'header') {
1677 $headerscount++;
1681 $anyrequiredorerror = false;
1682 $headercounter = 0;
1683 $headername = null;
1684 foreach (array_keys($this->_elements) as $elementIndex){
1685 $element =& $this->_elements[$elementIndex];
1687 if ($element->getType() == 'header') {
1688 $headercounter++;
1689 $element->_generateId();
1690 $headername = $element->getName();
1691 $anyrequiredorerror = false;
1692 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1693 $anyrequiredorerror = true;
1694 } else {
1695 // Do not reset $anyrequiredorerror to false because we do not want any other element
1696 // in this header (fieldset) to possibly revert the state given.
1699 if ($element->getType() == 'header') {
1700 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1701 // By default the first section is always expanded, except if a state has already been set.
1702 $this->setExpanded($headername, true);
1703 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1704 // The second section is always expanded if the form only contains 2 sections),
1705 // except if a state has already been set.
1706 $this->setExpanded($headername, true);
1708 } else if ($anyrequiredorerror) {
1709 // If any error or required field are present within the header, we need to expand it.
1710 $this->setExpanded($headername, true, true);
1711 } else if (!isset($this->_collapsibleElements[$headername])) {
1712 // Define element as collapsed by default.
1713 $this->setExpanded($headername, false);
1717 // Pass the array to renderer object.
1718 $renderer->setCollapsibleElements($this->_collapsibleElements);
1720 parent::accept($renderer);
1724 * Adds one or more element names that indicate the end of a fieldset
1726 * @param string $elementName name of the element
1728 function closeHeaderBefore($elementName){
1729 $renderer =& $this->defaultRenderer();
1730 $renderer->addStopFieldsetElements($elementName);
1734 * Should be used for all elements of a form except for select, radio and checkboxes which
1735 * clean their own data.
1737 * @param string $elementname
1738 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1739 * {@link lib/moodlelib.php} for defined parameter types
1741 function setType($elementname, $paramtype) {
1742 $this->_types[$elementname] = $paramtype;
1746 * This can be used to set several types at once.
1748 * @param array $paramtypes types of parameters.
1749 * @see MoodleQuickForm::setType
1751 function setTypes($paramtypes) {
1752 $this->_types = $paramtypes + $this->_types;
1756 * Return the type(s) to use to clean an element.
1758 * In the case where the element has an array as a value, we will try to obtain a
1759 * type defined for that specific key, and recursively until done.
1761 * This method does not work reverse, you cannot pass a nested element and hoping to
1762 * fallback on the clean type of a parent. This method intends to be used with the
1763 * main element, which will generate child types if needed, not the other way around.
1765 * Example scenario:
1767 * You have defined a new repeated element containing a text field called 'foo'.
1768 * By default there will always be 2 occurence of 'foo' in the form. Even though
1769 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1770 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1771 * $mform->setType('foo[0]', PARAM_FLOAT).
1773 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1774 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1775 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1776 * get the default clean type returned (param $default).
1778 * @param string $elementname name of the element.
1779 * @param mixed $value value that should be cleaned.
1780 * @param int $default default constant value to be returned (PARAM_...)
1781 * @return string|array constant value or array of constant values (PARAM_...)
1783 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1784 $type = $default;
1785 if (array_key_exists($elementname, $this->_types)) {
1786 $type = $this->_types[$elementname];
1788 if (is_array($value)) {
1789 $default = $type;
1790 $type = array();
1791 foreach ($value as $subkey => $subvalue) {
1792 $typekey = "$elementname" . "[$subkey]";
1793 if (array_key_exists($typekey, $this->_types)) {
1794 $subtype = $this->_types[$typekey];
1795 } else {
1796 $subtype = $default;
1798 if (is_array($subvalue)) {
1799 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1800 } else {
1801 $type[$subkey] = $subtype;
1805 return $type;
1809 * Return the cleaned value using the passed type(s).
1811 * @param mixed $value value that has to be cleaned.
1812 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1813 * @return mixed cleaned up value.
1815 public function getCleanedValue($value, $type) {
1816 if (is_array($type) && is_array($value)) {
1817 foreach ($type as $key => $param) {
1818 $value[$key] = $this->getCleanedValue($value[$key], $param);
1820 } else if (!is_array($type) && !is_array($value)) {
1821 $value = clean_param($value, $type);
1822 } else if (!is_array($type) && is_array($value)) {
1823 $value = clean_param_array($value, $type, true);
1824 } else {
1825 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1827 return $value;
1831 * Updates submitted values
1833 * @param array $submission submitted values
1834 * @param array $files list of files
1836 function updateSubmission($submission, $files) {
1837 $this->_flagSubmitted = false;
1839 if (empty($submission)) {
1840 $this->_submitValues = array();
1841 } else {
1842 foreach ($submission as $key => $s) {
1843 $type = $this->getCleanType($key, $s);
1844 $submission[$key] = $this->getCleanedValue($s, $type);
1846 $this->_submitValues = $submission;
1847 $this->_flagSubmitted = true;
1850 if (empty($files)) {
1851 $this->_submitFiles = array();
1852 } else {
1853 $this->_submitFiles = $files;
1854 $this->_flagSubmitted = true;
1857 // need to tell all elements that they need to update their value attribute.
1858 foreach (array_keys($this->_elements) as $key) {
1859 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1864 * Returns HTML for required elements
1866 * @return string
1868 function getReqHTML(){
1869 return $this->_reqHTML;
1873 * Returns HTML for advanced elements
1875 * @return string
1877 function getAdvancedHTML(){
1878 return $this->_advancedHTML;
1882 * Initializes a default form value. Used to specify the default for a new entry where
1883 * no data is loaded in using moodleform::set_data()
1885 * note: $slashed param removed
1887 * @param string $elementName element name
1888 * @param mixed $defaultValue values for that element name
1890 function setDefault($elementName, $defaultValue){
1891 $this->setDefaults(array($elementName=>$defaultValue));
1895 * Add a help button to element, only one button per element is allowed.
1897 * This is new, simplified and preferable method of setting a help icon on form elements.
1898 * It uses the new $OUTPUT->help_icon().
1900 * Typically, you will provide the same identifier and the component as you have used for the
1901 * label of the element. The string identifier with the _help suffix added is then used
1902 * as the help string.
1904 * There has to be two strings defined:
1905 * 1/ get_string($identifier, $component) - the title of the help page
1906 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1908 * @since Moodle 2.0
1909 * @param string $elementname name of the element to add the item to
1910 * @param string $identifier help string identifier without _help suffix
1911 * @param string $component component name to look the help string in
1912 * @param string $linktext optional text to display next to the icon
1913 * @param bool $suppresscheck set to true if the element may not exist
1915 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1916 global $OUTPUT;
1917 if (array_key_exists($elementname, $this->_elementIndex)) {
1918 $element = $this->_elements[$this->_elementIndex[$elementname]];
1919 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1920 } else if (!$suppresscheck) {
1921 debugging(get_string('nonexistentformelements', 'form', $elementname));
1926 * Set constant value not overridden by _POST or _GET
1927 * note: this does not work for complex names with [] :-(
1929 * @param string $elname name of element
1930 * @param mixed $value
1932 function setConstant($elname, $value) {
1933 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1934 $element =& $this->getElement($elname);
1935 $element->onQuickFormEvent('updateValue', null, $this);
1939 * export submitted values
1941 * @param string $elementList list of elements in form
1942 * @return array
1944 function exportValues($elementList = null){
1945 $unfiltered = array();
1946 if (null === $elementList) {
1947 // iterate over all elements, calling their exportValue() methods
1948 foreach (array_keys($this->_elements) as $key) {
1949 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1950 $varname = $this->_elements[$key]->_attributes['name'];
1951 $value = '';
1952 // If we have a default value then export it.
1953 if (isset($this->_defaultValues[$varname])) {
1954 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
1956 } else {
1957 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1960 if (is_array($value)) {
1961 // This shit throws a bogus warning in PHP 4.3.x
1962 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1965 } else {
1966 if (!is_array($elementList)) {
1967 $elementList = array_map('trim', explode(',', $elementList));
1969 foreach ($elementList as $elementName) {
1970 $value = $this->exportValue($elementName);
1971 if (@PEAR::isError($value)) {
1972 return $value;
1974 //oh, stock QuickFOrm was returning array of arrays!
1975 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1979 if (is_array($this->_constantValues)) {
1980 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1982 return $unfiltered;
1986 * This is a bit of a hack, and it duplicates the code in
1987 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
1988 * reliably calling that code. (Think about date selectors, for example.)
1989 * @param string $name the element name.
1990 * @param mixed $value the fixed value to set.
1991 * @return mixed the appropriate array to add to the $unfiltered array.
1993 protected function prepare_fixed_value($name, $value) {
1994 if (null === $value) {
1995 return null;
1996 } else {
1997 if (!strpos($name, '[')) {
1998 return array($name => $value);
1999 } else {
2000 $valueAry = array();
2001 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2002 eval("\$valueAry$myIndex = \$value;");
2003 return $valueAry;
2009 * Adds a validation rule for the given field
2011 * If the element is in fact a group, it will be considered as a whole.
2012 * To validate grouped elements as separated entities,
2013 * use addGroupRule instead of addRule.
2015 * @param string $element Form element name
2016 * @param string $message Message to display for invalid data
2017 * @param string $type Rule type, use getRegisteredRules() to get types
2018 * @param string $format (optional)Required for extra rule data
2019 * @param string $validation (optional)Where to perform validation: "server", "client"
2020 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2021 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2023 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2025 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2026 if ($validation == 'client') {
2027 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2033 * Adds a validation rule for the given group of elements
2035 * Only groups with a name can be assigned a validation rule
2036 * Use addGroupRule when you need to validate elements inside the group.
2037 * Use addRule if you need to validate the group as a whole. In this case,
2038 * the same rule will be applied to all elements in the group.
2039 * Use addRule if you need to validate the group against a function.
2041 * @param string $group Form group name
2042 * @param array|string $arg1 Array for multiple elements or error message string for one element
2043 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2044 * @param string $format (optional)Required for extra rule data
2045 * @param int $howmany (optional)How many valid elements should be in the group
2046 * @param string $validation (optional)Where to perform validation: "server", "client"
2047 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2049 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2051 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2052 if (is_array($arg1)) {
2053 foreach ($arg1 as $rules) {
2054 foreach ($rules as $rule) {
2055 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2057 if ('client' == $validation) {
2058 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2062 } elseif (is_string($arg1)) {
2064 if ($validation == 'client') {
2065 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2071 * Returns the client side validation script
2073 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2074 * and slightly modified to run rules per-element
2075 * Needed to override this because of an error with client side validation of grouped elements.
2077 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2079 function getValidationScript()
2081 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
2082 return '';
2085 include_once('HTML/QuickForm/RuleRegistry.php');
2086 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2087 $test = array();
2088 $js_escape = array(
2089 "\r" => '\r',
2090 "\n" => '\n',
2091 "\t" => '\t',
2092 "'" => "\\'",
2093 '"' => '\"',
2094 '\\' => '\\\\'
2097 foreach ($this->_rules as $elementName => $rules) {
2098 foreach ($rules as $rule) {
2099 if ('client' == $rule['validation']) {
2100 unset($element); //TODO: find out how to properly initialize it
2102 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2103 $rule['message'] = strtr($rule['message'], $js_escape);
2105 if (isset($rule['group'])) {
2106 $group =& $this->getElement($rule['group']);
2107 // No JavaScript validation for frozen elements
2108 if ($group->isFrozen()) {
2109 continue 2;
2111 $elements =& $group->getElements();
2112 foreach (array_keys($elements) as $key) {
2113 if ($elementName == $group->getElementName($key)) {
2114 $element =& $elements[$key];
2115 break;
2118 } elseif ($dependent) {
2119 $element = array();
2120 $element[] =& $this->getElement($elementName);
2121 foreach ($rule['dependent'] as $elName) {
2122 $element[] =& $this->getElement($elName);
2124 } else {
2125 $element =& $this->getElement($elementName);
2127 // No JavaScript validation for frozen elements
2128 if (is_object($element) && $element->isFrozen()) {
2129 continue 2;
2130 } elseif (is_array($element)) {
2131 foreach (array_keys($element) as $key) {
2132 if ($element[$key]->isFrozen()) {
2133 continue 3;
2137 //for editor element, [text] is appended to the name.
2138 $fullelementname = $elementName;
2139 if ($element->getType() == 'editor') {
2140 $fullelementname .= '[text]';
2141 //Add format to rule as moodleform check which format is supported by browser
2142 //it is not set anywhere... So small hack to make sure we pass it down to quickform
2143 if (is_null($rule['format'])) {
2144 $rule['format'] = $element->getFormat();
2147 // Fix for bug displaying errors for elements in a group
2148 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2149 $test[$fullelementname][1]=$element;
2150 //end of fix
2155 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2156 // the form, and then that form field gets corrupted by the code that follows.
2157 unset($element);
2159 $js = '
2160 <script type="text/javascript">
2161 //<![CDATA[
2163 var skipClientValidation = false;
2165 function qf_errorHandler(element, _qfMsg) {
2166 div = element.parentNode;
2168 if ((div == undefined) || (element.name == undefined)) {
2169 //no checking can be done for undefined elements so let server handle it.
2170 return true;
2173 if (_qfMsg != \'\') {
2174 var errorSpan = document.getElementById(\'id_error_\'+element.name);
2175 if (!errorSpan) {
2176 errorSpan = document.createElement("span");
2177 errorSpan.id = \'id_error_\'+element.name;
2178 errorSpan.className = "error";
2179 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2180 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2181 document.getElementById(errorSpan.id).focus();
2184 while (errorSpan.firstChild) {
2185 errorSpan.removeChild(errorSpan.firstChild);
2188 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2190 if (div.className.substr(div.className.length - 6, 6) != " error"
2191 && div.className != "error") {
2192 div.className += " error";
2193 linebreak = document.createElement("br");
2194 linebreak.className = "error";
2195 linebreak.id = \'id_error_break_\'+element.name;
2196 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2199 return false;
2200 } else {
2201 var errorSpan = document.getElementById(\'id_error_\'+element.name);
2202 if (errorSpan) {
2203 errorSpan.parentNode.removeChild(errorSpan);
2205 var linebreak = document.getElementById(\'id_error_break_\'+element.name);
2206 if (linebreak) {
2207 linebreak.parentNode.removeChild(linebreak);
2210 if (div.className.substr(div.className.length - 6, 6) == " error") {
2211 div.className = div.className.substr(0, div.className.length - 6);
2212 } else if (div.className == "error") {
2213 div.className = "";
2216 return true;
2219 $validateJS = '';
2220 foreach ($test as $elementName => $jsandelement) {
2221 // Fix for bug displaying errors for elements in a group
2222 //unset($element);
2223 list($jsArr,$element)=$jsandelement;
2224 //end of fix
2225 $escapedElementName = preg_replace_callback(
2226 '/[_\[\]-]/',
2227 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2228 $elementName);
2229 $js .= '
2230 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
2231 if (undefined == element) {
2232 //required element was not found, then let form be submitted without client side validation
2233 return true;
2235 var value = \'\';
2236 var errFlag = new Array();
2237 var _qfGroups = {};
2238 var _qfMsg = \'\';
2239 var frm = element.parentNode;
2240 if ((undefined != element.name) && (frm != undefined)) {
2241 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2242 frm = frm.parentNode;
2244 ' . join("\n", $jsArr) . '
2245 return qf_errorHandler(element, _qfMsg);
2246 } else {
2247 //element name should be defined else error msg will not be displayed.
2248 return true;
2252 $validateJS .= '
2253 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
2254 if (!ret && !first_focus) {
2255 first_focus = true;
2256 document.getElementById(\'id_error_'.$elementName.'\').focus();
2260 // Fix for bug displaying errors for elements in a group
2261 //unset($element);
2262 //$element =& $this->getElement($elementName);
2263 //end of fix
2264 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
2265 $onBlur = $element->getAttribute('onBlur');
2266 $onChange = $element->getAttribute('onChange');
2267 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2268 'onChange' => $onChange . $valFunc));
2270 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2271 $js .= '
2272 function validate_' . $this->_formName . '(frm) {
2273 if (skipClientValidation) {
2274 return true;
2276 var ret = true;
2278 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2279 var first_focus = false;
2280 ' . $validateJS . ';
2281 return ret;
2283 //]]>
2284 </script>';
2285 return $js;
2286 } // end func getValidationScript
2289 * Sets default error message
2291 function _setDefaultRuleMessages(){
2292 foreach ($this->_rules as $field => $rulesarr){
2293 foreach ($rulesarr as $key => $rule){
2294 if ($rule['message']===null){
2295 $a=new stdClass();
2296 $a->format=$rule['format'];
2297 $str=get_string('err_'.$rule['type'], 'form', $a);
2298 if (strpos($str, '[[')!==0){
2299 $this->_rules[$field][$key]['message']=$str;
2307 * Get list of attributes which have dependencies
2309 * @return array
2311 function getLockOptionObject(){
2312 $result = array();
2313 foreach ($this->_dependencies as $dependentOn => $conditions){
2314 $result[$dependentOn] = array();
2315 foreach ($conditions as $condition=>$values) {
2316 $result[$dependentOn][$condition] = array();
2317 foreach ($values as $value=>$dependents) {
2318 $result[$dependentOn][$condition][$value] = array();
2319 $i = 0;
2320 foreach ($dependents as $dependent) {
2321 $elements = $this->_getElNamesRecursive($dependent);
2322 if (empty($elements)) {
2323 // probably element inside of some group
2324 $elements = array($dependent);
2326 foreach($elements as $element) {
2327 if ($element == $dependentOn) {
2328 continue;
2330 $result[$dependentOn][$condition][$value][] = $element;
2336 return array($this->getAttribute('id'), $result);
2340 * Get names of element or elements in a group.
2342 * @param HTML_QuickForm_group|element $element element group or element object
2343 * @return array
2345 function _getElNamesRecursive($element) {
2346 if (is_string($element)) {
2347 if (!$this->elementExists($element)) {
2348 return array();
2350 $element = $this->getElement($element);
2353 if (is_a($element, 'HTML_QuickForm_group')) {
2354 $elsInGroup = $element->getElements();
2355 $elNames = array();
2356 foreach ($elsInGroup as $elInGroup){
2357 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2358 // not sure if this would work - groups nested in groups
2359 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2360 } else {
2361 $elNames[] = $element->getElementName($elInGroup->getName());
2365 } else if (is_a($element, 'HTML_QuickForm_header')) {
2366 return array();
2368 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2369 return array();
2371 } else if (method_exists($element, 'getPrivateName') &&
2372 !($element instanceof HTML_QuickForm_advcheckbox)) {
2373 // The advcheckbox element implements a method called getPrivateName,
2374 // but in a way that is not compatible with the generic API, so we
2375 // have to explicitly exclude it.
2376 return array($element->getPrivateName());
2378 } else {
2379 $elNames = array($element->getName());
2382 return $elNames;
2386 * Adds a dependency for $elementName which will be disabled if $condition is met.
2387 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2388 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2389 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2390 * of the $dependentOn element is $condition (such as equal) to $value.
2392 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2393 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2394 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2396 * @param string $elementName the name of the element which will be disabled
2397 * @param string $dependentOn the name of the element whose state will be checked for condition
2398 * @param string $condition the condition to check
2399 * @param mixed $value used in conjunction with condition.
2401 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2402 // Multiple selects allow for a multiple selection, we transform the array to string here as
2403 // an array cannot be used as a key in an associative array.
2404 if (is_array($value)) {
2405 $value = implode('|', $value);
2407 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2408 $this->_dependencies[$dependentOn] = array();
2410 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2411 $this->_dependencies[$dependentOn][$condition] = array();
2413 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2414 $this->_dependencies[$dependentOn][$condition][$value] = array();
2416 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2420 * Registers button as no submit button
2422 * @param string $buttonname name of the button
2424 function registerNoSubmitButton($buttonname){
2425 $this->_noSubmitButtons[]=$buttonname;
2429 * Checks if button is a no submit button, i.e it doesn't submit form
2431 * @param string $buttonname name of the button to check
2432 * @return bool
2434 function isNoSubmitButton($buttonname){
2435 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2439 * Registers a button as cancel button
2441 * @param string $addfieldsname name of the button
2443 function _registerCancelButton($addfieldsname){
2444 $this->_cancelButtons[]=$addfieldsname;
2448 * Displays elements without HTML input tags.
2449 * This method is different to freeze() in that it makes sure no hidden
2450 * elements are included in the form.
2451 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2453 * This function also removes all previously defined rules.
2455 * @param string|array $elementList array or string of element(s) to be frozen
2456 * @return object|bool if element list is not empty then return error object, else true
2458 function hardFreeze($elementList=null)
2460 if (!isset($elementList)) {
2461 $this->_freezeAll = true;
2462 $elementList = array();
2463 } else {
2464 if (!is_array($elementList)) {
2465 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2467 $elementList = array_flip($elementList);
2470 foreach (array_keys($this->_elements) as $key) {
2471 $name = $this->_elements[$key]->getName();
2472 if ($this->_freezeAll || isset($elementList[$name])) {
2473 $this->_elements[$key]->freeze();
2474 $this->_elements[$key]->setPersistantFreeze(false);
2475 unset($elementList[$name]);
2477 // remove all rules
2478 $this->_rules[$name] = array();
2479 // if field is required, remove the rule
2480 $unset = array_search($name, $this->_required);
2481 if ($unset !== false) {
2482 unset($this->_required[$unset]);
2487 if (!empty($elementList)) {
2488 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);
2490 return true;
2494 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2496 * This function also removes all previously defined rules of elements it freezes.
2498 * @throws HTML_QuickForm_Error
2499 * @param array $elementList array or string of element(s) not to be frozen
2500 * @return bool returns true
2502 function hardFreezeAllVisibleExcept($elementList)
2504 $elementList = array_flip($elementList);
2505 foreach (array_keys($this->_elements) as $key) {
2506 $name = $this->_elements[$key]->getName();
2507 $type = $this->_elements[$key]->getType();
2509 if ($type == 'hidden'){
2510 // leave hidden types as they are
2511 } elseif (!isset($elementList[$name])) {
2512 $this->_elements[$key]->freeze();
2513 $this->_elements[$key]->setPersistantFreeze(false);
2515 // remove all rules
2516 $this->_rules[$name] = array();
2517 // if field is required, remove the rule
2518 $unset = array_search($name, $this->_required);
2519 if ($unset !== false) {
2520 unset($this->_required[$unset]);
2524 return true;
2528 * Tells whether the form was already submitted
2530 * This is useful since the _submitFiles and _submitValues arrays
2531 * may be completely empty after the trackSubmit value is removed.
2533 * @return bool
2535 function isSubmitted()
2537 return parent::isSubmitted() && (!$this->isFrozen());
2542 * MoodleQuickForm renderer
2544 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2545 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2547 * Stylesheet is part of standard theme and should be automatically included.
2549 * @package core_form
2550 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2553 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2555 /** @var array Element template array */
2556 var $_elementTemplates;
2559 * Template used when opening a hidden fieldset
2560 * (i.e. a fieldset that is opened when there is no header element)
2561 * @var string
2563 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2565 /** @var string Header Template string */
2566 var $_headerTemplate =
2567 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2569 /** @var string Template used when opening a fieldset */
2570 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id} {aria-live}>";
2572 /** @var string Template used when closing a fieldset */
2573 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2575 /** @var string Required Note template string */
2576 var $_requiredNoteTemplate =
2577 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2580 * Collapsible buttons string template.
2582 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2583 * until the Javascript has been fully loaded.
2585 * @var string
2587 var $_collapseButtonsTemplate =
2588 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2591 * Array whose keys are element names. If the key exists this is a advanced element
2593 * @var array
2595 var $_advancedElements = array();
2598 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2600 * @var array
2602 var $_collapsibleElements = array();
2605 * @var string Contains the collapsible buttons to add to the form.
2607 var $_collapseButtons = '';
2610 * Constructor
2612 function MoodleQuickForm_Renderer(){
2613 // switch next two lines for ol li containers for form items.
2614 // $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>');
2615 $this->_elementTemplates = array(
2616 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}" {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">{error}</span><br /><!-- END error -->{element}</div></div>',
2618 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2620 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}"><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">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2622 'static'=>"\n\t\t".'<div class="fitem {advanced}"><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">{error}</span><br /><!-- END error -->{element}&nbsp;</div></div>',
2624 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2626 'nodisplay'=>'');
2628 parent::HTML_QuickForm_Renderer_Tableless();
2632 * Set element's as adavance element
2634 * @param array $elements form elements which needs to be grouped as advance elements.
2636 function setAdvancedElements($elements){
2637 $this->_advancedElements = $elements;
2641 * Setting collapsible elements
2643 * @param array $elements
2645 function setCollapsibleElements($elements) {
2646 $this->_collapsibleElements = $elements;
2650 * What to do when starting the form
2652 * @param MoodleQuickForm $form reference of the form
2654 function startForm(&$form){
2655 global $PAGE;
2656 $this->_reqHTML = $form->getReqHTML();
2657 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2658 $this->_advancedHTML = $form->getAdvancedHTML();
2659 $this->_collapseButtons = '';
2660 $formid = $form->getAttribute('id');
2661 parent::startForm($form);
2662 if ($form->isFrozen()){
2663 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2664 } else {
2665 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2666 $this->_hiddenHtml .= $form->_pageparams;
2669 if ($form->is_form_change_checker_enabled()) {
2670 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2671 'M.core_formchangechecker.init',
2672 array(array(
2673 'formid' => $formid
2676 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2678 if (!empty($this->_collapsibleElements)) {
2679 if (count($this->_collapsibleElements) > 1) {
2680 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2681 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2682 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2684 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2686 if (!empty($this->_advancedElements)){
2687 $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2688 $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2693 * Create advance group of elements
2695 * @param object $group Passed by reference
2696 * @param bool $required if input is required field
2697 * @param string $error error message to display
2699 function startGroup(&$group, $required, $error){
2700 // Make sure the element has an id.
2701 $group->_generateId();
2703 if (method_exists($group, 'getElementTemplateType')){
2704 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2705 }else{
2706 $html = $this->_elementTemplates['default'];
2710 if (isset($this->_advancedElements[$group->getName()])){
2711 $html =str_replace(' {advanced}', ' advanced', $html);
2712 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2713 } else {
2714 $html =str_replace(' {advanced}', '', $html);
2715 $html =str_replace('{advancedimg}', '', $html);
2717 if (method_exists($group, 'getHelpButton')){
2718 $html =str_replace('{help}', $group->getHelpButton(), $html);
2719 }else{
2720 $html =str_replace('{help}', '', $html);
2722 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2723 $html =str_replace('{name}', $group->getName(), $html);
2724 $html =str_replace('{type}', 'fgroup', $html);
2726 $this->_templates[$group->getName()]=$html;
2727 // Fix for bug in tableless quickforms that didn't allow you to stop a
2728 // fieldset before a group of elements.
2729 // if the element name indicates the end of a fieldset, close the fieldset
2730 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2731 && $this->_fieldsetsOpen > 0
2733 $this->_html .= $this->_closeFieldsetTemplate;
2734 $this->_fieldsetsOpen--;
2736 parent::startGroup($group, $required, $error);
2740 * Renders element
2742 * @param HTML_QuickForm_element $element element
2743 * @param bool $required if input is required field
2744 * @param string $error error message to display
2746 function renderElement(&$element, $required, $error){
2747 // Make sure the element has an id.
2748 $element->_generateId();
2750 //adding stuff to place holders in template
2751 //check if this is a group element first
2752 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2753 // so it gets substitutions for *each* element
2754 $html = $this->_groupElementTemplate;
2756 elseif (method_exists($element, 'getElementTemplateType')){
2757 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2758 }else{
2759 $html = $this->_elementTemplates['default'];
2761 if (isset($this->_advancedElements[$element->getName()])){
2762 $html = str_replace(' {advanced}', ' advanced', $html);
2763 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2764 } else {
2765 $html = str_replace(' {advanced}', '', $html);
2766 $html = str_replace(' {aria-live}', '', $html);
2768 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2769 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2770 } else {
2771 $html =str_replace('{advancedimg}', '', $html);
2773 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2774 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2775 $html =str_replace('{name}', $element->getName(), $html);
2776 if (method_exists($element, 'getHelpButton')){
2777 $html = str_replace('{help}', $element->getHelpButton(), $html);
2778 }else{
2779 $html = str_replace('{help}', '', $html);
2782 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2783 $this->_groupElementTemplate = $html;
2785 elseif (!isset($this->_templates[$element->getName()])) {
2786 $this->_templates[$element->getName()] = $html;
2789 parent::renderElement($element, $required, $error);
2793 * Called when visiting a form, after processing all form elements
2794 * Adds required note, form attributes, validation javascript and form content.
2796 * @global moodle_page $PAGE
2797 * @param moodleform $form Passed by reference
2799 function finishForm(&$form){
2800 global $PAGE;
2801 if ($form->isFrozen()){
2802 $this->_hiddenHtml = '';
2804 parent::finishForm($form);
2805 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2806 if (!$form->isFrozen()) {
2807 $args = $form->getLockOptionObject();
2808 if (count($args[1]) > 0) {
2809 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2814 * Called when visiting a header element
2816 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2817 * @global moodle_page $PAGE
2819 function renderHeader(&$header) {
2820 global $PAGE;
2822 $header->_generateId();
2823 $name = $header->getName();
2825 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2826 if (is_null($header->_text)) {
2827 $header_html = '';
2828 } elseif (!empty($name) && isset($this->_templates[$name])) {
2829 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2830 } else {
2831 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2834 if ($this->_fieldsetsOpen > 0) {
2835 $this->_html .= $this->_closeFieldsetTemplate;
2836 $this->_fieldsetsOpen--;
2839 // Define collapsible classes for fieldsets.
2840 $arialive = '';
2841 $fieldsetclasses = array('clearfix');
2842 if (isset($this->_collapsibleElements[$header->getName()])) {
2843 $fieldsetclasses[] = 'collapsible';
2844 $arialive = 'aria-live="polite"';
2845 if ($this->_collapsibleElements[$header->getName()]) {
2846 $fieldsetclasses[] = 'collapsed';
2850 if (isset($this->_advancedElements[$name])){
2851 $fieldsetclasses[] = 'containsadvancedelements';
2854 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2855 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
2856 $openFieldsetTemplate = str_replace('{aria-live}', $arialive, $openFieldsetTemplate);
2858 $this->_html .= $openFieldsetTemplate . $header_html;
2859 $this->_fieldsetsOpen++;
2863 * Return Array of element names that indicate the end of a fieldset
2865 * @return array
2867 function getStopFieldsetElements(){
2868 return $this->_stopFieldsetElements;
2873 * Required elements validation
2875 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2877 * @package core_form
2878 * @category form
2879 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2880 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2882 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2884 * Checks if an element is not empty.
2885 * This is a server-side validation, it works for both text fields and editor fields
2887 * @param string $value Value to check
2888 * @param int|string|array $options Not used yet
2889 * @return bool true if value is not empty
2891 function validate($value, $options = null) {
2892 global $CFG;
2893 if (is_array($value) && array_key_exists('text', $value)) {
2894 $value = $value['text'];
2896 if (is_array($value)) {
2897 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2898 $value = implode('', $value);
2900 $stripvalues = array(
2901 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2902 '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
2904 if (!empty($CFG->strictformsrequired)) {
2905 $value = preg_replace($stripvalues, '', (string)$value);
2907 if ((string)$value == '') {
2908 return false;
2910 return true;
2914 * This function returns Javascript code used to build client-side validation.
2915 * It checks if an element is not empty.
2917 * @param int $format format of data which needs to be validated.
2918 * @return array
2920 function getValidationScript($format = null) {
2921 global $CFG;
2922 if (!empty($CFG->strictformsrequired)) {
2923 if (!empty($format) && $format == FORMAT_HTML) {
2924 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2925 } else {
2926 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2928 } else {
2929 return array('', "{jsVar} == ''");
2935 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2936 * @name $_HTML_QuickForm_default_renderer
2938 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2940 /** Please keep this list in alphabetical order. */
2941 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2942 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2943 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2944 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2945 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2946 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2947 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2948 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2949 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2950 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2951 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2952 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2953 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2954 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2955 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2956 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2957 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
2958 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2959 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2960 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2961 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2962 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2963 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2964 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2965 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2966 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2967 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2968 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2969 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2970 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2971 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2972 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2973 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2974 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2975 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2976 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2978 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");