Merge branch 'wip-mdl-52066-m28' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / lib / formslib.php
blobfa17e6c79fb39d1eee227d4b824e02b03f084940
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
20 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
21 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
22 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
23 * and validation.
25 * See examples of use of this library in course/edit.php and course/edit_form.php
27 * A few notes :
28 * form definition is used for both printing of form and processing and should be the same
29 * for both or you may lose some submitted data which won't be let through.
30 * you should be using setType for every form element except select, radio or checkbox
31 * elements, these elements clean themselves.
33 * @package core_form
34 * @copyright 2006 Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /** setup.php includes our hacked pear libs first */
41 require_once 'HTML/QuickForm.php';
42 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43 require_once 'HTML/QuickForm/Renderer/Tableless.php';
44 require_once 'HTML/QuickForm/Rule.php';
46 require_once $CFG->libdir.'/filelib.php';
48 /**
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
53 /**
54 * Callback called when PEAR throws an error
56 * @param PEAR_Error $error
58 function pear_handle_error($error){
59 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
60 echo '<br /> <strong>Backtrace </strong>:';
61 print_object($error->backtrace);
64 if ($CFG->debugdeveloper) {
65 //TODO: this is a wrong place to init PEAR!
66 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
67 $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
70 /**
71 * Initalize javascript for date type form element
73 * @staticvar bool $done make sure it gets initalize once.
74 * @global moodle_page $PAGE
76 function form_init_date_js() {
77 global $PAGE;
78 static $done = false;
79 if (!$done) {
80 $calendar = \core_calendar\type_factory::get_calendar_instance();
81 $module = 'moodle-form-dateselector';
82 $function = 'M.form.dateselector.init_date_selectors';
83 $config = array(array(
84 'firstdayofweek' => $calendar->get_starting_weekday(),
85 'mon' => date_format_string(strtotime("Monday"), '%a', 99),
86 'tue' => date_format_string(strtotime("Tuesday"), '%a', 99),
87 'wed' => date_format_string(strtotime("Wednesday"), '%a', 99),
88 'thu' => date_format_string(strtotime("Thursday"), '%a', 99),
89 'fri' => date_format_string(strtotime("Friday"), '%a', 99),
90 'sat' => date_format_string(strtotime("Saturday"), '%a', 99),
91 'sun' => date_format_string(strtotime("Sunday"), '%a', 99),
92 'january' => date_format_string(strtotime("January 1"), '%B', 99),
93 'february' => date_format_string(strtotime("February 1"), '%B', 99),
94 'march' => date_format_string(strtotime("March 1"), '%B', 99),
95 'april' => date_format_string(strtotime("April 1"), '%B', 99),
96 'may' => date_format_string(strtotime("May 1"), '%B', 99),
97 'june' => date_format_string(strtotime("June 1"), '%B', 99),
98 'july' => date_format_string(strtotime("July 1"), '%B', 99),
99 'august' => date_format_string(strtotime("August 1"), '%B', 99),
100 'september' => date_format_string(strtotime("September 1"), '%B', 99),
101 'october' => date_format_string(strtotime("October 1"), '%B', 99),
102 'november' => date_format_string(strtotime("November 1"), '%B', 99),
103 'december' => date_format_string(strtotime("December 1"), '%B', 99)
105 $PAGE->requires->yui_module($module, $function, $config);
106 $done = true;
111 * Wrapper that separates quickforms syntax from moodle code
113 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
114 * use this class you should write a class definition which extends this class or a more specific
115 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
117 * You will write your own definition() method which performs the form set up.
119 * @package core_form
120 * @copyright 2006 Jamie Pratt <me@jamiep.org>
121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
122 * @todo MDL-19380 rethink the file scanning
124 abstract class moodleform {
125 /** @var string name of the form */
126 protected $_formname; // form name
128 /** @var MoodleQuickForm quickform object definition */
129 protected $_form;
131 /** @var array globals workaround */
132 protected $_customdata;
134 /** @var object definition_after_data executed flag */
135 protected $_definition_finalized = false;
138 * The constructor function calls the abstract function definition() and it will then
139 * process and clean and attempt to validate incoming data.
141 * It will call your custom validate method to validate data and will also check any rules
142 * you have specified in definition using addRule
144 * The name of the form (id attribute of the form) is automatically generated depending on
145 * the name you gave the class extending moodleform. You should call your class something
146 * like
148 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
149 * current url. If a moodle_url object then outputs params as hidden variables.
150 * @param mixed $customdata if your form defintion method needs access to data such as $course
151 * $cm, etc. to construct the form definition then pass it in this array. You can
152 * use globals for somethings.
153 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
154 * be merged and used as incoming data to the form.
155 * @param string $target target frame for form submission. You will rarely use this. Don't use
156 * it if you don't need to as the target attribute is deprecated in xhtml strict.
157 * @param mixed $attributes you can pass a string of html attributes here or an array.
158 * @param bool $editable
160 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
161 global $CFG, $FULLME;
162 // no standard mform in moodle should allow autocomplete with the exception of user signup
163 if (empty($attributes)) {
164 $attributes = array('autocomplete'=>'off');
165 } else if (is_array($attributes)) {
166 $attributes['autocomplete'] = 'off';
167 } else {
168 if (strpos($attributes, 'autocomplete') === false) {
169 $attributes .= ' autocomplete="off" ';
173 if (empty($action)){
174 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
175 $action = strip_querystring($FULLME);
176 if (!empty($CFG->sslproxy)) {
177 // return only https links when using SSL proxy
178 $action = preg_replace('/^http:/', 'https:', $action, 1);
180 //TODO: use following instead of FULLME - see MDL-33015
181 //$action = strip_querystring(qualified_me());
183 // Assign custom data first, so that get_form_identifier can use it.
184 $this->_customdata = $customdata;
185 $this->_formname = $this->get_form_identifier();
187 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
188 if (!$editable){
189 $this->_form->hardFreeze();
192 // HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
193 $element = $this->_form->addElement('hidden');
194 $element->setType('password');
196 $this->definition();
198 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
199 $this->_form->setType('sesskey', PARAM_RAW);
200 $this->_form->setDefault('sesskey', sesskey());
201 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
202 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
203 $this->_form->setDefault('_qf__'.$this->_formname, 1);
204 $this->_form->_setDefaultRuleMessages();
206 // we have to know all input types before processing submission ;-)
207 $this->_process_submission($method);
211 * It should returns unique identifier for the form.
212 * Currently it will return class name, but in case two same forms have to be
213 * rendered on same page then override function to get unique form identifier.
214 * e.g This is used on multiple self enrollments page.
216 * @return string form identifier.
218 protected function get_form_identifier() {
219 $class = get_class($this);
221 return preg_replace('/[^a-z0-9_]/i', '_', $class);
225 * To autofocus on first form element or first element with error.
227 * @param string $name if this is set then the focus is forced to a field with this name
228 * @return string javascript to select form element with first error or
229 * first element if no errors. Use this as a parameter
230 * when calling print_header
232 function focus($name=NULL) {
233 $form =& $this->_form;
234 $elkeys = array_keys($form->_elementIndex);
235 $error = false;
236 if (isset($form->_errors) && 0 != count($form->_errors)){
237 $errorkeys = array_keys($form->_errors);
238 $elkeys = array_intersect($elkeys, $errorkeys);
239 $error = true;
242 if ($error or empty($name)) {
243 $names = array();
244 while (empty($names) and !empty($elkeys)) {
245 $el = array_shift($elkeys);
246 $names = $form->_getElNamesRecursive($el);
248 if (!empty($names)) {
249 $name = array_shift($names);
253 $focus = '';
254 if (!empty($name)) {
255 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
258 return $focus;
262 * Internal method. Alters submitted data to be suitable for quickforms processing.
263 * Must be called when the form is fully set up.
265 * @param string $method name of the method which alters submitted data
267 function _process_submission($method) {
268 $submission = array();
269 if ($method == 'post') {
270 if (!empty($_POST)) {
271 $submission = $_POST;
273 } else {
274 $submission = $_GET;
275 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
278 // following trick is needed to enable proper sesskey checks when using GET forms
279 // the _qf__.$this->_formname serves as a marker that form was actually submitted
280 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
281 if (!confirm_sesskey()) {
282 print_error('invalidsesskey');
284 $files = $_FILES;
285 } else {
286 $submission = array();
287 $files = array();
289 $this->detectMissingSetType();
291 $this->_form->updateSubmission($submission, $files);
295 * Internal method - should not be used anywhere.
296 * @deprecated since 2.6
297 * @return array $_POST.
299 protected function _get_post_params() {
300 return $_POST;
304 * Internal method. Validates all old-style deprecated uploaded files.
305 * The new way is to upload files via repository api.
307 * @param array $files list of files to be validated
308 * @return bool|array Success or an array of errors
310 function _validate_files(&$files) {
311 global $CFG, $COURSE;
313 $files = array();
315 if (empty($_FILES)) {
316 // we do not need to do any checks because no files were submitted
317 // note: server side rules do not work for files - use custom verification in validate() instead
318 return true;
321 $errors = array();
322 $filenames = array();
324 // now check that we really want each file
325 foreach ($_FILES as $elname=>$file) {
326 $required = $this->_form->isElementRequired($elname);
328 if ($file['error'] == 4 and $file['size'] == 0) {
329 if ($required) {
330 $errors[$elname] = get_string('required');
332 unset($_FILES[$elname]);
333 continue;
336 if (!empty($file['error'])) {
337 $errors[$elname] = file_get_upload_error($file['error']);
338 unset($_FILES[$elname]);
339 continue;
342 if (!is_uploaded_file($file['tmp_name'])) {
343 // TODO: improve error message
344 $errors[$elname] = get_string('error');
345 unset($_FILES[$elname]);
346 continue;
349 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
350 // hmm, this file was not requested
351 unset($_FILES[$elname]);
352 continue;
355 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
357 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
358 if ($filename === '') {
359 // TODO: improve error message - wrong chars
360 $errors[$elname] = get_string('error');
361 unset($_FILES[$elname]);
362 continue;
364 if (in_array($filename, $filenames)) {
365 // TODO: improve error message - duplicate name
366 $errors[$elname] = get_string('error');
367 unset($_FILES[$elname]);
368 continue;
370 $filenames[] = $filename;
371 $_FILES[$elname]['name'] = $filename;
373 $files[$elname] = $_FILES[$elname]['tmp_name'];
376 // return errors if found
377 if (count($errors) == 0){
378 return true;
380 } else {
381 $files = array();
382 return $errors;
387 * Internal method. Validates filepicker and filemanager files if they are
388 * set as required fields. Also, sets the error message if encountered one.
390 * @return bool|array with errors
392 protected function validate_draft_files() {
393 global $USER;
394 $mform =& $this->_form;
396 $errors = array();
397 //Go through all the required elements and make sure you hit filepicker or
398 //filemanager element.
399 foreach ($mform->_rules as $elementname => $rules) {
400 $elementtype = $mform->getElementType($elementname);
401 //If element is of type filepicker then do validation
402 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
403 //Check if rule defined is required rule
404 foreach ($rules as $rule) {
405 if ($rule['type'] == 'required') {
406 $draftid = (int)$mform->getSubmitValue($elementname);
407 $fs = get_file_storage();
408 $context = context_user::instance($USER->id);
409 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
410 $errors[$elementname] = $rule['message'];
416 // Check all the filemanager elements to make sure they do not have too many
417 // files in them.
418 foreach ($mform->_elements as $element) {
419 if ($element->_type == 'filemanager') {
420 $maxfiles = $element->getMaxfiles();
421 if ($maxfiles > 0) {
422 $draftid = (int)$element->getValue();
423 $fs = get_file_storage();
424 $context = context_user::instance($USER->id);
425 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
426 if (count($files) > $maxfiles) {
427 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
432 if (empty($errors)) {
433 return true;
434 } else {
435 return $errors;
440 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
441 * form definition (new entry form); this function is used to load in data where values
442 * already exist and data is being edited (edit entry form).
444 * note: $slashed param removed
446 * @param stdClass|array $default_values object or array of default values
448 function set_data($default_values) {
449 if (is_object($default_values)) {
450 $default_values = (array)$default_values;
452 $this->_form->setDefaults($default_values);
456 * Check that form was submitted. Does not check validity of submitted data.
458 * @return bool true if form properly submitted
460 function is_submitted() {
461 return $this->_form->isSubmitted();
465 * Checks if button pressed is not for submitting the form
467 * @staticvar bool $nosubmit keeps track of no submit button
468 * @return bool
470 function no_submit_button_pressed(){
471 static $nosubmit = null; // one check is enough
472 if (!is_null($nosubmit)){
473 return $nosubmit;
475 $mform =& $this->_form;
476 $nosubmit = false;
477 if (!$this->is_submitted()){
478 return false;
480 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
481 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
482 $nosubmit = true;
483 break;
486 return $nosubmit;
491 * Check that form data is valid.
492 * You should almost always use this, rather than {@link validate_defined_fields}
494 * @return bool true if form data valid
496 function is_validated() {
497 //finalize the form definition before any processing
498 if (!$this->_definition_finalized) {
499 $this->_definition_finalized = true;
500 $this->definition_after_data();
503 return $this->validate_defined_fields();
507 * Validate the form.
509 * You almost always want to call {@link is_validated} instead of this
510 * because it calls {@link definition_after_data} first, before validating the form,
511 * which is what you want in 99% of cases.
513 * This is provided as a separate function for those special cases where
514 * you want the form validated before definition_after_data is called
515 * for example, to selectively add new elements depending on a no_submit_button press,
516 * but only when the form is valid when the no_submit_button is pressed,
518 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
519 * is NOT to validate the form when a no submit button has been pressed.
520 * pass true here to override this behaviour
522 * @return bool true if form data valid
524 function validate_defined_fields($validateonnosubmit=false) {
525 static $validated = null; // one validation is enough
526 $mform =& $this->_form;
527 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
528 return false;
529 } elseif ($validated === null) {
530 $internal_val = $mform->validate();
532 $files = array();
533 $file_val = $this->_validate_files($files);
534 //check draft files for validation and flag them if required files
535 //are not in draft area.
536 $draftfilevalue = $this->validate_draft_files();
538 if ($file_val !== true && $draftfilevalue !== true) {
539 $file_val = array_merge($file_val, $draftfilevalue);
540 } else if ($draftfilevalue !== true) {
541 $file_val = $draftfilevalue;
542 } //default is file_val, so no need to assign.
544 if ($file_val !== true) {
545 if (!empty($file_val)) {
546 foreach ($file_val as $element=>$msg) {
547 $mform->setElementError($element, $msg);
550 $file_val = false;
553 $data = $mform->exportValues();
554 $moodle_val = $this->validation($data, $files);
555 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
556 // non-empty array means errors
557 foreach ($moodle_val as $element=>$msg) {
558 $mform->setElementError($element, $msg);
560 $moodle_val = false;
562 } else {
563 // anything else means validation ok
564 $moodle_val = true;
567 $validated = ($internal_val and $moodle_val and $file_val);
569 return $validated;
573 * Return true if a cancel button has been pressed resulting in the form being submitted.
575 * @return bool true if a cancel button has been pressed
577 function is_cancelled(){
578 $mform =& $this->_form;
579 if ($mform->isSubmitted()){
580 foreach ($mform->_cancelButtons as $cancelbutton){
581 if (optional_param($cancelbutton, 0, PARAM_RAW)){
582 return true;
586 return false;
590 * Return submitted data if properly submitted or returns NULL if validation fails or
591 * if there is no submitted data.
593 * note: $slashed param removed
595 * @return object submitted data; NULL if not valid or not submitted or cancelled
597 function get_data() {
598 $mform =& $this->_form;
600 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
601 $data = $mform->exportValues();
602 unset($data['sesskey']); // we do not need to return sesskey
603 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
604 if (empty($data)) {
605 return NULL;
606 } else {
607 return (object)$data;
609 } else {
610 return NULL;
615 * Return submitted data without validation or NULL if there is no submitted data.
616 * note: $slashed param removed
618 * @return object submitted data; NULL if not submitted
620 function get_submitted_data() {
621 $mform =& $this->_form;
623 if ($this->is_submitted()) {
624 $data = $mform->exportValues();
625 unset($data['sesskey']); // we do not need to return sesskey
626 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
627 if (empty($data)) {
628 return NULL;
629 } else {
630 return (object)$data;
632 } else {
633 return NULL;
638 * Save verified uploaded files into directory. Upload process can be customised from definition()
640 * @deprecated since Moodle 2.0
641 * @todo MDL-31294 remove this api
642 * @see moodleform::save_stored_file()
643 * @see moodleform::save_file()
644 * @param string $destination path where file should be stored
645 * @return bool Always false
647 function save_files($destination) {
648 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
649 return false;
653 * Returns name of uploaded file.
655 * @param string $elname first element if null
656 * @return string|bool false in case of failure, string if ok
658 function get_new_filename($elname=null) {
659 global $USER;
661 if (!$this->is_submitted() or !$this->is_validated()) {
662 return false;
665 if (is_null($elname)) {
666 if (empty($_FILES)) {
667 return false;
669 reset($_FILES);
670 $elname = key($_FILES);
673 if (empty($elname)) {
674 return false;
677 $element = $this->_form->getElement($elname);
679 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
680 $values = $this->_form->exportValues($elname);
681 if (empty($values[$elname])) {
682 return false;
684 $draftid = $values[$elname];
685 $fs = get_file_storage();
686 $context = context_user::instance($USER->id);
687 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
688 return false;
690 $file = reset($files);
691 return $file->get_filename();
694 if (!isset($_FILES[$elname])) {
695 return false;
698 return $_FILES[$elname]['name'];
702 * Save file to standard filesystem
704 * @param string $elname name of element
705 * @param string $pathname full path name of file
706 * @param bool $override override file if exists
707 * @return bool success
709 function save_file($elname, $pathname, $override=false) {
710 global $USER;
712 if (!$this->is_submitted() or !$this->is_validated()) {
713 return false;
715 if (file_exists($pathname)) {
716 if ($override) {
717 if (!@unlink($pathname)) {
718 return false;
720 } else {
721 return false;
725 $element = $this->_form->getElement($elname);
727 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
728 $values = $this->_form->exportValues($elname);
729 if (empty($values[$elname])) {
730 return false;
732 $draftid = $values[$elname];
733 $fs = get_file_storage();
734 $context = context_user::instance($USER->id);
735 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
736 return false;
738 $file = reset($files);
740 return $file->copy_content_to($pathname);
742 } else if (isset($_FILES[$elname])) {
743 return copy($_FILES[$elname]['tmp_name'], $pathname);
746 return false;
750 * Returns a temporary file, do not forget to delete after not needed any more.
752 * @param string $elname name of the elmenet
753 * @return string|bool either string or false
755 function save_temp_file($elname) {
756 if (!$this->get_new_filename($elname)) {
757 return false;
759 if (!$dir = make_temp_directory('forms')) {
760 return false;
762 if (!$tempfile = tempnam($dir, 'tempup_')) {
763 return false;
765 if (!$this->save_file($elname, $tempfile, true)) {
766 // something went wrong
767 @unlink($tempfile);
768 return false;
771 return $tempfile;
775 * Get draft files of a form element
776 * This is a protected method which will be used only inside moodleforms
778 * @param string $elname name of element
779 * @return array|bool|null
781 protected function get_draft_files($elname) {
782 global $USER;
784 if (!$this->is_submitted()) {
785 return false;
788 $element = $this->_form->getElement($elname);
790 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
791 $values = $this->_form->exportValues($elname);
792 if (empty($values[$elname])) {
793 return false;
795 $draftid = $values[$elname];
796 $fs = get_file_storage();
797 $context = context_user::instance($USER->id);
798 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
799 return null;
801 return $files;
803 return null;
807 * Save file to local filesystem pool
809 * @param string $elname name of element
810 * @param int $newcontextid id of context
811 * @param string $newcomponent name of the component
812 * @param string $newfilearea name of file area
813 * @param int $newitemid item id
814 * @param string $newfilepath path of file where it get stored
815 * @param string $newfilename use specified filename, if not specified name of uploaded file used
816 * @param bool $overwrite overwrite file if exists
817 * @param int $newuserid new userid if required
818 * @return mixed stored_file object or false if error; may throw exception if duplicate found
820 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
821 $newfilename=null, $overwrite=false, $newuserid=null) {
822 global $USER;
824 if (!$this->is_submitted() or !$this->is_validated()) {
825 return false;
828 if (empty($newuserid)) {
829 $newuserid = $USER->id;
832 $element = $this->_form->getElement($elname);
833 $fs = get_file_storage();
835 if ($element instanceof MoodleQuickForm_filepicker) {
836 $values = $this->_form->exportValues($elname);
837 if (empty($values[$elname])) {
838 return false;
840 $draftid = $values[$elname];
841 $context = context_user::instance($USER->id);
842 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
843 return false;
845 $file = reset($files);
846 if (is_null($newfilename)) {
847 $newfilename = $file->get_filename();
850 if ($overwrite) {
851 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
852 if (!$oldfile->delete()) {
853 return false;
858 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
859 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
860 return $fs->create_file_from_storedfile($file_record, $file);
862 } else if (isset($_FILES[$elname])) {
863 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
865 if ($overwrite) {
866 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
867 if (!$oldfile->delete()) {
868 return false;
873 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
874 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
875 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
878 return false;
882 * Get content of uploaded file.
884 * @param string $elname name of file upload element
885 * @return string|bool false in case of failure, string if ok
887 function get_file_content($elname) {
888 global $USER;
890 if (!$this->is_submitted() or !$this->is_validated()) {
891 return false;
894 $element = $this->_form->getElement($elname);
896 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
897 $values = $this->_form->exportValues($elname);
898 if (empty($values[$elname])) {
899 return false;
901 $draftid = $values[$elname];
902 $fs = get_file_storage();
903 $context = context_user::instance($USER->id);
904 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
905 return false;
907 $file = reset($files);
909 return $file->get_content();
911 } else if (isset($_FILES[$elname])) {
912 return file_get_contents($_FILES[$elname]['tmp_name']);
915 return false;
919 * Print html form.
921 function display() {
922 //finalize the form definition if not yet done
923 if (!$this->_definition_finalized) {
924 $this->_definition_finalized = true;
925 $this->definition_after_data();
928 $this->_form->display();
932 * Renders the html form (same as display, but returns the result).
934 * Note that you can only output this rendered result once per page, as
935 * it contains IDs which must be unique.
937 * @return string HTML code for the form
939 public function render() {
940 ob_start();
941 $this->display();
942 $out = ob_get_contents();
943 ob_end_clean();
944 return $out;
948 * Form definition. Abstract method - always override!
950 protected abstract function definition();
953 * Dummy stub method - override if you need to setup the form depending on current
954 * values. This method is called after definition(), data submission and set_data().
955 * All form setup that is dependent on form values should go in here.
957 function definition_after_data(){
961 * Dummy stub method - override if you needed to perform some extra validation.
962 * If there are errors return array of errors ("fieldname"=>"error message"),
963 * otherwise true if ok.
965 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
967 * @param array $data array of ("fieldname"=>value) of submitted data
968 * @param array $files array of uploaded files "element_name"=>tmp_file_path
969 * @return array of "element_name"=>"error_description" if there are errors,
970 * or an empty array if everything is OK (true allowed for backwards compatibility too).
972 function validation($data, $files) {
973 return array();
977 * Helper used by {@link repeat_elements()}.
979 * @param int $i the index of this element.
980 * @param HTML_QuickForm_element $elementclone
981 * @param array $namecloned array of names
983 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
984 $name = $elementclone->getName();
985 $namecloned[] = $name;
987 if (!empty($name)) {
988 $elementclone->setName($name."[$i]");
991 if (is_a($elementclone, 'HTML_QuickForm_header')) {
992 $value = $elementclone->_text;
993 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
995 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
996 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
998 } else {
999 $value=$elementclone->getLabel();
1000 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1005 * Method to add a repeating group of elements to a form.
1007 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1008 * @param int $repeats no of times to repeat elements initially
1009 * @param array $options a nested array. The first array key is the element name.
1010 * the second array key is the type of option to set, and depend on that option,
1011 * the value takes different forms.
1012 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1013 * 'type' - PARAM_* type.
1014 * 'helpbutton' - array containing the helpbutton params.
1015 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1016 * 'rule' - array containing the addRule arguments after the element name.
1017 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1018 * 'advanced' - whether this element is hidden by 'Show more ...'.
1019 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1020 * @param string $addfieldsname name for button to add more fields
1021 * @param int $addfieldsno how many fields to add at a time
1022 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1023 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1024 * @return int no of repeats of element in this page
1026 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1027 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1028 if ($addstring===null){
1029 $addstring = get_string('addfields', 'form', $addfieldsno);
1030 } else {
1031 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1033 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1034 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1035 if (!empty($addfields)){
1036 $repeats += $addfieldsno;
1038 $mform =& $this->_form;
1039 $mform->registerNoSubmitButton($addfieldsname);
1040 $mform->addElement('hidden', $repeathiddenname, $repeats);
1041 $mform->setType($repeathiddenname, PARAM_INT);
1042 //value not to be overridden by submitted value
1043 $mform->setConstants(array($repeathiddenname=>$repeats));
1044 $namecloned = array();
1045 for ($i = 0; $i < $repeats; $i++) {
1046 foreach ($elementobjs as $elementobj){
1047 $elementclone = fullclone($elementobj);
1048 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1050 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1051 foreach ($elementclone->getElements() as $el) {
1052 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1054 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1057 $mform->addElement($elementclone);
1060 for ($i=0; $i<$repeats; $i++) {
1061 foreach ($options as $elementname => $elementoptions){
1062 $pos=strpos($elementname, '[');
1063 if ($pos!==FALSE){
1064 $realelementname = substr($elementname, 0, $pos)."[$i]";
1065 $realelementname .= substr($elementname, $pos);
1066 }else {
1067 $realelementname = $elementname."[$i]";
1069 foreach ($elementoptions as $option => $params){
1071 switch ($option){
1072 case 'default' :
1073 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1074 break;
1075 case 'helpbutton' :
1076 $params = array_merge(array($realelementname), $params);
1077 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1078 break;
1079 case 'disabledif' :
1080 foreach ($namecloned as $num => $name){
1081 if ($params[0] == $name){
1082 $params[0] = $params[0]."[$i]";
1083 break;
1086 $params = array_merge(array($realelementname), $params);
1087 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1088 break;
1089 case 'rule' :
1090 if (is_string($params)){
1091 $params = array(null, $params, null, 'client');
1093 $params = array_merge(array($realelementname), $params);
1094 call_user_func_array(array(&$mform, 'addRule'), $params);
1095 break;
1097 case 'type':
1098 $mform->setType($realelementname, $params);
1099 break;
1101 case 'expanded':
1102 $mform->setExpanded($realelementname, $params);
1103 break;
1105 case 'advanced' :
1106 $mform->setAdvanced($realelementname, $params);
1107 break;
1112 $mform->addElement('submit', $addfieldsname, $addstring);
1114 if (!$addbuttoninside) {
1115 $mform->closeHeaderBefore($addfieldsname);
1118 return $repeats;
1122 * Adds a link/button that controls the checked state of a group of checkboxes.
1124 * @param int $groupid The id of the group of advcheckboxes this element controls
1125 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1126 * @param array $attributes associative array of HTML attributes
1127 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1129 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1130 global $CFG, $PAGE;
1132 // Name of the controller button
1133 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1134 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1135 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1137 // Set the default text if none was specified
1138 if (empty($text)) {
1139 $text = get_string('selectallornone', 'form');
1142 $mform = $this->_form;
1143 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1144 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1146 $newselectvalue = $selectvalue;
1147 if (is_null($selectvalue)) {
1148 $newselectvalue = $originalValue;
1149 } else if (!is_null($contollerbutton)) {
1150 $newselectvalue = (int) !$selectvalue;
1152 // set checkbox state depending on orignal/submitted value by controoler button
1153 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1154 foreach ($mform->_elements as $element) {
1155 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1156 $element->getAttribute('class') == $checkboxgroupclass &&
1157 !$element->isFrozen()) {
1158 $mform->setConstants(array($element->getName() => $newselectvalue));
1163 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1164 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1165 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1167 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1168 array(
1169 array('groupid' => $groupid,
1170 'checkboxclass' => $checkboxgroupclass,
1171 'checkboxcontroller' => $checkboxcontrollerparam,
1172 'controllerbutton' => $checkboxcontrollername)
1176 require_once("$CFG->libdir/form/submit.php");
1177 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1178 $mform->addElement($submitlink);
1179 $mform->registerNoSubmitButton($checkboxcontrollername);
1180 $mform->setDefault($checkboxcontrollername, $text);
1184 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1185 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1186 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1187 * get data with get_data().
1189 * @param bool $cancel whether to show cancel button, default true
1190 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1192 function add_action_buttons($cancel = true, $submitlabel=null){
1193 if (is_null($submitlabel)){
1194 $submitlabel = get_string('savechanges');
1196 $mform =& $this->_form;
1197 if ($cancel){
1198 //when two elements we need a group
1199 $buttonarray=array();
1200 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1201 $buttonarray[] = &$mform->createElement('cancel');
1202 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1203 $mform->closeHeaderBefore('buttonar');
1204 } else {
1205 //no group needed
1206 $mform->addElement('submit', 'submitbutton', $submitlabel);
1207 $mform->closeHeaderBefore('submitbutton');
1212 * Adds an initialisation call for a standard JavaScript enhancement.
1214 * This function is designed to add an initialisation call for a JavaScript
1215 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1217 * Current options:
1218 * - Selectboxes
1219 * - smartselect: Turns a nbsp indented select box into a custom drop down
1220 * control that supports multilevel and category selection.
1221 * $enhancement = 'smartselect';
1222 * $options = array('selectablecategories' => true|false)
1224 * @since Moodle 2.0
1225 * @param string|element $element form element for which Javascript needs to be initalized
1226 * @param string $enhancement which init function should be called
1227 * @param array $options options passed to javascript
1228 * @param array $strings strings for javascript
1230 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1231 global $PAGE;
1232 if (is_string($element)) {
1233 $element = $this->_form->getElement($element);
1235 if (is_object($element)) {
1236 $element->_generateId();
1237 $elementid = $element->getAttribute('id');
1238 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1239 if (is_array($strings)) {
1240 foreach ($strings as $string) {
1241 if (is_array($string)) {
1242 call_user_method_array('string_for_js', $PAGE->requires, $string);
1243 } else {
1244 $PAGE->requires->string_for_js($string, 'moodle');
1252 * Returns a JS module definition for the mforms JS
1254 * @return array
1256 public static function get_js_module() {
1257 global $CFG;
1258 return array(
1259 'name' => 'mform',
1260 'fullpath' => '/lib/form/form.js',
1261 'requires' => array('base', 'node')
1266 * Detects elements with missing setType() declerations.
1268 * Finds elements in the form which should a PARAM_ type set and throws a
1269 * developer debug warning for any elements without it. This is to reduce the
1270 * risk of potential security issues by developers mistakenly forgetting to set
1271 * the type.
1273 * @return void
1275 private function detectMissingSetType() {
1276 global $CFG;
1278 if (!$CFG->debugdeveloper) {
1279 // Only for devs.
1280 return;
1283 $mform = $this->_form;
1284 foreach ($mform->_elements as $element) {
1285 $group = false;
1286 $elements = array($element);
1288 if ($element->getType() == 'group') {
1289 $group = $element;
1290 $elements = $element->getElements();
1293 foreach ($elements as $index => $element) {
1294 switch ($element->getType()) {
1295 case 'hidden':
1296 case 'text':
1297 case 'url':
1298 if ($group) {
1299 $name = $group->getElementName($index);
1300 } else {
1301 $name = $element->getName();
1303 $key = $name;
1304 $found = array_key_exists($key, $mform->_types);
1305 // For repeated elements we need to look for
1306 // the "main" type, not for the one present
1307 // on each repetition. All the stuff in formslib
1308 // (repeat_elements(), updateSubmission()... seems
1309 // to work that way.
1310 while (!$found && strrpos($key, '[') !== false) {
1311 $pos = strrpos($key, '[');
1312 $key = substr($key, 0, $pos);
1313 $found = array_key_exists($key, $mform->_types);
1315 if (!$found) {
1316 debugging("Did you remember to call setType() for '$name'? ".
1317 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1319 break;
1326 * Used by tests to simulate submitted form data submission from the user.
1328 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1329 * get_data.
1331 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1332 * global arrays after each test.
1334 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1335 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1336 * @param string $method 'post' or 'get', defaults to 'post'.
1337 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1338 * a different value here for some forms that are used more than once on the
1339 * same page.
1341 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1342 $formidentifier = null) {
1343 $_FILES = $simulatedsubmittedfiles;
1344 if ($formidentifier === null) {
1345 $formidentifier = get_called_class();
1347 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1348 $simulatedsubmitteddata['sesskey'] = sesskey();
1349 if (strtolower($method) === 'get') {
1350 $_GET = $simulatedsubmitteddata;
1351 } else {
1352 $_POST = $simulatedsubmitteddata;
1358 * MoodleQuickForm implementation
1360 * You never extend this class directly. The class methods of this class are available from
1361 * the private $this->_form property on moodleform and its children. You generally only
1362 * call methods on this class from within abstract methods that you override on moodleform such
1363 * as definition and definition_after_data
1365 * @package core_form
1366 * @category form
1367 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1368 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1370 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1371 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1372 var $_types = array();
1374 /** @var array dependent state for the element/'s */
1375 var $_dependencies = array();
1377 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1378 var $_noSubmitButtons=array();
1380 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1381 var $_cancelButtons=array();
1383 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1384 var $_advancedElements = array();
1387 * Array whose keys are element names and values are the desired collapsible state.
1388 * True for collapsed, False for expanded. If not present, set to default in
1389 * {@link self::accept()}.
1391 * @var array
1393 var $_collapsibleElements = array();
1396 * Whether to enable shortforms for this form
1398 * @var boolean
1400 var $_disableShortforms = false;
1402 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1403 protected $_use_form_change_checker = true;
1406 * The form name is derived from the class name of the wrapper minus the trailing form
1407 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1408 * @var string
1410 var $_formName = '';
1413 * String with the html for hidden params passed in as part of a moodle_url
1414 * object for the action. Output in the form.
1415 * @var string
1417 var $_pageparams = '';
1420 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1422 * @staticvar int $formcounter counts number of forms
1423 * @param string $formName Form's name.
1424 * @param string $method Form's method defaults to 'POST'
1425 * @param string|moodle_url $action Form's action
1426 * @param string $target (optional)Form's target defaults to none
1427 * @param mixed $attributes (optional)Extra attributes for <form> tag
1429 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1430 global $CFG, $OUTPUT;
1432 static $formcounter = 1;
1434 HTML_Common::HTML_Common($attributes);
1435 $target = empty($target) ? array() : array('target' => $target);
1436 $this->_formName = $formName;
1437 if (is_a($action, 'moodle_url')){
1438 $this->_pageparams = html_writer::input_hidden_params($action);
1439 $action = $action->out_omit_querystring();
1440 } else {
1441 $this->_pageparams = '';
1443 // No 'name' atttribute for form in xhtml strict :
1444 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1445 if (is_null($this->getAttribute('id'))) {
1446 $attributes['id'] = 'mform' . $formcounter;
1448 $formcounter++;
1449 $this->updateAttributes($attributes);
1451 // This is custom stuff for Moodle :
1452 $oldclass= $this->getAttribute('class');
1453 if (!empty($oldclass)){
1454 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1455 }else {
1456 $this->updateAttributes(array('class'=>'mform'));
1458 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1459 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1460 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1464 * Use this method to indicate an element in a form is an advanced field. If items in a form
1465 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1466 * form so the user can decide whether to display advanced form controls.
1468 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1470 * @param string $elementName group or element name (not the element name of something inside a group).
1471 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1473 function setAdvanced($elementName, $advanced = true) {
1474 if ($advanced){
1475 $this->_advancedElements[$elementName]='';
1476 } elseif (isset($this->_advancedElements[$elementName])) {
1477 unset($this->_advancedElements[$elementName]);
1482 * Use this method to indicate that the fieldset should be shown as expanded.
1483 * The method is applicable to header elements only.
1485 * @param string $headername header element name
1486 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1487 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1488 * the form was submitted.
1489 * @return void
1491 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1492 if (empty($headername)) {
1493 return;
1495 $element = $this->getElement($headername);
1496 if ($element->getType() != 'header') {
1497 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1498 return;
1500 if (!$headerid = $element->getAttribute('id')) {
1501 $element->_generateId();
1502 $headerid = $element->getAttribute('id');
1504 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1505 // See if the form has been submitted already.
1506 $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1507 if (!$ignoreuserstate && $formexpanded != -1) {
1508 // Override expanded state with the form variable.
1509 $expanded = $formexpanded;
1511 // Create the form element for storing expanded state.
1512 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1513 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1514 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1516 $this->_collapsibleElements[$headername] = !$expanded;
1520 * Use this method to add show more/less status element required for passing
1521 * over the advanced elements visibility status on the form submission.
1523 * @param string $headerName header element name.
1524 * @param boolean $showmore default false sets the advanced elements to be hidden.
1526 function addAdvancedStatusElement($headerid, $showmore=false){
1527 // Add extra hidden element to store advanced items state for each section.
1528 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1529 // See if we the form has been submitted already.
1530 $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1531 if (!$showmore && $formshowmore != -1) {
1532 // Override showmore state with the form variable.
1533 $showmore = $formshowmore;
1535 // Create the form element for storing advanced items state.
1536 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1537 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1538 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1543 * This function has been deprecated. Show advanced has been replaced by
1544 * "Show more.../Show less..." in the shortforms javascript module.
1546 * @deprecated since Moodle 2.5
1547 * @param bool $showadvancedNow if true will show advanced elements.
1549 function setShowAdvanced($showadvancedNow = null){
1550 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1554 * This function has been deprecated. Show advanced has been replaced by
1555 * "Show more.../Show less..." in the shortforms javascript module.
1557 * @deprecated since Moodle 2.5
1558 * @return bool (Always false)
1560 function getShowAdvanced(){
1561 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1562 return false;
1566 * Use this method to indicate that the form will not be using shortforms.
1568 * @param boolean $disable default true, controls if the shortforms are disabled.
1570 function setDisableShortforms ($disable = true) {
1571 $this->_disableShortforms = $disable;
1575 * Call this method if you don't want the formchangechecker JavaScript to be
1576 * automatically initialised for this form.
1578 public function disable_form_change_checker() {
1579 $this->_use_form_change_checker = false;
1583 * If you have called {@link disable_form_change_checker()} then you can use
1584 * this method to re-enable it. It is enabled by default, so normally you don't
1585 * need to call this.
1587 public function enable_form_change_checker() {
1588 $this->_use_form_change_checker = true;
1592 * @return bool whether this form should automatically initialise
1593 * formchangechecker for itself.
1595 public function is_form_change_checker_enabled() {
1596 return $this->_use_form_change_checker;
1600 * Accepts a renderer
1602 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1604 function accept(&$renderer) {
1605 if (method_exists($renderer, 'setAdvancedElements')){
1606 //Check for visible fieldsets where all elements are advanced
1607 //and mark these headers as advanced as well.
1608 //Also mark all elements in a advanced header as advanced.
1609 $stopFields = $renderer->getStopFieldSetElements();
1610 $lastHeader = null;
1611 $lastHeaderAdvanced = false;
1612 $anyAdvanced = false;
1613 $anyError = false;
1614 foreach (array_keys($this->_elements) as $elementIndex){
1615 $element =& $this->_elements[$elementIndex];
1617 // if closing header and any contained element was advanced then mark it as advanced
1618 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1619 if ($anyAdvanced && !is_null($lastHeader)) {
1620 $lastHeader->_generateId();
1621 $this->setAdvanced($lastHeader->getName());
1622 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1624 $lastHeaderAdvanced = false;
1625 unset($lastHeader);
1626 $lastHeader = null;
1627 } elseif ($lastHeaderAdvanced) {
1628 $this->setAdvanced($element->getName());
1631 if ($element->getType()=='header'){
1632 $lastHeader =& $element;
1633 $anyAdvanced = false;
1634 $anyError = false;
1635 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1636 } elseif (isset($this->_advancedElements[$element->getName()])){
1637 $anyAdvanced = true;
1638 if (isset($this->_errors[$element->getName()])) {
1639 $anyError = true;
1643 // the last header may not be closed yet...
1644 if ($anyAdvanced && !is_null($lastHeader)){
1645 $this->setAdvanced($lastHeader->getName());
1646 $lastHeader->_generateId();
1647 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1649 $renderer->setAdvancedElements($this->_advancedElements);
1651 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1653 // Count the number of sections.
1654 $headerscount = 0;
1655 foreach (array_keys($this->_elements) as $elementIndex){
1656 $element =& $this->_elements[$elementIndex];
1657 if ($element->getType() == 'header') {
1658 $headerscount++;
1662 $anyrequiredorerror = false;
1663 $headercounter = 0;
1664 $headername = null;
1665 foreach (array_keys($this->_elements) as $elementIndex){
1666 $element =& $this->_elements[$elementIndex];
1668 if ($element->getType() == 'header') {
1669 $headercounter++;
1670 $element->_generateId();
1671 $headername = $element->getName();
1672 $anyrequiredorerror = false;
1673 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1674 $anyrequiredorerror = true;
1675 } else {
1676 // Do not reset $anyrequiredorerror to false because we do not want any other element
1677 // in this header (fieldset) to possibly revert the state given.
1680 if ($element->getType() == 'header') {
1681 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1682 // By default the first section is always expanded, except if a state has already been set.
1683 $this->setExpanded($headername, true);
1684 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1685 // The second section is always expanded if the form only contains 2 sections),
1686 // except if a state has already been set.
1687 $this->setExpanded($headername, true);
1689 } else if ($anyrequiredorerror) {
1690 // If any error or required field are present within the header, we need to expand it.
1691 $this->setExpanded($headername, true, true);
1692 } else if (!isset($this->_collapsibleElements[$headername])) {
1693 // Define element as collapsed by default.
1694 $this->setExpanded($headername, false);
1698 // Pass the array to renderer object.
1699 $renderer->setCollapsibleElements($this->_collapsibleElements);
1701 parent::accept($renderer);
1705 * Adds one or more element names that indicate the end of a fieldset
1707 * @param string $elementName name of the element
1709 function closeHeaderBefore($elementName){
1710 $renderer =& $this->defaultRenderer();
1711 $renderer->addStopFieldsetElements($elementName);
1715 * Should be used for all elements of a form except for select, radio and checkboxes which
1716 * clean their own data.
1718 * @param string $elementname
1719 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1720 * {@link lib/moodlelib.php} for defined parameter types
1722 function setType($elementname, $paramtype) {
1723 $this->_types[$elementname] = $paramtype;
1727 * This can be used to set several types at once.
1729 * @param array $paramtypes types of parameters.
1730 * @see MoodleQuickForm::setType
1732 function setTypes($paramtypes) {
1733 $this->_types = $paramtypes + $this->_types;
1737 * Return the type(s) to use to clean an element.
1739 * In the case where the element has an array as a value, we will try to obtain a
1740 * type defined for that specific key, and recursively until done.
1742 * This method does not work reverse, you cannot pass a nested element and hoping to
1743 * fallback on the clean type of a parent. This method intends to be used with the
1744 * main element, which will generate child types if needed, not the other way around.
1746 * Example scenario:
1748 * You have defined a new repeated element containing a text field called 'foo'.
1749 * By default there will always be 2 occurence of 'foo' in the form. Even though
1750 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1751 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1752 * $mform->setType('foo[0]', PARAM_FLOAT).
1754 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1755 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1756 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1757 * get the default clean type returned (param $default).
1759 * @param string $elementname name of the element.
1760 * @param mixed $value value that should be cleaned.
1761 * @param int $default default constant value to be returned (PARAM_...)
1762 * @return string|array constant value or array of constant values (PARAM_...)
1764 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1765 $type = $default;
1766 if (array_key_exists($elementname, $this->_types)) {
1767 $type = $this->_types[$elementname];
1769 if (is_array($value)) {
1770 $default = $type;
1771 $type = array();
1772 foreach ($value as $subkey => $subvalue) {
1773 $typekey = "$elementname" . "[$subkey]";
1774 if (array_key_exists($typekey, $this->_types)) {
1775 $subtype = $this->_types[$typekey];
1776 } else {
1777 $subtype = $default;
1779 if (is_array($subvalue)) {
1780 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1781 } else {
1782 $type[$subkey] = $subtype;
1786 return $type;
1790 * Return the cleaned value using the passed type(s).
1792 * @param mixed $value value that has to be cleaned.
1793 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1794 * @return mixed cleaned up value.
1796 public function getCleanedValue($value, $type) {
1797 if (is_array($type) && is_array($value)) {
1798 foreach ($type as $key => $param) {
1799 $value[$key] = $this->getCleanedValue($value[$key], $param);
1801 } else if (!is_array($type) && !is_array($value)) {
1802 $value = clean_param($value, $type);
1803 } else if (!is_array($type) && is_array($value)) {
1804 $value = clean_param_array($value, $type, true);
1805 } else {
1806 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1808 return $value;
1812 * Updates submitted values
1814 * @param array $submission submitted values
1815 * @param array $files list of files
1817 function updateSubmission($submission, $files) {
1818 $this->_flagSubmitted = false;
1820 if (empty($submission)) {
1821 $this->_submitValues = array();
1822 } else {
1823 foreach ($submission as $key => $s) {
1824 $type = $this->getCleanType($key, $s);
1825 $submission[$key] = $this->getCleanedValue($s, $type);
1827 $this->_submitValues = $submission;
1828 $this->_flagSubmitted = true;
1831 if (empty($files)) {
1832 $this->_submitFiles = array();
1833 } else {
1834 $this->_submitFiles = $files;
1835 $this->_flagSubmitted = true;
1838 // need to tell all elements that they need to update their value attribute.
1839 foreach (array_keys($this->_elements) as $key) {
1840 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1845 * Returns HTML for required elements
1847 * @return string
1849 function getReqHTML(){
1850 return $this->_reqHTML;
1854 * Returns HTML for advanced elements
1856 * @return string
1858 function getAdvancedHTML(){
1859 return $this->_advancedHTML;
1863 * Initializes a default form value. Used to specify the default for a new entry where
1864 * no data is loaded in using moodleform::set_data()
1866 * note: $slashed param removed
1868 * @param string $elementName element name
1869 * @param mixed $defaultValue values for that element name
1871 function setDefault($elementName, $defaultValue){
1872 $this->setDefaults(array($elementName=>$defaultValue));
1876 * Add a help button to element, only one button per element is allowed.
1878 * This is new, simplified and preferable method of setting a help icon on form elements.
1879 * It uses the new $OUTPUT->help_icon().
1881 * Typically, you will provide the same identifier and the component as you have used for the
1882 * label of the element. The string identifier with the _help suffix added is then used
1883 * as the help string.
1885 * There has to be two strings defined:
1886 * 1/ get_string($identifier, $component) - the title of the help page
1887 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1889 * @since Moodle 2.0
1890 * @param string $elementname name of the element to add the item to
1891 * @param string $identifier help string identifier without _help suffix
1892 * @param string $component component name to look the help string in
1893 * @param string $linktext optional text to display next to the icon
1894 * @param bool $suppresscheck set to true if the element may not exist
1896 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1897 global $OUTPUT;
1898 if (array_key_exists($elementname, $this->_elementIndex)) {
1899 $element = $this->_elements[$this->_elementIndex[$elementname]];
1900 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1901 } else if (!$suppresscheck) {
1902 debugging(get_string('nonexistentformelements', 'form', $elementname));
1907 * Set constant value not overridden by _POST or _GET
1908 * note: this does not work for complex names with [] :-(
1910 * @param string $elname name of element
1911 * @param mixed $value
1913 function setConstant($elname, $value) {
1914 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1915 $element =& $this->getElement($elname);
1916 $element->onQuickFormEvent('updateValue', null, $this);
1920 * export submitted values
1922 * @param string $elementList list of elements in form
1923 * @return array
1925 function exportValues($elementList = null){
1926 $unfiltered = array();
1927 if (null === $elementList) {
1928 // iterate over all elements, calling their exportValue() methods
1929 foreach (array_keys($this->_elements) as $key) {
1930 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1931 $varname = $this->_elements[$key]->_attributes['name'];
1932 $value = '';
1933 // If we have a default value then export it.
1934 if (isset($this->_defaultValues[$varname])) {
1935 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
1937 } else {
1938 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1941 if (is_array($value)) {
1942 // This shit throws a bogus warning in PHP 4.3.x
1943 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1946 } else {
1947 if (!is_array($elementList)) {
1948 $elementList = array_map('trim', explode(',', $elementList));
1950 foreach ($elementList as $elementName) {
1951 $value = $this->exportValue($elementName);
1952 if (@PEAR::isError($value)) {
1953 return $value;
1955 //oh, stock QuickFOrm was returning array of arrays!
1956 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1960 if (is_array($this->_constantValues)) {
1961 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1963 return $unfiltered;
1967 * This is a bit of a hack, and it duplicates the code in
1968 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
1969 * reliably calling that code. (Think about date selectors, for example.)
1970 * @param string $name the element name.
1971 * @param mixed $value the fixed value to set.
1972 * @return mixed the appropriate array to add to the $unfiltered array.
1974 protected function prepare_fixed_value($name, $value) {
1975 if (null === $value) {
1976 return null;
1977 } else {
1978 if (!strpos($name, '[')) {
1979 return array($name => $value);
1980 } else {
1981 $valueAry = array();
1982 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
1983 eval("\$valueAry$myIndex = \$value;");
1984 return $valueAry;
1990 * Adds a validation rule for the given field
1992 * If the element is in fact a group, it will be considered as a whole.
1993 * To validate grouped elements as separated entities,
1994 * use addGroupRule instead of addRule.
1996 * @param string $element Form element name
1997 * @param string $message Message to display for invalid data
1998 * @param string $type Rule type, use getRegisteredRules() to get types
1999 * @param string $format (optional)Required for extra rule data
2000 * @param string $validation (optional)Where to perform validation: "server", "client"
2001 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2002 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2004 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2006 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2007 if ($validation == 'client') {
2008 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2014 * Adds a validation rule for the given group of elements
2016 * Only groups with a name can be assigned a validation rule
2017 * Use addGroupRule when you need to validate elements inside the group.
2018 * Use addRule if you need to validate the group as a whole. In this case,
2019 * the same rule will be applied to all elements in the group.
2020 * Use addRule if you need to validate the group against a function.
2022 * @param string $group Form group name
2023 * @param array|string $arg1 Array for multiple elements or error message string for one element
2024 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2025 * @param string $format (optional)Required for extra rule data
2026 * @param int $howmany (optional)How many valid elements should be in the group
2027 * @param string $validation (optional)Where to perform validation: "server", "client"
2028 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2030 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2032 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2033 if (is_array($arg1)) {
2034 foreach ($arg1 as $rules) {
2035 foreach ($rules as $rule) {
2036 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2038 if ('client' == $validation) {
2039 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2043 } elseif (is_string($arg1)) {
2045 if ($validation == 'client') {
2046 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2052 * Returns the client side validation script
2054 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2055 * and slightly modified to run rules per-element
2056 * Needed to override this because of an error with client side validation of grouped elements.
2058 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2060 function getValidationScript()
2062 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
2063 return '';
2066 include_once('HTML/QuickForm/RuleRegistry.php');
2067 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2068 $test = array();
2069 $js_escape = array(
2070 "\r" => '\r',
2071 "\n" => '\n',
2072 "\t" => '\t',
2073 "'" => "\\'",
2074 '"' => '\"',
2075 '\\' => '\\\\'
2078 foreach ($this->_rules as $elementName => $rules) {
2079 foreach ($rules as $rule) {
2080 if ('client' == $rule['validation']) {
2081 unset($element); //TODO: find out how to properly initialize it
2083 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2084 $rule['message'] = strtr($rule['message'], $js_escape);
2086 if (isset($rule['group'])) {
2087 $group =& $this->getElement($rule['group']);
2088 // No JavaScript validation for frozen elements
2089 if ($group->isFrozen()) {
2090 continue 2;
2092 $elements =& $group->getElements();
2093 foreach (array_keys($elements) as $key) {
2094 if ($elementName == $group->getElementName($key)) {
2095 $element =& $elements[$key];
2096 break;
2099 } elseif ($dependent) {
2100 $element = array();
2101 $element[] =& $this->getElement($elementName);
2102 foreach ($rule['dependent'] as $elName) {
2103 $element[] =& $this->getElement($elName);
2105 } else {
2106 $element =& $this->getElement($elementName);
2108 // No JavaScript validation for frozen elements
2109 if (is_object($element) && $element->isFrozen()) {
2110 continue 2;
2111 } elseif (is_array($element)) {
2112 foreach (array_keys($element) as $key) {
2113 if ($element[$key]->isFrozen()) {
2114 continue 3;
2118 //for editor element, [text] is appended to the name.
2119 $fullelementname = $elementName;
2120 if ($element->getType() == 'editor') {
2121 $fullelementname .= '[text]';
2122 //Add format to rule as moodleform check which format is supported by browser
2123 //it is not set anywhere... So small hack to make sure we pass it down to quickform
2124 if (is_null($rule['format'])) {
2125 $rule['format'] = $element->getFormat();
2128 // Fix for bug displaying errors for elements in a group
2129 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2130 $test[$fullelementname][1]=$element;
2131 //end of fix
2136 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2137 // the form, and then that form field gets corrupted by the code that follows.
2138 unset($element);
2140 $js = '
2141 <script type="text/javascript">
2142 //<![CDATA[
2144 var skipClientValidation = false;
2146 function qf_errorHandler(element, _qfMsg, escapedName) {
2147 div = element.parentNode;
2149 if ((div == undefined) || (element.name == undefined)) {
2150 //no checking can be done for undefined elements so let server handle it.
2151 return true;
2154 if (_qfMsg != \'\') {
2155 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2156 if (!errorSpan) {
2157 errorSpan = document.createElement("span");
2158 errorSpan.id = \'id_error_\' + escapedName;
2159 errorSpan.className = "error";
2160 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2161 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2162 document.getElementById(errorSpan.id).focus();
2165 while (errorSpan.firstChild) {
2166 errorSpan.removeChild(errorSpan.firstChild);
2169 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2171 if (div.className.substr(div.className.length - 6, 6) != " error"
2172 && div.className != "error") {
2173 div.className += " error";
2174 linebreak = document.createElement("br");
2175 linebreak.className = "error";
2176 linebreak.id = \'id_error_break_\' + escapedName;
2177 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2180 return false;
2181 } else {
2182 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2183 if (errorSpan) {
2184 errorSpan.parentNode.removeChild(errorSpan);
2186 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2187 if (linebreak) {
2188 linebreak.parentNode.removeChild(linebreak);
2191 if (div.className.substr(div.className.length - 6, 6) == " error") {
2192 div.className = div.className.substr(0, div.className.length - 6);
2193 } else if (div.className == "error") {
2194 div.className = "";
2197 return true;
2200 $validateJS = '';
2201 foreach ($test as $elementName => $jsandelement) {
2202 // Fix for bug displaying errors for elements in a group
2203 //unset($element);
2204 list($jsArr,$element)=$jsandelement;
2205 //end of fix
2206 $escapedElementName = preg_replace_callback(
2207 '/[_\[\]-]/',
2208 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2209 $elementName);
2210 $js .= '
2211 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2212 if (undefined == element) {
2213 //required element was not found, then let form be submitted without client side validation
2214 return true;
2216 var value = \'\';
2217 var errFlag = new Array();
2218 var _qfGroups = {};
2219 var _qfMsg = \'\';
2220 var frm = element.parentNode;
2221 if ((undefined != element.name) && (frm != undefined)) {
2222 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2223 frm = frm.parentNode;
2225 ' . join("\n", $jsArr) . '
2226 return qf_errorHandler(element, _qfMsg, escapedName);
2227 } else {
2228 //element name should be defined else error msg will not be displayed.
2229 return true;
2233 $validateJS .= '
2234 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2235 if (!ret && !first_focus) {
2236 first_focus = true;
2237 Y.use(\'moodle-core-event\', function() {
2238 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes['id'] . '\',
2239 elementid: \'id_error_' . $escapedElementName . '\'});
2240 document.getElementById(\'id_error_' . $escapedElementName . '\').focus();
2245 // Fix for bug displaying errors for elements in a group
2246 //unset($element);
2247 //$element =& $this->getElement($elementName);
2248 //end of fix
2249 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this, \''.$escapedElementName.'\')';
2250 $onBlur = $element->getAttribute('onBlur');
2251 $onChange = $element->getAttribute('onChange');
2252 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2253 'onChange' => $onChange . $valFunc));
2255 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2256 $js .= '
2257 function validate_' . $this->_formName . '(frm) {
2258 if (skipClientValidation) {
2259 return true;
2261 var ret = true;
2263 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2264 var first_focus = false;
2265 ' . $validateJS . ';
2266 return ret;
2268 //]]>
2269 </script>';
2270 return $js;
2271 } // end func getValidationScript
2274 * Sets default error message
2276 function _setDefaultRuleMessages(){
2277 foreach ($this->_rules as $field => $rulesarr){
2278 foreach ($rulesarr as $key => $rule){
2279 if ($rule['message']===null){
2280 $a=new stdClass();
2281 $a->format=$rule['format'];
2282 $str=get_string('err_'.$rule['type'], 'form', $a);
2283 if (strpos($str, '[[')!==0){
2284 $this->_rules[$field][$key]['message']=$str;
2292 * Get list of attributes which have dependencies
2294 * @return array
2296 function getLockOptionObject(){
2297 $result = array();
2298 foreach ($this->_dependencies as $dependentOn => $conditions){
2299 $result[$dependentOn] = array();
2300 foreach ($conditions as $condition=>$values) {
2301 $result[$dependentOn][$condition] = array();
2302 foreach ($values as $value=>$dependents) {
2303 $result[$dependentOn][$condition][$value] = array();
2304 $i = 0;
2305 foreach ($dependents as $dependent) {
2306 $elements = $this->_getElNamesRecursive($dependent);
2307 if (empty($elements)) {
2308 // probably element inside of some group
2309 $elements = array($dependent);
2311 foreach($elements as $element) {
2312 if ($element == $dependentOn) {
2313 continue;
2315 $result[$dependentOn][$condition][$value][] = $element;
2321 return array($this->getAttribute('id'), $result);
2325 * Get names of element or elements in a group.
2327 * @param HTML_QuickForm_group|element $element element group or element object
2328 * @return array
2330 function _getElNamesRecursive($element) {
2331 if (is_string($element)) {
2332 if (!$this->elementExists($element)) {
2333 return array();
2335 $element = $this->getElement($element);
2338 if (is_a($element, 'HTML_QuickForm_group')) {
2339 $elsInGroup = $element->getElements();
2340 $elNames = array();
2341 foreach ($elsInGroup as $elInGroup){
2342 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2343 // not sure if this would work - groups nested in groups
2344 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2345 } else {
2346 $elNames[] = $element->getElementName($elInGroup->getName());
2350 } else if (is_a($element, 'HTML_QuickForm_header')) {
2351 return array();
2353 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2354 return array();
2356 } else if (method_exists($element, 'getPrivateName') &&
2357 !($element instanceof HTML_QuickForm_advcheckbox)) {
2358 // The advcheckbox element implements a method called getPrivateName,
2359 // but in a way that is not compatible with the generic API, so we
2360 // have to explicitly exclude it.
2361 return array($element->getPrivateName());
2363 } else {
2364 $elNames = array($element->getName());
2367 return $elNames;
2371 * Adds a dependency for $elementName which will be disabled if $condition is met.
2372 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2373 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2374 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2375 * of the $dependentOn element is $condition (such as equal) to $value.
2377 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2378 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2379 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2381 * @param string $elementName the name of the element which will be disabled
2382 * @param string $dependentOn the name of the element whose state will be checked for condition
2383 * @param string $condition the condition to check
2384 * @param mixed $value used in conjunction with condition.
2386 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2387 // Multiple selects allow for a multiple selection, we transform the array to string here as
2388 // an array cannot be used as a key in an associative array.
2389 if (is_array($value)) {
2390 $value = implode('|', $value);
2392 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2393 $this->_dependencies[$dependentOn] = array();
2395 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2396 $this->_dependencies[$dependentOn][$condition] = array();
2398 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2399 $this->_dependencies[$dependentOn][$condition][$value] = array();
2401 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2405 * Registers button as no submit button
2407 * @param string $buttonname name of the button
2409 function registerNoSubmitButton($buttonname){
2410 $this->_noSubmitButtons[]=$buttonname;
2414 * Checks if button is a no submit button, i.e it doesn't submit form
2416 * @param string $buttonname name of the button to check
2417 * @return bool
2419 function isNoSubmitButton($buttonname){
2420 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2424 * Registers a button as cancel button
2426 * @param string $addfieldsname name of the button
2428 function _registerCancelButton($addfieldsname){
2429 $this->_cancelButtons[]=$addfieldsname;
2433 * Displays elements without HTML input tags.
2434 * This method is different to freeze() in that it makes sure no hidden
2435 * elements are included in the form.
2436 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2438 * This function also removes all previously defined rules.
2440 * @param string|array $elementList array or string of element(s) to be frozen
2441 * @return object|bool if element list is not empty then return error object, else true
2443 function hardFreeze($elementList=null)
2445 if (!isset($elementList)) {
2446 $this->_freezeAll = true;
2447 $elementList = array();
2448 } else {
2449 if (!is_array($elementList)) {
2450 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2452 $elementList = array_flip($elementList);
2455 foreach (array_keys($this->_elements) as $key) {
2456 $name = $this->_elements[$key]->getName();
2457 if ($this->_freezeAll || isset($elementList[$name])) {
2458 $this->_elements[$key]->freeze();
2459 $this->_elements[$key]->setPersistantFreeze(false);
2460 unset($elementList[$name]);
2462 // remove all rules
2463 $this->_rules[$name] = array();
2464 // if field is required, remove the rule
2465 $unset = array_search($name, $this->_required);
2466 if ($unset !== false) {
2467 unset($this->_required[$unset]);
2472 if (!empty($elementList)) {
2473 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);
2475 return true;
2479 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2481 * This function also removes all previously defined rules of elements it freezes.
2483 * @throws HTML_QuickForm_Error
2484 * @param array $elementList array or string of element(s) not to be frozen
2485 * @return bool returns true
2487 function hardFreezeAllVisibleExcept($elementList)
2489 $elementList = array_flip($elementList);
2490 foreach (array_keys($this->_elements) as $key) {
2491 $name = $this->_elements[$key]->getName();
2492 $type = $this->_elements[$key]->getType();
2494 if ($type == 'hidden'){
2495 // leave hidden types as they are
2496 } elseif (!isset($elementList[$name])) {
2497 $this->_elements[$key]->freeze();
2498 $this->_elements[$key]->setPersistantFreeze(false);
2500 // remove all rules
2501 $this->_rules[$name] = array();
2502 // if field is required, remove the rule
2503 $unset = array_search($name, $this->_required);
2504 if ($unset !== false) {
2505 unset($this->_required[$unset]);
2509 return true;
2513 * Tells whether the form was already submitted
2515 * This is useful since the _submitFiles and _submitValues arrays
2516 * may be completely empty after the trackSubmit value is removed.
2518 * @return bool
2520 function isSubmitted()
2522 return parent::isSubmitted() && (!$this->isFrozen());
2527 * MoodleQuickForm renderer
2529 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2530 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2532 * Stylesheet is part of standard theme and should be automatically included.
2534 * @package core_form
2535 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2538 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2540 /** @var array Element template array */
2541 var $_elementTemplates;
2544 * Template used when opening a hidden fieldset
2545 * (i.e. a fieldset that is opened when there is no header element)
2546 * @var string
2548 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2550 /** @var string Header Template string */
2551 var $_headerTemplate =
2552 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2554 /** @var string Template used when opening a fieldset */
2555 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2557 /** @var string Template used when closing a fieldset */
2558 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2560 /** @var string Required Note template string */
2561 var $_requiredNoteTemplate =
2562 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2565 * Collapsible buttons string template.
2567 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2568 * until the Javascript has been fully loaded.
2570 * @var string
2572 var $_collapseButtonsTemplate =
2573 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2576 * Array whose keys are element names. If the key exists this is a advanced element
2578 * @var array
2580 var $_advancedElements = array();
2583 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2585 * @var array
2587 var $_collapsibleElements = array();
2590 * @var string Contains the collapsible buttons to add to the form.
2592 var $_collapseButtons = '';
2595 * Constructor
2597 function MoodleQuickForm_Renderer(){
2598 // switch next two lines for ol li containers for form items.
2599 // $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>');
2600 $this->_elementTemplates = array(
2601 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}" {aria-live}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2603 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2605 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2607 'static'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2609 'warning'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}">{element}</div>',
2611 'nodisplay'=>'');
2613 parent::HTML_QuickForm_Renderer_Tableless();
2617 * Set element's as adavance element
2619 * @param array $elements form elements which needs to be grouped as advance elements.
2621 function setAdvancedElements($elements){
2622 $this->_advancedElements = $elements;
2626 * Setting collapsible elements
2628 * @param array $elements
2630 function setCollapsibleElements($elements) {
2631 $this->_collapsibleElements = $elements;
2635 * What to do when starting the form
2637 * @param MoodleQuickForm $form reference of the form
2639 function startForm(&$form){
2640 global $PAGE;
2641 $this->_reqHTML = $form->getReqHTML();
2642 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2643 $this->_advancedHTML = $form->getAdvancedHTML();
2644 $this->_collapseButtons = '';
2645 $formid = $form->getAttribute('id');
2646 parent::startForm($form);
2647 if ($form->isFrozen()){
2648 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2649 } else {
2650 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2651 $this->_hiddenHtml .= $form->_pageparams;
2654 if ($form->is_form_change_checker_enabled()) {
2655 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2656 'M.core_formchangechecker.init',
2657 array(array(
2658 'formid' => $formid
2661 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2663 if (!empty($this->_collapsibleElements)) {
2664 if (count($this->_collapsibleElements) > 1) {
2665 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2666 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2667 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2669 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2671 if (!empty($this->_advancedElements)){
2672 $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2673 $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2678 * Create advance group of elements
2680 * @param object $group Passed by reference
2681 * @param bool $required if input is required field
2682 * @param string $error error message to display
2684 function startGroup(&$group, $required, $error){
2685 // Make sure the element has an id.
2686 $group->_generateId();
2688 if (method_exists($group, 'getElementTemplateType')){
2689 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2690 }else{
2691 $html = $this->_elementTemplates['default'];
2695 if (isset($this->_advancedElements[$group->getName()])){
2696 $html =str_replace(' {advanced}', ' advanced', $html);
2697 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2698 } else {
2699 $html =str_replace(' {advanced}', '', $html);
2700 $html =str_replace('{advancedimg}', '', $html);
2702 if (method_exists($group, 'getHelpButton')){
2703 $html =str_replace('{help}', $group->getHelpButton(), $html);
2704 }else{
2705 $html =str_replace('{help}', '', $html);
2707 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2708 $html =str_replace('{name}', $group->getName(), $html);
2709 $html =str_replace('{type}', 'fgroup', $html);
2710 $emptylabel = '';
2711 if ($group->getLabel() == '') {
2712 $emptylabel = 'femptylabel';
2714 $html = str_replace('{emptylabel}', $emptylabel, $html);
2716 $this->_templates[$group->getName()]=$html;
2717 // Fix for bug in tableless quickforms that didn't allow you to stop a
2718 // fieldset before a group of elements.
2719 // if the element name indicates the end of a fieldset, close the fieldset
2720 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2721 && $this->_fieldsetsOpen > 0
2723 $this->_html .= $this->_closeFieldsetTemplate;
2724 $this->_fieldsetsOpen--;
2726 parent::startGroup($group, $required, $error);
2730 * Renders element
2732 * @param HTML_QuickForm_element $element element
2733 * @param bool $required if input is required field
2734 * @param string $error error message to display
2736 function renderElement(&$element, $required, $error){
2737 // Make sure the element has an id.
2738 $element->_generateId();
2740 //adding stuff to place holders in template
2741 //check if this is a group element first
2742 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2743 // so it gets substitutions for *each* element
2744 $html = $this->_groupElementTemplate;
2746 elseif (method_exists($element, 'getElementTemplateType')){
2747 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2748 }else{
2749 $html = $this->_elementTemplates['default'];
2751 if (isset($this->_advancedElements[$element->getName()])){
2752 $html = str_replace(' {advanced}', ' advanced', $html);
2753 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2754 } else {
2755 $html = str_replace(' {advanced}', '', $html);
2756 $html = str_replace(' {aria-live}', '', $html);
2758 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2759 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2760 } else {
2761 $html =str_replace('{advancedimg}', '', $html);
2763 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2764 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2765 $html =str_replace('{name}', $element->getName(), $html);
2766 $emptylabel = '';
2767 if ($element->getLabel() == '') {
2768 $emptylabel = 'femptylabel';
2770 $html = str_replace('{emptylabel}', $emptylabel, $html);
2771 if (method_exists($element, 'getHelpButton')){
2772 $html = str_replace('{help}', $element->getHelpButton(), $html);
2773 }else{
2774 $html = str_replace('{help}', '', $html);
2777 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2778 $this->_groupElementTemplate = $html;
2780 elseif (!isset($this->_templates[$element->getName()])) {
2781 $this->_templates[$element->getName()] = $html;
2784 parent::renderElement($element, $required, $error);
2788 * Called when visiting a form, after processing all form elements
2789 * Adds required note, form attributes, validation javascript and form content.
2791 * @global moodle_page $PAGE
2792 * @param moodleform $form Passed by reference
2794 function finishForm(&$form){
2795 global $PAGE;
2796 if ($form->isFrozen()){
2797 $this->_hiddenHtml = '';
2799 parent::finishForm($form);
2800 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2801 if (!$form->isFrozen()) {
2802 $args = $form->getLockOptionObject();
2803 if (count($args[1]) > 0) {
2804 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2809 * Called when visiting a header element
2811 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2812 * @global moodle_page $PAGE
2814 function renderHeader(&$header) {
2815 global $PAGE;
2817 $header->_generateId();
2818 $name = $header->getName();
2820 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2821 if (is_null($header->_text)) {
2822 $header_html = '';
2823 } elseif (!empty($name) && isset($this->_templates[$name])) {
2824 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2825 } else {
2826 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2829 if ($this->_fieldsetsOpen > 0) {
2830 $this->_html .= $this->_closeFieldsetTemplate;
2831 $this->_fieldsetsOpen--;
2834 // Define collapsible classes for fieldsets.
2835 $arialive = '';
2836 $fieldsetclasses = array('clearfix');
2837 if (isset($this->_collapsibleElements[$header->getName()])) {
2838 $fieldsetclasses[] = 'collapsible';
2839 if ($this->_collapsibleElements[$header->getName()]) {
2840 $fieldsetclasses[] = 'collapsed';
2844 if (isset($this->_advancedElements[$name])){
2845 $fieldsetclasses[] = 'containsadvancedelements';
2848 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2849 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
2851 $this->_html .= $openFieldsetTemplate . $header_html;
2852 $this->_fieldsetsOpen++;
2856 * Return Array of element names that indicate the end of a fieldset
2858 * @return array
2860 function getStopFieldsetElements(){
2861 return $this->_stopFieldsetElements;
2866 * Required elements validation
2868 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2870 * @package core_form
2871 * @category form
2872 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2873 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2875 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2877 * Checks if an element is not empty.
2878 * This is a server-side validation, it works for both text fields and editor fields
2880 * @param string $value Value to check
2881 * @param int|string|array $options Not used yet
2882 * @return bool true if value is not empty
2884 function validate($value, $options = null) {
2885 global $CFG;
2886 if (is_array($value) && array_key_exists('text', $value)) {
2887 $value = $value['text'];
2889 if (is_array($value)) {
2890 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2891 $value = implode('', $value);
2893 $stripvalues = array(
2894 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2895 '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
2897 if (!empty($CFG->strictformsrequired)) {
2898 $value = preg_replace($stripvalues, '', (string)$value);
2900 if ((string)$value == '') {
2901 return false;
2903 return true;
2907 * This function returns Javascript code used to build client-side validation.
2908 * It checks if an element is not empty.
2910 * @param int $format format of data which needs to be validated.
2911 * @return array
2913 function getValidationScript($format = null) {
2914 global $CFG;
2915 if (!empty($CFG->strictformsrequired)) {
2916 if (!empty($format) && $format == FORMAT_HTML) {
2917 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
2918 } else {
2919 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2921 } else {
2922 return array('', "{jsVar} == ''");
2928 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2929 * @name $_HTML_QuickForm_default_renderer
2931 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2933 /** Please keep this list in alphabetical order. */
2934 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2935 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2936 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2937 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2938 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2939 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2940 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2941 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2942 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2943 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2944 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2945 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2946 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2947 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2948 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2949 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2950 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
2951 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2952 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2953 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2954 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2955 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2956 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2957 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2958 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2959 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2960 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2961 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2962 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2963 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2964 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2965 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2966 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2967 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2968 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2969 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2971 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");