MDL-57266 upgrade: add 3.2.0 separation line to all upgrade scripts
[moodle.git] / lib / formslib.php
blob23dce84d27695ef784a988476deb710abc7a8e20
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
20 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
21 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
22 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
23 * and validation.
25 * See examples of use of this library in course/edit.php and course/edit_form.php
27 * A few notes :
28 * form definition is used for both printing of form and processing and should be the same
29 * for both or you may lose some submitted data which won't be let through.
30 * you should be using setType for every form element except select, radio or checkbox
31 * elements, these elements clean themselves.
33 * @package core_form
34 * @copyright 2006 Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /** setup.php includes our hacked pear libs first */
41 require_once 'HTML/QuickForm.php';
42 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43 require_once 'HTML/QuickForm/Renderer/Tableless.php';
44 require_once 'HTML/QuickForm/Rule.php';
46 require_once $CFG->libdir.'/filelib.php';
48 /**
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
53 /**
54 * Callback called when PEAR throws an error
56 * @param PEAR_Error $error
58 function pear_handle_error($error){
59 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
60 echo '<br /> <strong>Backtrace </strong>:';
61 print_object($error->backtrace);
64 if ($CFG->debugdeveloper) {
65 //TODO: this is a wrong place to init PEAR!
66 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
67 $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
70 /**
71 * Initalize javascript for date type form element
73 * @staticvar bool $done make sure it gets initalize once.
74 * @global moodle_page $PAGE
76 function form_init_date_js() {
77 global $PAGE;
78 static $done = false;
79 if (!$done) {
80 $calendar = \core_calendar\type_factory::get_calendar_instance();
81 $module = 'moodle-form-dateselector';
82 $function = 'M.form.dateselector.init_date_selectors';
83 $defaulttimezone = date_default_timezone_get();
85 $config = array(array(
86 'firstdayofweek' => $calendar->get_starting_weekday(),
87 'mon' => date_format_string(strtotime("Monday"), '%a', $defaulttimezone),
88 'tue' => date_format_string(strtotime("Tuesday"), '%a', $defaulttimezone),
89 'wed' => date_format_string(strtotime("Wednesday"), '%a', $defaulttimezone),
90 'thu' => date_format_string(strtotime("Thursday"), '%a', $defaulttimezone),
91 'fri' => date_format_string(strtotime("Friday"), '%a', $defaulttimezone),
92 'sat' => date_format_string(strtotime("Saturday"), '%a', $defaulttimezone),
93 'sun' => date_format_string(strtotime("Sunday"), '%a', $defaulttimezone),
94 'january' => date_format_string(strtotime("January 1"), '%B', $defaulttimezone),
95 'february' => date_format_string(strtotime("February 1"), '%B', $defaulttimezone),
96 'march' => date_format_string(strtotime("March 1"), '%B', $defaulttimezone),
97 'april' => date_format_string(strtotime("April 1"), '%B', $defaulttimezone),
98 'may' => date_format_string(strtotime("May 1"), '%B', $defaulttimezone),
99 'june' => date_format_string(strtotime("June 1"), '%B', $defaulttimezone),
100 'july' => date_format_string(strtotime("July 1"), '%B', $defaulttimezone),
101 'august' => date_format_string(strtotime("August 1"), '%B', $defaulttimezone),
102 'september' => date_format_string(strtotime("September 1"), '%B', $defaulttimezone),
103 'october' => date_format_string(strtotime("October 1"), '%B', $defaulttimezone),
104 'november' => date_format_string(strtotime("November 1"), '%B', $defaulttimezone),
105 'december' => date_format_string(strtotime("December 1"), '%B', $defaulttimezone)
107 $PAGE->requires->yui_module($module, $function, $config);
108 $done = true;
113 * Wrapper that separates quickforms syntax from moodle code
115 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
116 * use this class you should write a class definition which extends this class or a more specific
117 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
119 * You will write your own definition() method which performs the form set up.
121 * @package core_form
122 * @copyright 2006 Jamie Pratt <me@jamiep.org>
123 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
124 * @todo MDL-19380 rethink the file scanning
126 abstract class moodleform {
127 /** @var string name of the form */
128 protected $_formname; // form name
130 /** @var MoodleQuickForm quickform object definition */
131 protected $_form;
133 /** @var array globals workaround */
134 protected $_customdata;
136 /** @var array submitted form data when using mforms with ajax */
137 protected $_ajaxformdata;
139 /** @var object definition_after_data executed flag */
140 protected $_definition_finalized = false;
142 /** @var bool|null stores the validation result of this form or null if not yet validated */
143 protected $_validated = null;
146 * The constructor function calls the abstract function definition() and it will then
147 * process and clean and attempt to validate incoming data.
149 * It will call your custom validate method to validate data and will also check any rules
150 * you have specified in definition using addRule
152 * The name of the form (id attribute of the form) is automatically generated depending on
153 * the name you gave the class extending moodleform. You should call your class something
154 * like
156 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
157 * current url. If a moodle_url object then outputs params as hidden variables.
158 * @param mixed $customdata if your form defintion method needs access to data such as $course
159 * $cm, etc. to construct the form definition then pass it in this array. You can
160 * use globals for somethings.
161 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
162 * be merged and used as incoming data to the form.
163 * @param string $target target frame for form submission. You will rarely use this. Don't use
164 * it if you don't need to as the target attribute is deprecated in xhtml strict.
165 * @param mixed $attributes you can pass a string of html attributes here or an array.
166 * @param bool $editable
167 * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
169 public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true,
170 $ajaxformdata=null) {
171 global $CFG, $FULLME;
172 // no standard mform in moodle should allow autocomplete with the exception of user signup
173 if (empty($attributes)) {
174 $attributes = array('autocomplete'=>'off');
175 } else if (is_array($attributes)) {
176 $attributes['autocomplete'] = 'off';
177 } else {
178 if (strpos($attributes, 'autocomplete') === false) {
179 $attributes .= ' autocomplete="off" ';
184 if (empty($action)){
185 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
186 $action = strip_querystring($FULLME);
187 if (!empty($CFG->sslproxy)) {
188 // return only https links when using SSL proxy
189 $action = preg_replace('/^http:/', 'https:', $action, 1);
191 //TODO: use following instead of FULLME - see MDL-33015
192 //$action = strip_querystring(qualified_me());
194 // Assign custom data first, so that get_form_identifier can use it.
195 $this->_customdata = $customdata;
196 $this->_formname = $this->get_form_identifier();
197 $this->_ajaxformdata = $ajaxformdata;
199 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
200 if (!$editable){
201 $this->_form->hardFreeze();
204 $this->definition();
206 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
207 $this->_form->setType('sesskey', PARAM_RAW);
208 $this->_form->setDefault('sesskey', sesskey());
209 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
210 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
211 $this->_form->setDefault('_qf__'.$this->_formname, 1);
212 $this->_form->_setDefaultRuleMessages();
214 // we have to know all input types before processing submission ;-)
215 $this->_process_submission($method);
219 * Old syntax of class constructor. Deprecated in PHP7.
221 * @deprecated since Moodle 3.1
223 public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
224 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
225 self::__construct($action, $customdata, $method, $target, $attributes, $editable);
229 * It should returns unique identifier for the form.
230 * Currently it will return class name, but in case two same forms have to be
231 * rendered on same page then override function to get unique form identifier.
232 * e.g This is used on multiple self enrollments page.
234 * @return string form identifier.
236 protected function get_form_identifier() {
237 $class = get_class($this);
239 return preg_replace('/[^a-z0-9_]/i', '_', $class);
243 * To autofocus on first form element or first element with error.
245 * @param string $name if this is set then the focus is forced to a field with this name
246 * @return string javascript to select form element with first error or
247 * first element if no errors. Use this as a parameter
248 * when calling print_header
250 function focus($name=NULL) {
251 $form =& $this->_form;
252 $elkeys = array_keys($form->_elementIndex);
253 $error = false;
254 if (isset($form->_errors) && 0 != count($form->_errors)){
255 $errorkeys = array_keys($form->_errors);
256 $elkeys = array_intersect($elkeys, $errorkeys);
257 $error = true;
260 if ($error or empty($name)) {
261 $names = array();
262 while (empty($names) and !empty($elkeys)) {
263 $el = array_shift($elkeys);
264 $names = $form->_getElNamesRecursive($el);
266 if (!empty($names)) {
267 $name = array_shift($names);
271 $focus = '';
272 if (!empty($name)) {
273 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
276 return $focus;
280 * Internal method. Alters submitted data to be suitable for quickforms processing.
281 * Must be called when the form is fully set up.
283 * @param string $method name of the method which alters submitted data
285 function _process_submission($method) {
286 $submission = array();
287 if (!empty($this->_ajaxformdata)) {
288 $submission = $this->_ajaxformdata;
289 } else if ($method == 'post') {
290 if (!empty($_POST)) {
291 $submission = $_POST;
293 } else {
294 $submission = $_GET;
295 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
298 // following trick is needed to enable proper sesskey checks when using GET forms
299 // the _qf__.$this->_formname serves as a marker that form was actually submitted
300 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
301 if (!confirm_sesskey()) {
302 print_error('invalidsesskey');
304 $files = $_FILES;
305 } else {
306 $submission = array();
307 $files = array();
309 $this->detectMissingSetType();
311 $this->_form->updateSubmission($submission, $files);
315 * Internal method - should not be used anywhere.
316 * @deprecated since 2.6
317 * @return array $_POST.
319 protected function _get_post_params() {
320 return $_POST;
324 * Internal method. Validates all old-style deprecated uploaded files.
325 * The new way is to upload files via repository api.
327 * @param array $files list of files to be validated
328 * @return bool|array Success or an array of errors
330 function _validate_files(&$files) {
331 global $CFG, $COURSE;
333 $files = array();
335 if (empty($_FILES)) {
336 // we do not need to do any checks because no files were submitted
337 // note: server side rules do not work for files - use custom verification in validate() instead
338 return true;
341 $errors = array();
342 $filenames = array();
344 // now check that we really want each file
345 foreach ($_FILES as $elname=>$file) {
346 $required = $this->_form->isElementRequired($elname);
348 if ($file['error'] == 4 and $file['size'] == 0) {
349 if ($required) {
350 $errors[$elname] = get_string('required');
352 unset($_FILES[$elname]);
353 continue;
356 if (!empty($file['error'])) {
357 $errors[$elname] = file_get_upload_error($file['error']);
358 unset($_FILES[$elname]);
359 continue;
362 if (!is_uploaded_file($file['tmp_name'])) {
363 // TODO: improve error message
364 $errors[$elname] = get_string('error');
365 unset($_FILES[$elname]);
366 continue;
369 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
370 // hmm, this file was not requested
371 unset($_FILES[$elname]);
372 continue;
375 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
377 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
378 if ($filename === '') {
379 // TODO: improve error message - wrong chars
380 $errors[$elname] = get_string('error');
381 unset($_FILES[$elname]);
382 continue;
384 if (in_array($filename, $filenames)) {
385 // TODO: improve error message - duplicate name
386 $errors[$elname] = get_string('error');
387 unset($_FILES[$elname]);
388 continue;
390 $filenames[] = $filename;
391 $_FILES[$elname]['name'] = $filename;
393 $files[$elname] = $_FILES[$elname]['tmp_name'];
396 // return errors if found
397 if (count($errors) == 0){
398 return true;
400 } else {
401 $files = array();
402 return $errors;
407 * Internal method. Validates filepicker and filemanager files if they are
408 * set as required fields. Also, sets the error message if encountered one.
410 * @return bool|array with errors
412 protected function validate_draft_files() {
413 global $USER;
414 $mform =& $this->_form;
416 $errors = array();
417 //Go through all the required elements and make sure you hit filepicker or
418 //filemanager element.
419 foreach ($mform->_rules as $elementname => $rules) {
420 $elementtype = $mform->getElementType($elementname);
421 //If element is of type filepicker then do validation
422 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
423 //Check if rule defined is required rule
424 foreach ($rules as $rule) {
425 if ($rule['type'] == 'required') {
426 $draftid = (int)$mform->getSubmitValue($elementname);
427 $fs = get_file_storage();
428 $context = context_user::instance($USER->id);
429 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
430 $errors[$elementname] = $rule['message'];
436 // Check all the filemanager elements to make sure they do not have too many
437 // files in them.
438 foreach ($mform->_elements as $element) {
439 if ($element->_type == 'filemanager') {
440 $maxfiles = $element->getMaxfiles();
441 if ($maxfiles > 0) {
442 $draftid = (int)$element->getValue();
443 $fs = get_file_storage();
444 $context = context_user::instance($USER->id);
445 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
446 if (count($files) > $maxfiles) {
447 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
452 if (empty($errors)) {
453 return true;
454 } else {
455 return $errors;
460 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
461 * form definition (new entry form); this function is used to load in data where values
462 * already exist and data is being edited (edit entry form).
464 * note: $slashed param removed
466 * @param stdClass|array $default_values object or array of default values
468 function set_data($default_values) {
469 if (is_object($default_values)) {
470 $default_values = (array)$default_values;
472 $this->_form->setDefaults($default_values);
476 * Check that form was submitted. Does not check validity of submitted data.
478 * @return bool true if form properly submitted
480 function is_submitted() {
481 return $this->_form->isSubmitted();
485 * Checks if button pressed is not for submitting the form
487 * @staticvar bool $nosubmit keeps track of no submit button
488 * @return bool
490 function no_submit_button_pressed(){
491 static $nosubmit = null; // one check is enough
492 if (!is_null($nosubmit)){
493 return $nosubmit;
495 $mform =& $this->_form;
496 $nosubmit = false;
497 if (!$this->is_submitted()){
498 return false;
500 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
501 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
502 $nosubmit = true;
503 break;
506 return $nosubmit;
511 * Check that form data is valid.
512 * You should almost always use this, rather than {@link validate_defined_fields}
514 * @return bool true if form data valid
516 function is_validated() {
517 //finalize the form definition before any processing
518 if (!$this->_definition_finalized) {
519 $this->_definition_finalized = true;
520 $this->definition_after_data();
523 return $this->validate_defined_fields();
527 * Validate the form.
529 * You almost always want to call {@link is_validated} instead of this
530 * because it calls {@link definition_after_data} first, before validating the form,
531 * which is what you want in 99% of cases.
533 * This is provided as a separate function for those special cases where
534 * you want the form validated before definition_after_data is called
535 * for example, to selectively add new elements depending on a no_submit_button press,
536 * but only when the form is valid when the no_submit_button is pressed,
538 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
539 * is NOT to validate the form when a no submit button has been pressed.
540 * pass true here to override this behaviour
542 * @return bool true if form data valid
544 function validate_defined_fields($validateonnosubmit=false) {
545 $mform =& $this->_form;
546 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
547 return false;
548 } elseif ($this->_validated === null) {
549 $internal_val = $mform->validate();
551 $files = array();
552 $file_val = $this->_validate_files($files);
553 //check draft files for validation and flag them if required files
554 //are not in draft area.
555 $draftfilevalue = $this->validate_draft_files();
557 if ($file_val !== true && $draftfilevalue !== true) {
558 $file_val = array_merge($file_val, $draftfilevalue);
559 } else if ($draftfilevalue !== true) {
560 $file_val = $draftfilevalue;
561 } //default is file_val, so no need to assign.
563 if ($file_val !== true) {
564 if (!empty($file_val)) {
565 foreach ($file_val as $element=>$msg) {
566 $mform->setElementError($element, $msg);
569 $file_val = false;
572 $data = $mform->exportValues();
573 $moodle_val = $this->validation($data, $files);
574 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
575 // non-empty array means errors
576 foreach ($moodle_val as $element=>$msg) {
577 $mform->setElementError($element, $msg);
579 $moodle_val = false;
581 } else {
582 // anything else means validation ok
583 $moodle_val = true;
586 $this->_validated = ($internal_val and $moodle_val and $file_val);
588 return $this->_validated;
592 * Return true if a cancel button has been pressed resulting in the form being submitted.
594 * @return bool true if a cancel button has been pressed
596 function is_cancelled(){
597 $mform =& $this->_form;
598 if ($mform->isSubmitted()){
599 foreach ($mform->_cancelButtons as $cancelbutton){
600 if (optional_param($cancelbutton, 0, PARAM_RAW)){
601 return true;
605 return false;
609 * Return submitted data if properly submitted or returns NULL if validation fails or
610 * if there is no submitted data.
612 * note: $slashed param removed
614 * @return object submitted data; NULL if not valid or not submitted or cancelled
616 function get_data() {
617 $mform =& $this->_form;
619 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
620 $data = $mform->exportValues();
621 unset($data['sesskey']); // we do not need to return sesskey
622 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
623 if (empty($data)) {
624 return NULL;
625 } else {
626 return (object)$data;
628 } else {
629 return NULL;
634 * Return submitted data without validation or NULL if there is no submitted data.
635 * note: $slashed param removed
637 * @return object submitted data; NULL if not submitted
639 function get_submitted_data() {
640 $mform =& $this->_form;
642 if ($this->is_submitted()) {
643 $data = $mform->exportValues();
644 unset($data['sesskey']); // we do not need to return sesskey
645 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
646 if (empty($data)) {
647 return NULL;
648 } else {
649 return (object)$data;
651 } else {
652 return NULL;
657 * Save verified uploaded files into directory. Upload process can be customised from definition()
659 * @deprecated since Moodle 2.0
660 * @todo MDL-31294 remove this api
661 * @see moodleform::save_stored_file()
662 * @see moodleform::save_file()
663 * @param string $destination path where file should be stored
664 * @return bool Always false
666 function save_files($destination) {
667 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
668 return false;
672 * Returns name of uploaded file.
674 * @param string $elname first element if null
675 * @return string|bool false in case of failure, string if ok
677 function get_new_filename($elname=null) {
678 global $USER;
680 if (!$this->is_submitted() or !$this->is_validated()) {
681 return false;
684 if (is_null($elname)) {
685 if (empty($_FILES)) {
686 return false;
688 reset($_FILES);
689 $elname = key($_FILES);
692 if (empty($elname)) {
693 return false;
696 $element = $this->_form->getElement($elname);
698 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
699 $values = $this->_form->exportValues($elname);
700 if (empty($values[$elname])) {
701 return false;
703 $draftid = $values[$elname];
704 $fs = get_file_storage();
705 $context = context_user::instance($USER->id);
706 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
707 return false;
709 $file = reset($files);
710 return $file->get_filename();
713 if (!isset($_FILES[$elname])) {
714 return false;
717 return $_FILES[$elname]['name'];
721 * Save file to standard filesystem
723 * @param string $elname name of element
724 * @param string $pathname full path name of file
725 * @param bool $override override file if exists
726 * @return bool success
728 function save_file($elname, $pathname, $override=false) {
729 global $USER;
731 if (!$this->is_submitted() or !$this->is_validated()) {
732 return false;
734 if (file_exists($pathname)) {
735 if ($override) {
736 if (!@unlink($pathname)) {
737 return false;
739 } else {
740 return false;
744 $element = $this->_form->getElement($elname);
746 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
747 $values = $this->_form->exportValues($elname);
748 if (empty($values[$elname])) {
749 return false;
751 $draftid = $values[$elname];
752 $fs = get_file_storage();
753 $context = context_user::instance($USER->id);
754 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
755 return false;
757 $file = reset($files);
759 return $file->copy_content_to($pathname);
761 } else if (isset($_FILES[$elname])) {
762 return copy($_FILES[$elname]['tmp_name'], $pathname);
765 return false;
769 * Returns a temporary file, do not forget to delete after not needed any more.
771 * @param string $elname name of the elmenet
772 * @return string|bool either string or false
774 function save_temp_file($elname) {
775 if (!$this->get_new_filename($elname)) {
776 return false;
778 if (!$dir = make_temp_directory('forms')) {
779 return false;
781 if (!$tempfile = tempnam($dir, 'tempup_')) {
782 return false;
784 if (!$this->save_file($elname, $tempfile, true)) {
785 // something went wrong
786 @unlink($tempfile);
787 return false;
790 return $tempfile;
794 * Get draft files of a form element
795 * This is a protected method which will be used only inside moodleforms
797 * @param string $elname name of element
798 * @return array|bool|null
800 protected function get_draft_files($elname) {
801 global $USER;
803 if (!$this->is_submitted()) {
804 return false;
807 $element = $this->_form->getElement($elname);
809 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
810 $values = $this->_form->exportValues($elname);
811 if (empty($values[$elname])) {
812 return false;
814 $draftid = $values[$elname];
815 $fs = get_file_storage();
816 $context = context_user::instance($USER->id);
817 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
818 return null;
820 return $files;
822 return null;
826 * Save file to local filesystem pool
828 * @param string $elname name of element
829 * @param int $newcontextid id of context
830 * @param string $newcomponent name of the component
831 * @param string $newfilearea name of file area
832 * @param int $newitemid item id
833 * @param string $newfilepath path of file where it get stored
834 * @param string $newfilename use specified filename, if not specified name of uploaded file used
835 * @param bool $overwrite overwrite file if exists
836 * @param int $newuserid new userid if required
837 * @return mixed stored_file object or false if error; may throw exception if duplicate found
839 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
840 $newfilename=null, $overwrite=false, $newuserid=null) {
841 global $USER;
843 if (!$this->is_submitted() or !$this->is_validated()) {
844 return false;
847 if (empty($newuserid)) {
848 $newuserid = $USER->id;
851 $element = $this->_form->getElement($elname);
852 $fs = get_file_storage();
854 if ($element instanceof MoodleQuickForm_filepicker) {
855 $values = $this->_form->exportValues($elname);
856 if (empty($values[$elname])) {
857 return false;
859 $draftid = $values[$elname];
860 $context = context_user::instance($USER->id);
861 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
862 return false;
864 $file = reset($files);
865 if (is_null($newfilename)) {
866 $newfilename = $file->get_filename();
869 if ($overwrite) {
870 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
871 if (!$oldfile->delete()) {
872 return false;
877 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
878 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
879 return $fs->create_file_from_storedfile($file_record, $file);
881 } else if (isset($_FILES[$elname])) {
882 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
884 if ($overwrite) {
885 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
886 if (!$oldfile->delete()) {
887 return false;
892 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
893 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
894 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
897 return false;
901 * Get content of uploaded file.
903 * @param string $elname name of file upload element
904 * @return string|bool false in case of failure, string if ok
906 function get_file_content($elname) {
907 global $USER;
909 if (!$this->is_submitted() or !$this->is_validated()) {
910 return false;
913 $element = $this->_form->getElement($elname);
915 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
916 $values = $this->_form->exportValues($elname);
917 if (empty($values[$elname])) {
918 return false;
920 $draftid = $values[$elname];
921 $fs = get_file_storage();
922 $context = context_user::instance($USER->id);
923 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
924 return false;
926 $file = reset($files);
928 return $file->get_content();
930 } else if (isset($_FILES[$elname])) {
931 return file_get_contents($_FILES[$elname]['tmp_name']);
934 return false;
938 * Print html form.
940 function display() {
941 //finalize the form definition if not yet done
942 if (!$this->_definition_finalized) {
943 $this->_definition_finalized = true;
944 $this->definition_after_data();
947 $this->_form->display();
951 * Renders the html form (same as display, but returns the result).
953 * Note that you can only output this rendered result once per page, as
954 * it contains IDs which must be unique.
956 * @return string HTML code for the form
958 public function render() {
959 ob_start();
960 $this->display();
961 $out = ob_get_contents();
962 ob_end_clean();
963 return $out;
967 * Form definition. Abstract method - always override!
969 protected abstract function definition();
972 * Dummy stub method - override if you need to setup the form depending on current
973 * values. This method is called after definition(), data submission and set_data().
974 * All form setup that is dependent on form values should go in here.
976 function definition_after_data(){
980 * Dummy stub method - override if you needed to perform some extra validation.
981 * If there are errors return array of errors ("fieldname"=>"error message"),
982 * otherwise true if ok.
984 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
986 * @param array $data array of ("fieldname"=>value) of submitted data
987 * @param array $files array of uploaded files "element_name"=>tmp_file_path
988 * @return array of "element_name"=>"error_description" if there are errors,
989 * or an empty array if everything is OK (true allowed for backwards compatibility too).
991 function validation($data, $files) {
992 return array();
996 * Helper used by {@link repeat_elements()}.
998 * @param int $i the index of this element.
999 * @param HTML_QuickForm_element $elementclone
1000 * @param array $namecloned array of names
1002 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1003 $name = $elementclone->getName();
1004 $namecloned[] = $name;
1006 if (!empty($name)) {
1007 $elementclone->setName($name."[$i]");
1010 if (is_a($elementclone, 'HTML_QuickForm_header')) {
1011 $value = $elementclone->_text;
1012 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1014 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1015 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1017 } else {
1018 $value=$elementclone->getLabel();
1019 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1024 * Method to add a repeating group of elements to a form.
1026 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1027 * @param int $repeats no of times to repeat elements initially
1028 * @param array $options a nested array. The first array key is the element name.
1029 * the second array key is the type of option to set, and depend on that option,
1030 * the value takes different forms.
1031 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1032 * 'type' - PARAM_* type.
1033 * 'helpbutton' - array containing the helpbutton params.
1034 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1035 * 'rule' - array containing the addRule arguments after the element name.
1036 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1037 * 'advanced' - whether this element is hidden by 'Show more ...'.
1038 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1039 * @param string $addfieldsname name for button to add more fields
1040 * @param int $addfieldsno how many fields to add at a time
1041 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1042 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1043 * @return int no of repeats of element in this page
1045 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1046 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1047 if ($addstring===null){
1048 $addstring = get_string('addfields', 'form', $addfieldsno);
1049 } else {
1050 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1052 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1053 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1054 if (!empty($addfields)){
1055 $repeats += $addfieldsno;
1057 $mform =& $this->_form;
1058 $mform->registerNoSubmitButton($addfieldsname);
1059 $mform->addElement('hidden', $repeathiddenname, $repeats);
1060 $mform->setType($repeathiddenname, PARAM_INT);
1061 //value not to be overridden by submitted value
1062 $mform->setConstants(array($repeathiddenname=>$repeats));
1063 $namecloned = array();
1064 for ($i = 0; $i < $repeats; $i++) {
1065 foreach ($elementobjs as $elementobj){
1066 $elementclone = fullclone($elementobj);
1067 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1069 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1070 foreach ($elementclone->getElements() as $el) {
1071 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1073 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1076 $mform->addElement($elementclone);
1079 for ($i=0; $i<$repeats; $i++) {
1080 foreach ($options as $elementname => $elementoptions){
1081 $pos=strpos($elementname, '[');
1082 if ($pos!==FALSE){
1083 $realelementname = substr($elementname, 0, $pos)."[$i]";
1084 $realelementname .= substr($elementname, $pos);
1085 }else {
1086 $realelementname = $elementname."[$i]";
1088 foreach ($elementoptions as $option => $params){
1090 switch ($option){
1091 case 'default' :
1092 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1093 break;
1094 case 'helpbutton' :
1095 $params = array_merge(array($realelementname), $params);
1096 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1097 break;
1098 case 'disabledif' :
1099 foreach ($namecloned as $num => $name){
1100 if ($params[0] == $name){
1101 $params[0] = $params[0]."[$i]";
1102 break;
1105 $params = array_merge(array($realelementname), $params);
1106 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1107 break;
1108 case 'rule' :
1109 if (is_string($params)){
1110 $params = array(null, $params, null, 'client');
1112 $params = array_merge(array($realelementname), $params);
1113 call_user_func_array(array(&$mform, 'addRule'), $params);
1114 break;
1116 case 'type':
1117 $mform->setType($realelementname, $params);
1118 break;
1120 case 'expanded':
1121 $mform->setExpanded($realelementname, $params);
1122 break;
1124 case 'advanced' :
1125 $mform->setAdvanced($realelementname, $params);
1126 break;
1131 $mform->addElement('submit', $addfieldsname, $addstring);
1133 if (!$addbuttoninside) {
1134 $mform->closeHeaderBefore($addfieldsname);
1137 return $repeats;
1141 * Adds a link/button that controls the checked state of a group of checkboxes.
1143 * @param int $groupid The id of the group of advcheckboxes this element controls
1144 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1145 * @param array $attributes associative array of HTML attributes
1146 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1148 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1149 global $CFG, $PAGE;
1151 // Name of the controller button
1152 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1153 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1154 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1156 // Set the default text if none was specified
1157 if (empty($text)) {
1158 $text = get_string('selectallornone', 'form');
1161 $mform = $this->_form;
1162 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1163 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1165 $newselectvalue = $selectvalue;
1166 if (is_null($selectvalue)) {
1167 $newselectvalue = $originalValue;
1168 } else if (!is_null($contollerbutton)) {
1169 $newselectvalue = (int) !$selectvalue;
1171 // set checkbox state depending on orignal/submitted value by controoler button
1172 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1173 foreach ($mform->_elements as $element) {
1174 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1175 $element->getAttribute('class') == $checkboxgroupclass &&
1176 !$element->isFrozen()) {
1177 $mform->setConstants(array($element->getName() => $newselectvalue));
1182 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1183 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1184 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1186 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1187 array(
1188 array('groupid' => $groupid,
1189 'checkboxclass' => $checkboxgroupclass,
1190 'checkboxcontroller' => $checkboxcontrollerparam,
1191 'controllerbutton' => $checkboxcontrollername)
1195 require_once("$CFG->libdir/form/submit.php");
1196 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1197 $mform->addElement($submitlink);
1198 $mform->registerNoSubmitButton($checkboxcontrollername);
1199 $mform->setDefault($checkboxcontrollername, $text);
1203 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1204 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1205 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1206 * get data with get_data().
1208 * @param bool $cancel whether to show cancel button, default true
1209 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1211 function add_action_buttons($cancel = true, $submitlabel=null){
1212 if (is_null($submitlabel)){
1213 $submitlabel = get_string('savechanges');
1215 $mform =& $this->_form;
1216 if ($cancel){
1217 //when two elements we need a group
1218 $buttonarray=array();
1219 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1220 $buttonarray[] = &$mform->createElement('cancel');
1221 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1222 $mform->closeHeaderBefore('buttonar');
1223 } else {
1224 //no group needed
1225 $mform->addElement('submit', 'submitbutton', $submitlabel);
1226 $mform->closeHeaderBefore('submitbutton');
1231 * Adds an initialisation call for a standard JavaScript enhancement.
1233 * This function is designed to add an initialisation call for a JavaScript
1234 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1236 * Current options:
1237 * - Selectboxes
1238 * - smartselect: Turns a nbsp indented select box into a custom drop down
1239 * control that supports multilevel and category selection.
1240 * $enhancement = 'smartselect';
1241 * $options = array('selectablecategories' => true|false)
1243 * @since Moodle 2.0
1244 * @param string|element $element form element for which Javascript needs to be initalized
1245 * @param string $enhancement which init function should be called
1246 * @param array $options options passed to javascript
1247 * @param array $strings strings for javascript
1249 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1250 global $PAGE;
1251 if (is_string($element)) {
1252 $element = $this->_form->getElement($element);
1254 if (is_object($element)) {
1255 $element->_generateId();
1256 $elementid = $element->getAttribute('id');
1257 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1258 if (is_array($strings)) {
1259 foreach ($strings as $string) {
1260 if (is_array($string)) {
1261 call_user_func_array(array($PAGE->requires, 'string_for_js'), $string);
1262 } else {
1263 $PAGE->requires->string_for_js($string, 'moodle');
1271 * Returns a JS module definition for the mforms JS
1273 * @return array
1275 public static function get_js_module() {
1276 global $CFG;
1277 return array(
1278 'name' => 'mform',
1279 'fullpath' => '/lib/form/form.js',
1280 'requires' => array('base', 'node')
1285 * Detects elements with missing setType() declerations.
1287 * Finds elements in the form which should a PARAM_ type set and throws a
1288 * developer debug warning for any elements without it. This is to reduce the
1289 * risk of potential security issues by developers mistakenly forgetting to set
1290 * the type.
1292 * @return void
1294 private function detectMissingSetType() {
1295 global $CFG;
1297 if (!$CFG->debugdeveloper) {
1298 // Only for devs.
1299 return;
1302 $mform = $this->_form;
1303 foreach ($mform->_elements as $element) {
1304 $group = false;
1305 $elements = array($element);
1307 if ($element->getType() == 'group') {
1308 $group = $element;
1309 $elements = $element->getElements();
1312 foreach ($elements as $index => $element) {
1313 switch ($element->getType()) {
1314 case 'hidden':
1315 case 'text':
1316 case 'url':
1317 if ($group) {
1318 $name = $group->getElementName($index);
1319 } else {
1320 $name = $element->getName();
1322 $key = $name;
1323 $found = array_key_exists($key, $mform->_types);
1324 // For repeated elements we need to look for
1325 // the "main" type, not for the one present
1326 // on each repetition. All the stuff in formslib
1327 // (repeat_elements(), updateSubmission()... seems
1328 // to work that way.
1329 while (!$found && strrpos($key, '[') !== false) {
1330 $pos = strrpos($key, '[');
1331 $key = substr($key, 0, $pos);
1332 $found = array_key_exists($key, $mform->_types);
1334 if (!$found) {
1335 debugging("Did you remember to call setType() for '$name'? ".
1336 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1338 break;
1345 * Used by tests to simulate submitted form data submission from the user.
1347 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1348 * get_data.
1350 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1351 * global arrays after each test.
1353 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1354 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1355 * @param string $method 'post' or 'get', defaults to 'post'.
1356 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1357 * a different value here for some forms that are used more than once on the
1358 * same page.
1360 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1361 $formidentifier = null) {
1362 $_FILES = $simulatedsubmittedfiles;
1363 if ($formidentifier === null) {
1364 $formidentifier = get_called_class();
1366 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1367 $simulatedsubmitteddata['sesskey'] = sesskey();
1368 if (strtolower($method) === 'get') {
1369 $_GET = $simulatedsubmitteddata;
1370 } else {
1371 $_POST = $simulatedsubmitteddata;
1377 * MoodleQuickForm implementation
1379 * You never extend this class directly. The class methods of this class are available from
1380 * the private $this->_form property on moodleform and its children. You generally only
1381 * call methods on this class from within abstract methods that you override on moodleform such
1382 * as definition and definition_after_data
1384 * @package core_form
1385 * @category form
1386 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1387 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1389 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1390 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1391 var $_types = array();
1393 /** @var array dependent state for the element/'s */
1394 var $_dependencies = array();
1396 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1397 var $_noSubmitButtons=array();
1399 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1400 var $_cancelButtons=array();
1402 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1403 var $_advancedElements = array();
1406 * Array whose keys are element names and values are the desired collapsible state.
1407 * True for collapsed, False for expanded. If not present, set to default in
1408 * {@link self::accept()}.
1410 * @var array
1412 var $_collapsibleElements = array();
1415 * Whether to enable shortforms for this form
1417 * @var boolean
1419 var $_disableShortforms = false;
1421 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1422 protected $_use_form_change_checker = true;
1425 * The form name is derived from the class name of the wrapper minus the trailing form
1426 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1427 * @var string
1429 var $_formName = '';
1432 * String with the html for hidden params passed in as part of a moodle_url
1433 * object for the action. Output in the form.
1434 * @var string
1436 var $_pageparams = '';
1439 * Whether the form contains any client-side validation or not.
1440 * @var bool
1442 protected $clientvalidation = false;
1445 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1447 * @staticvar int $formcounter counts number of forms
1448 * @param string $formName Form's name.
1449 * @param string $method Form's method defaults to 'POST'
1450 * @param string|moodle_url $action Form's action
1451 * @param string $target (optional)Form's target defaults to none
1452 * @param mixed $attributes (optional)Extra attributes for <form> tag
1454 public function __construct($formName, $method, $action, $target='', $attributes=null) {
1455 global $CFG, $OUTPUT;
1457 static $formcounter = 1;
1459 // TODO MDL-52313 Replace with the call to parent::__construct().
1460 HTML_Common::__construct($attributes);
1461 $target = empty($target) ? array() : array('target' => $target);
1462 $this->_formName = $formName;
1463 if (is_a($action, 'moodle_url')){
1464 $this->_pageparams = html_writer::input_hidden_params($action);
1465 $action = $action->out_omit_querystring();
1466 } else {
1467 $this->_pageparams = '';
1469 // No 'name' atttribute for form in xhtml strict :
1470 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1471 if (is_null($this->getAttribute('id'))) {
1472 $attributes['id'] = 'mform' . $formcounter;
1474 $formcounter++;
1475 $this->updateAttributes($attributes);
1477 // This is custom stuff for Moodle :
1478 $oldclass= $this->getAttribute('class');
1479 if (!empty($oldclass)){
1480 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1481 }else {
1482 $this->updateAttributes(array('class'=>'mform'));
1484 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1485 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1486 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1490 * Old syntax of class constructor. Deprecated in PHP7.
1492 * @deprecated since Moodle 3.1
1494 public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1495 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1496 self::__construct($formName, $method, $action, $target, $attributes);
1500 * Use this method to indicate an element in a form is an advanced field. If items in a form
1501 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1502 * form so the user can decide whether to display advanced form controls.
1504 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1506 * @param string $elementName group or element name (not the element name of something inside a group).
1507 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1509 function setAdvanced($elementName, $advanced = true) {
1510 if ($advanced){
1511 $this->_advancedElements[$elementName]='';
1512 } elseif (isset($this->_advancedElements[$elementName])) {
1513 unset($this->_advancedElements[$elementName]);
1518 * Use this method to indicate that the fieldset should be shown as expanded.
1519 * The method is applicable to header elements only.
1521 * @param string $headername header element name
1522 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1523 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1524 * the form was submitted.
1525 * @return void
1527 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1528 if (empty($headername)) {
1529 return;
1531 $element = $this->getElement($headername);
1532 if ($element->getType() != 'header') {
1533 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1534 return;
1536 if (!$headerid = $element->getAttribute('id')) {
1537 $element->_generateId();
1538 $headerid = $element->getAttribute('id');
1540 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1541 // See if the form has been submitted already.
1542 $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1543 if (!$ignoreuserstate && $formexpanded != -1) {
1544 // Override expanded state with the form variable.
1545 $expanded = $formexpanded;
1547 // Create the form element for storing expanded state.
1548 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1549 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1550 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1552 $this->_collapsibleElements[$headername] = !$expanded;
1556 * Use this method to add show more/less status element required for passing
1557 * over the advanced elements visibility status on the form submission.
1559 * @param string $headerName header element name.
1560 * @param boolean $showmore default false sets the advanced elements to be hidden.
1562 function addAdvancedStatusElement($headerid, $showmore=false){
1563 // Add extra hidden element to store advanced items state for each section.
1564 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1565 // See if we the form has been submitted already.
1566 $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1567 if (!$showmore && $formshowmore != -1) {
1568 // Override showmore state with the form variable.
1569 $showmore = $formshowmore;
1571 // Create the form element for storing advanced items state.
1572 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1573 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1574 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1579 * This function has been deprecated. Show advanced has been replaced by
1580 * "Show more.../Show less..." in the shortforms javascript module.
1582 * @deprecated since Moodle 2.5
1583 * @param bool $showadvancedNow if true will show advanced elements.
1585 function setShowAdvanced($showadvancedNow = null){
1586 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1590 * This function has been deprecated. Show advanced has been replaced by
1591 * "Show more.../Show less..." in the shortforms javascript module.
1593 * @deprecated since Moodle 2.5
1594 * @return bool (Always false)
1596 function getShowAdvanced(){
1597 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1598 return false;
1602 * Use this method to indicate that the form will not be using shortforms.
1604 * @param boolean $disable default true, controls if the shortforms are disabled.
1606 function setDisableShortforms ($disable = true) {
1607 $this->_disableShortforms = $disable;
1611 * Call this method if you don't want the formchangechecker JavaScript to be
1612 * automatically initialised for this form.
1614 public function disable_form_change_checker() {
1615 $this->_use_form_change_checker = false;
1619 * If you have called {@link disable_form_change_checker()} then you can use
1620 * this method to re-enable it. It is enabled by default, so normally you don't
1621 * need to call this.
1623 public function enable_form_change_checker() {
1624 $this->_use_form_change_checker = true;
1628 * @return bool whether this form should automatically initialise
1629 * formchangechecker for itself.
1631 public function is_form_change_checker_enabled() {
1632 return $this->_use_form_change_checker;
1636 * Accepts a renderer
1638 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1640 function accept(&$renderer) {
1641 if (method_exists($renderer, 'setAdvancedElements')){
1642 //Check for visible fieldsets where all elements are advanced
1643 //and mark these headers as advanced as well.
1644 //Also mark all elements in a advanced header as advanced.
1645 $stopFields = $renderer->getStopFieldSetElements();
1646 $lastHeader = null;
1647 $lastHeaderAdvanced = false;
1648 $anyAdvanced = false;
1649 $anyError = false;
1650 foreach (array_keys($this->_elements) as $elementIndex){
1651 $element =& $this->_elements[$elementIndex];
1653 // if closing header and any contained element was advanced then mark it as advanced
1654 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1655 if ($anyAdvanced && !is_null($lastHeader)) {
1656 $lastHeader->_generateId();
1657 $this->setAdvanced($lastHeader->getName());
1658 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1660 $lastHeaderAdvanced = false;
1661 unset($lastHeader);
1662 $lastHeader = null;
1663 } elseif ($lastHeaderAdvanced) {
1664 $this->setAdvanced($element->getName());
1667 if ($element->getType()=='header'){
1668 $lastHeader =& $element;
1669 $anyAdvanced = false;
1670 $anyError = false;
1671 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1672 } elseif (isset($this->_advancedElements[$element->getName()])){
1673 $anyAdvanced = true;
1674 if (isset($this->_errors[$element->getName()])) {
1675 $anyError = true;
1679 // the last header may not be closed yet...
1680 if ($anyAdvanced && !is_null($lastHeader)){
1681 $this->setAdvanced($lastHeader->getName());
1682 $lastHeader->_generateId();
1683 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1685 $renderer->setAdvancedElements($this->_advancedElements);
1687 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1689 // Count the number of sections.
1690 $headerscount = 0;
1691 foreach (array_keys($this->_elements) as $elementIndex){
1692 $element =& $this->_elements[$elementIndex];
1693 if ($element->getType() == 'header') {
1694 $headerscount++;
1698 $anyrequiredorerror = false;
1699 $headercounter = 0;
1700 $headername = null;
1701 foreach (array_keys($this->_elements) as $elementIndex){
1702 $element =& $this->_elements[$elementIndex];
1704 if ($element->getType() == 'header') {
1705 $headercounter++;
1706 $element->_generateId();
1707 $headername = $element->getName();
1708 $anyrequiredorerror = false;
1709 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1710 $anyrequiredorerror = true;
1711 } else {
1712 // Do not reset $anyrequiredorerror to false because we do not want any other element
1713 // in this header (fieldset) to possibly revert the state given.
1716 if ($element->getType() == 'header') {
1717 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1718 // By default the first section is always expanded, except if a state has already been set.
1719 $this->setExpanded($headername, true);
1720 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1721 // The second section is always expanded if the form only contains 2 sections),
1722 // except if a state has already been set.
1723 $this->setExpanded($headername, true);
1725 } else if ($anyrequiredorerror) {
1726 // If any error or required field are present within the header, we need to expand it.
1727 $this->setExpanded($headername, true, true);
1728 } else if (!isset($this->_collapsibleElements[$headername])) {
1729 // Define element as collapsed by default.
1730 $this->setExpanded($headername, false);
1734 // Pass the array to renderer object.
1735 $renderer->setCollapsibleElements($this->_collapsibleElements);
1737 parent::accept($renderer);
1741 * Adds one or more element names that indicate the end of a fieldset
1743 * @param string $elementName name of the element
1745 function closeHeaderBefore($elementName){
1746 $renderer =& $this->defaultRenderer();
1747 $renderer->addStopFieldsetElements($elementName);
1751 * Set an element to be forced to flow LTR.
1753 * The element must exist and support this functionality. Also note that
1754 * when setting the type of a field (@link self::setType} we try to guess the
1755 * whether the field should be force to LTR or not. Make sure you're always
1756 * calling this method last.
1758 * @param string $elementname The element name.
1759 * @param bool $value When false, disables force LTR, else enables it.
1761 public function setForceLtr($elementname, $value = true) {
1762 $this->getElement($elementname)->set_force_ltr($value);
1766 * Should be used for all elements of a form except for select, radio and checkboxes which
1767 * clean their own data.
1769 * @param string $elementname
1770 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1771 * {@link lib/moodlelib.php} for defined parameter types
1773 function setType($elementname, $paramtype) {
1774 $this->_types[$elementname] = $paramtype;
1776 // This will not always get it right, but it should be accurate in most cases.
1777 // When inaccurate use setForceLtr().
1778 if (!is_rtl_compatible($paramtype)
1779 && $this->elementExists($elementname)
1780 && ($element =& $this->getElement($elementname))
1781 && method_exists($element, 'set_force_ltr')) {
1783 $element->set_force_ltr(true);
1788 * This can be used to set several types at once.
1790 * @param array $paramtypes types of parameters.
1791 * @see MoodleQuickForm::setType
1793 function setTypes($paramtypes) {
1794 foreach ($paramtypes as $elementname => $paramtype) {
1795 $this->setType($elementname, $paramtype);
1800 * Return the type(s) to use to clean an element.
1802 * In the case where the element has an array as a value, we will try to obtain a
1803 * type defined for that specific key, and recursively until done.
1805 * This method does not work reverse, you cannot pass a nested element and hoping to
1806 * fallback on the clean type of a parent. This method intends to be used with the
1807 * main element, which will generate child types if needed, not the other way around.
1809 * Example scenario:
1811 * You have defined a new repeated element containing a text field called 'foo'.
1812 * By default there will always be 2 occurence of 'foo' in the form. Even though
1813 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1814 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1815 * $mform->setType('foo[0]', PARAM_FLOAT).
1817 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1818 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1819 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1820 * get the default clean type returned (param $default).
1822 * @param string $elementname name of the element.
1823 * @param mixed $value value that should be cleaned.
1824 * @param int $default default constant value to be returned (PARAM_...)
1825 * @return string|array constant value or array of constant values (PARAM_...)
1827 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1828 $type = $default;
1829 if (array_key_exists($elementname, $this->_types)) {
1830 $type = $this->_types[$elementname];
1832 if (is_array($value)) {
1833 $default = $type;
1834 $type = array();
1835 foreach ($value as $subkey => $subvalue) {
1836 $typekey = "$elementname" . "[$subkey]";
1837 if (array_key_exists($typekey, $this->_types)) {
1838 $subtype = $this->_types[$typekey];
1839 } else {
1840 $subtype = $default;
1842 if (is_array($subvalue)) {
1843 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1844 } else {
1845 $type[$subkey] = $subtype;
1849 return $type;
1853 * Return the cleaned value using the passed type(s).
1855 * @param mixed $value value that has to be cleaned.
1856 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1857 * @return mixed cleaned up value.
1859 public function getCleanedValue($value, $type) {
1860 if (is_array($type) && is_array($value)) {
1861 foreach ($type as $key => $param) {
1862 $value[$key] = $this->getCleanedValue($value[$key], $param);
1864 } else if (!is_array($type) && !is_array($value)) {
1865 $value = clean_param($value, $type);
1866 } else if (!is_array($type) && is_array($value)) {
1867 $value = clean_param_array($value, $type, true);
1868 } else {
1869 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1871 return $value;
1875 * Updates submitted values
1877 * @param array $submission submitted values
1878 * @param array $files list of files
1880 function updateSubmission($submission, $files) {
1881 $this->_flagSubmitted = false;
1883 if (empty($submission)) {
1884 $this->_submitValues = array();
1885 } else {
1886 foreach ($submission as $key => $s) {
1887 $type = $this->getCleanType($key, $s);
1888 $submission[$key] = $this->getCleanedValue($s, $type);
1890 $this->_submitValues = $submission;
1891 $this->_flagSubmitted = true;
1894 if (empty($files)) {
1895 $this->_submitFiles = array();
1896 } else {
1897 $this->_submitFiles = $files;
1898 $this->_flagSubmitted = true;
1901 // need to tell all elements that they need to update their value attribute.
1902 foreach (array_keys($this->_elements) as $key) {
1903 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1908 * Returns HTML for required elements
1910 * @return string
1912 function getReqHTML(){
1913 return $this->_reqHTML;
1917 * Returns HTML for advanced elements
1919 * @return string
1921 function getAdvancedHTML(){
1922 return $this->_advancedHTML;
1926 * Initializes a default form value. Used to specify the default for a new entry where
1927 * no data is loaded in using moodleform::set_data()
1929 * note: $slashed param removed
1931 * @param string $elementName element name
1932 * @param mixed $defaultValue values for that element name
1934 function setDefault($elementName, $defaultValue){
1935 $this->setDefaults(array($elementName=>$defaultValue));
1939 * Add a help button to element, only one button per element is allowed.
1941 * This is new, simplified and preferable method of setting a help icon on form elements.
1942 * It uses the new $OUTPUT->help_icon().
1944 * Typically, you will provide the same identifier and the component as you have used for the
1945 * label of the element. The string identifier with the _help suffix added is then used
1946 * as the help string.
1948 * There has to be two strings defined:
1949 * 1/ get_string($identifier, $component) - the title of the help page
1950 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1952 * @since Moodle 2.0
1953 * @param string $elementname name of the element to add the item to
1954 * @param string $identifier help string identifier without _help suffix
1955 * @param string $component component name to look the help string in
1956 * @param string $linktext optional text to display next to the icon
1957 * @param bool $suppresscheck set to true if the element may not exist
1959 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1960 global $OUTPUT;
1961 if (array_key_exists($elementname, $this->_elementIndex)) {
1962 $element = $this->_elements[$this->_elementIndex[$elementname]];
1963 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1964 } else if (!$suppresscheck) {
1965 debugging(get_string('nonexistentformelements', 'form', $elementname));
1970 * Set constant value not overridden by _POST or _GET
1971 * note: this does not work for complex names with [] :-(
1973 * @param string $elname name of element
1974 * @param mixed $value
1976 function setConstant($elname, $value) {
1977 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1978 $element =& $this->getElement($elname);
1979 $element->onQuickFormEvent('updateValue', null, $this);
1983 * export submitted values
1985 * @param string $elementList list of elements in form
1986 * @return array
1988 function exportValues($elementList = null){
1989 $unfiltered = array();
1990 if (null === $elementList) {
1991 // iterate over all elements, calling their exportValue() methods
1992 foreach (array_keys($this->_elements) as $key) {
1993 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1994 $varname = $this->_elements[$key]->_attributes['name'];
1995 $value = '';
1996 // If we have a default value then export it.
1997 if (isset($this->_defaultValues[$varname])) {
1998 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
2000 } else {
2001 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
2004 if (is_array($value)) {
2005 // This shit throws a bogus warning in PHP 4.3.x
2006 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2009 } else {
2010 if (!is_array($elementList)) {
2011 $elementList = array_map('trim', explode(',', $elementList));
2013 foreach ($elementList as $elementName) {
2014 $value = $this->exportValue($elementName);
2015 if (@PEAR::isError($value)) {
2016 return $value;
2018 //oh, stock QuickFOrm was returning array of arrays!
2019 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2023 if (is_array($this->_constantValues)) {
2024 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
2026 return $unfiltered;
2030 * This is a bit of a hack, and it duplicates the code in
2031 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
2032 * reliably calling that code. (Think about date selectors, for example.)
2033 * @param string $name the element name.
2034 * @param mixed $value the fixed value to set.
2035 * @return mixed the appropriate array to add to the $unfiltered array.
2037 protected function prepare_fixed_value($name, $value) {
2038 if (null === $value) {
2039 return null;
2040 } else {
2041 if (!strpos($name, '[')) {
2042 return array($name => $value);
2043 } else {
2044 $valueAry = array();
2045 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2046 eval("\$valueAry$myIndex = \$value;");
2047 return $valueAry;
2053 * Adds a validation rule for the given field
2055 * If the element is in fact a group, it will be considered as a whole.
2056 * To validate grouped elements as separated entities,
2057 * use addGroupRule instead of addRule.
2059 * @param string $element Form element name
2060 * @param string $message Message to display for invalid data
2061 * @param string $type Rule type, use getRegisteredRules() to get types
2062 * @param string $format (optional)Required for extra rule data
2063 * @param string $validation (optional)Where to perform validation: "server", "client"
2064 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2065 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2067 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2069 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2070 if ($validation == 'client') {
2071 $this->clientvalidation = true;
2077 * Adds a validation rule for the given group of elements
2079 * Only groups with a name can be assigned a validation rule
2080 * Use addGroupRule when you need to validate elements inside the group.
2081 * Use addRule if you need to validate the group as a whole. In this case,
2082 * the same rule will be applied to all elements in the group.
2083 * Use addRule if you need to validate the group against a function.
2085 * @param string $group Form group name
2086 * @param array|string $arg1 Array for multiple elements or error message string for one element
2087 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2088 * @param string $format (optional)Required for extra rule data
2089 * @param int $howmany (optional)How many valid elements should be in the group
2090 * @param string $validation (optional)Where to perform validation: "server", "client"
2091 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2093 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2095 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2096 if (is_array($arg1)) {
2097 foreach ($arg1 as $rules) {
2098 foreach ($rules as $rule) {
2099 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2100 if ($validation == 'client') {
2101 $this->clientvalidation = true;
2105 } elseif (is_string($arg1)) {
2106 if ($validation == 'client') {
2107 $this->clientvalidation = true;
2113 * Returns the client side validation script
2115 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2116 * and slightly modified to run rules per-element
2117 * Needed to override this because of an error with client side validation of grouped elements.
2119 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2121 function getValidationScript()
2123 global $PAGE;
2125 if (empty($this->_rules) || $this->clientvalidation === false) {
2126 return '';
2129 include_once('HTML/QuickForm/RuleRegistry.php');
2130 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2131 $test = array();
2132 $js_escape = array(
2133 "\r" => '\r',
2134 "\n" => '\n',
2135 "\t" => '\t',
2136 "'" => "\\'",
2137 '"' => '\"',
2138 '\\' => '\\\\'
2141 foreach ($this->_rules as $elementName => $rules) {
2142 foreach ($rules as $rule) {
2143 if ('client' == $rule['validation']) {
2144 unset($element); //TODO: find out how to properly initialize it
2146 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2147 $rule['message'] = strtr($rule['message'], $js_escape);
2149 if (isset($rule['group'])) {
2150 $group =& $this->getElement($rule['group']);
2151 // No JavaScript validation for frozen elements
2152 if ($group->isFrozen()) {
2153 continue 2;
2155 $elements =& $group->getElements();
2156 foreach (array_keys($elements) as $key) {
2157 if ($elementName == $group->getElementName($key)) {
2158 $element =& $elements[$key];
2159 break;
2162 } elseif ($dependent) {
2163 $element = array();
2164 $element[] =& $this->getElement($elementName);
2165 foreach ($rule['dependent'] as $elName) {
2166 $element[] =& $this->getElement($elName);
2168 } else {
2169 $element =& $this->getElement($elementName);
2171 // No JavaScript validation for frozen elements
2172 if (is_object($element) && $element->isFrozen()) {
2173 continue 2;
2174 } elseif (is_array($element)) {
2175 foreach (array_keys($element) as $key) {
2176 if ($element[$key]->isFrozen()) {
2177 continue 3;
2181 //for editor element, [text] is appended to the name.
2182 $fullelementname = $elementName;
2183 if ($element->getType() == 'editor') {
2184 $fullelementname .= '[text]';
2185 //Add format to rule as moodleform check which format is supported by browser
2186 //it is not set anywhere... So small hack to make sure we pass it down to quickform
2187 if (is_null($rule['format'])) {
2188 $rule['format'] = $element->getFormat();
2191 // Fix for bug displaying errors for elements in a group
2192 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2193 $test[$fullelementname][1]=$element;
2194 //end of fix
2199 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2200 // the form, and then that form field gets corrupted by the code that follows.
2201 unset($element);
2203 $js = '
2205 require(["core/event", "jquery"], function(Event, $) {
2207 function qf_errorHandler(element, _qfMsg, escapedName) {
2208 var event = $.Event(Event.Events.FORM_FIELD_VALIDATION);
2209 $(element).trigger(event, _qfMsg);
2210 if (event.isDefaultPrevented()) {
2211 return _qfMsg == \'\';
2212 } else {
2213 // Legacy mforms.
2214 var div = element.parentNode;
2216 if ((div == undefined) || (element.name == undefined)) {
2217 // No checking can be done for undefined elements so let server handle it.
2218 return true;
2221 if (_qfMsg != \'\') {
2222 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2223 if (!errorSpan) {
2224 errorSpan = document.createElement("span");
2225 errorSpan.id = \'id_error_\' + escapedName;
2226 errorSpan.className = "error";
2227 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2228 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2229 document.getElementById(errorSpan.id).focus();
2232 while (errorSpan.firstChild) {
2233 errorSpan.removeChild(errorSpan.firstChild);
2236 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2238 if (div.className.substr(div.className.length - 6, 6) != " error"
2239 && div.className != "error") {
2240 div.className += " error";
2241 linebreak = document.createElement("br");
2242 linebreak.className = "error";
2243 linebreak.id = \'id_error_break_\' + escapedName;
2244 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2247 return false;
2248 } else {
2249 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2250 if (errorSpan) {
2251 errorSpan.parentNode.removeChild(errorSpan);
2253 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2254 if (linebreak) {
2255 linebreak.parentNode.removeChild(linebreak);
2258 if (div.className.substr(div.className.length - 6, 6) == " error") {
2259 div.className = div.className.substr(0, div.className.length - 6);
2260 } else if (div.className == "error") {
2261 div.className = "";
2264 return true;
2265 } // End if.
2266 } // End if.
2267 } // End function.
2269 $validateJS = '';
2270 foreach ($test as $elementName => $jsandelement) {
2271 // Fix for bug displaying errors for elements in a group
2272 //unset($element);
2273 list($jsArr,$element)=$jsandelement;
2274 //end of fix
2275 $escapedElementName = preg_replace_callback(
2276 '/[_\[\]-]/',
2277 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2278 $elementName);
2279 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
2281 $js .= '
2282 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2283 if (undefined == element) {
2284 //required element was not found, then let form be submitted without client side validation
2285 return true;
2287 var value = \'\';
2288 var errFlag = new Array();
2289 var _qfGroups = {};
2290 var _qfMsg = \'\';
2291 var frm = element.parentNode;
2292 if ((undefined != element.name) && (frm != undefined)) {
2293 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2294 frm = frm.parentNode;
2296 ' . join("\n", $jsArr) . '
2297 return qf_errorHandler(element, _qfMsg, escapedName);
2298 } else {
2299 //element name should be defined else error msg will not be displayed.
2300 return true;
2304 document.getElementById(\'' . $element->_attributes['id'] . '\').addEventListener(\'blur\', function(ev) {
2305 ' . $valFunc . '
2307 document.getElementById(\'' . $element->_attributes['id'] . '\').addEventListener(\'change\', function(ev) {
2308 ' . $valFunc . '
2311 $validateJS .= '
2312 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2313 if (!ret && !first_focus) {
2314 first_focus = true;
2315 Y.use(\'moodle-core-event\', function() {
2316 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes['id'] . '\',
2317 elementid: \'id_error_' . $escapedElementName . '\'});
2318 document.getElementById(\'id_error_' . $escapedElementName . '\').focus();
2323 // Fix for bug displaying errors for elements in a group
2324 //unset($element);
2325 //$element =& $this->getElement($elementName);
2326 //end of fix
2327 //$onBlur = $element->getAttribute('onBlur');
2328 //$onChange = $element->getAttribute('onChange');
2329 //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2330 //'onChange' => $onChange . $valFunc));
2332 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2333 $js .= '
2335 function validate_' . $this->_formName . '() {
2336 if (skipClientValidation) {
2337 return true;
2339 var ret = true;
2341 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2342 var first_focus = false;
2343 ' . $validateJS . ';
2344 return ret;
2348 document.getElementById(\'' . $this->_attributes['id'] . '\').addEventListener(\'submit\', function(ev) {
2349 try {
2350 var myValidator = validate_' . $this->_formName . ';
2351 } catch(e) {
2352 return true;
2354 if (typeof window.tinyMCE !== \'undefined\') {
2355 window.tinyMCE.triggerSave();
2357 if (!myValidator()) {
2358 ev.preventDefault();
2365 $PAGE->requires->js_amd_inline($js);
2367 // Global variable used to skip the client validation.
2368 return html_writer::tag('script', 'var skipClientValidation = false;');
2369 } // end func getValidationScript
2372 * Sets default error message
2374 function _setDefaultRuleMessages(){
2375 foreach ($this->_rules as $field => $rulesarr){
2376 foreach ($rulesarr as $key => $rule){
2377 if ($rule['message']===null){
2378 $a=new stdClass();
2379 $a->format=$rule['format'];
2380 $str=get_string('err_'.$rule['type'], 'form', $a);
2381 if (strpos($str, '[[')!==0){
2382 $this->_rules[$field][$key]['message']=$str;
2390 * Get list of attributes which have dependencies
2392 * @return array
2394 function getLockOptionObject(){
2395 $result = array();
2396 foreach ($this->_dependencies as $dependentOn => $conditions){
2397 $result[$dependentOn] = array();
2398 foreach ($conditions as $condition=>$values) {
2399 $result[$dependentOn][$condition] = array();
2400 foreach ($values as $value=>$dependents) {
2401 $result[$dependentOn][$condition][$value] = array();
2402 $i = 0;
2403 foreach ($dependents as $dependent) {
2404 $elements = $this->_getElNamesRecursive($dependent);
2405 if (empty($elements)) {
2406 // probably element inside of some group
2407 $elements = array($dependent);
2409 foreach($elements as $element) {
2410 if ($element == $dependentOn) {
2411 continue;
2413 $result[$dependentOn][$condition][$value][] = $element;
2419 return array($this->getAttribute('id'), $result);
2423 * Get names of element or elements in a group.
2425 * @param HTML_QuickForm_group|element $element element group or element object
2426 * @return array
2428 function _getElNamesRecursive($element) {
2429 if (is_string($element)) {
2430 if (!$this->elementExists($element)) {
2431 return array();
2433 $element = $this->getElement($element);
2436 if (is_a($element, 'HTML_QuickForm_group')) {
2437 $elsInGroup = $element->getElements();
2438 $elNames = array();
2439 foreach ($elsInGroup as $elInGroup){
2440 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2441 // not sure if this would work - groups nested in groups
2442 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2443 } else {
2444 $elNames[] = $element->getElementName($elInGroup->getName());
2448 } else if (is_a($element, 'HTML_QuickForm_header')) {
2449 return array();
2451 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2452 return array();
2454 } else if (method_exists($element, 'getPrivateName') &&
2455 !($element instanceof HTML_QuickForm_advcheckbox)) {
2456 // The advcheckbox element implements a method called getPrivateName,
2457 // but in a way that is not compatible with the generic API, so we
2458 // have to explicitly exclude it.
2459 return array($element->getPrivateName());
2461 } else {
2462 $elNames = array($element->getName());
2465 return $elNames;
2469 * Adds a dependency for $elementName which will be disabled if $condition is met.
2470 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2471 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2472 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2473 * of the $dependentOn element is $condition (such as equal) to $value.
2475 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2476 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2477 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2479 * @param string $elementName the name of the element which will be disabled
2480 * @param string $dependentOn the name of the element whose state will be checked for condition
2481 * @param string $condition the condition to check
2482 * @param mixed $value used in conjunction with condition.
2484 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2485 // Multiple selects allow for a multiple selection, we transform the array to string here as
2486 // an array cannot be used as a key in an associative array.
2487 if (is_array($value)) {
2488 $value = implode('|', $value);
2490 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2491 $this->_dependencies[$dependentOn] = array();
2493 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2494 $this->_dependencies[$dependentOn][$condition] = array();
2496 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2497 $this->_dependencies[$dependentOn][$condition][$value] = array();
2499 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2503 * Registers button as no submit button
2505 * @param string $buttonname name of the button
2507 function registerNoSubmitButton($buttonname){
2508 $this->_noSubmitButtons[]=$buttonname;
2512 * Checks if button is a no submit button, i.e it doesn't submit form
2514 * @param string $buttonname name of the button to check
2515 * @return bool
2517 function isNoSubmitButton($buttonname){
2518 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2522 * Registers a button as cancel button
2524 * @param string $addfieldsname name of the button
2526 function _registerCancelButton($addfieldsname){
2527 $this->_cancelButtons[]=$addfieldsname;
2531 * Displays elements without HTML input tags.
2532 * This method is different to freeze() in that it makes sure no hidden
2533 * elements are included in the form.
2534 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2536 * This function also removes all previously defined rules.
2538 * @param string|array $elementList array or string of element(s) to be frozen
2539 * @return object|bool if element list is not empty then return error object, else true
2541 function hardFreeze($elementList=null)
2543 if (!isset($elementList)) {
2544 $this->_freezeAll = true;
2545 $elementList = array();
2546 } else {
2547 if (!is_array($elementList)) {
2548 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2550 $elementList = array_flip($elementList);
2553 foreach (array_keys($this->_elements) as $key) {
2554 $name = $this->_elements[$key]->getName();
2555 if ($this->_freezeAll || isset($elementList[$name])) {
2556 $this->_elements[$key]->freeze();
2557 $this->_elements[$key]->setPersistantFreeze(false);
2558 unset($elementList[$name]);
2560 // remove all rules
2561 $this->_rules[$name] = array();
2562 // if field is required, remove the rule
2563 $unset = array_search($name, $this->_required);
2564 if ($unset !== false) {
2565 unset($this->_required[$unset]);
2570 if (!empty($elementList)) {
2571 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);
2573 return true;
2577 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2579 * This function also removes all previously defined rules of elements it freezes.
2581 * @throws HTML_QuickForm_Error
2582 * @param array $elementList array or string of element(s) not to be frozen
2583 * @return bool returns true
2585 function hardFreezeAllVisibleExcept($elementList)
2587 $elementList = array_flip($elementList);
2588 foreach (array_keys($this->_elements) as $key) {
2589 $name = $this->_elements[$key]->getName();
2590 $type = $this->_elements[$key]->getType();
2592 if ($type == 'hidden'){
2593 // leave hidden types as they are
2594 } elseif (!isset($elementList[$name])) {
2595 $this->_elements[$key]->freeze();
2596 $this->_elements[$key]->setPersistantFreeze(false);
2598 // remove all rules
2599 $this->_rules[$name] = array();
2600 // if field is required, remove the rule
2601 $unset = array_search($name, $this->_required);
2602 if ($unset !== false) {
2603 unset($this->_required[$unset]);
2607 return true;
2611 * Tells whether the form was already submitted
2613 * This is useful since the _submitFiles and _submitValues arrays
2614 * may be completely empty after the trackSubmit value is removed.
2616 * @return bool
2618 function isSubmitted()
2620 return parent::isSubmitted() && (!$this->isFrozen());
2625 * MoodleQuickForm renderer
2627 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2628 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2630 * Stylesheet is part of standard theme and should be automatically included.
2632 * @package core_form
2633 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2636 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2638 /** @var array Element template array */
2639 var $_elementTemplates;
2642 * Template used when opening a hidden fieldset
2643 * (i.e. a fieldset that is opened when there is no header element)
2644 * @var string
2646 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2648 /** @var string Header Template string */
2649 var $_headerTemplate =
2650 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2652 /** @var string Template used when opening a fieldset */
2653 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2655 /** @var string Template used when closing a fieldset */
2656 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2658 /** @var string Required Note template string */
2659 var $_requiredNoteTemplate =
2660 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2663 * Collapsible buttons string template.
2665 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2666 * until the Javascript has been fully loaded.
2668 * @var string
2670 var $_collapseButtonsTemplate =
2671 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2674 * Array whose keys are element names. If the key exists this is a advanced element
2676 * @var array
2678 var $_advancedElements = array();
2681 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2683 * @var array
2685 var $_collapsibleElements = array();
2688 * @var string Contains the collapsible buttons to add to the form.
2690 var $_collapseButtons = '';
2693 * Constructor
2695 public function __construct() {
2696 // switch next two lines for ol li containers for form items.
2697 // $this->_elementTemplates=array('default'=>"\n\t\t".'<li class="fitem"><label>{label}{help}<!-- BEGIN required -->{req}<!-- END required --></label><div class="qfelement<!-- BEGIN error --> error<!-- END error --> {typeclass}"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></li>');
2698 $this->_elementTemplates = array(
2699 'default' => "\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{typeclass} {emptylabel} {class}" {aria-live}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {typeclass}<!-- BEGIN error --> error<!-- END error -->" data-fieldtype="{type}"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2701 'actionbuttons' => "\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{typeclass} {class}"><div class="felement {typeclass}" data-fieldtype="{type}">{element}</div></div>',
2703 'fieldset' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {class}<!-- BEGIN required --> required<!-- END required --> fitem_{typeclass} {emptylabel}"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {typeclass}<!-- BEGIN error --> error<!-- END error -->" data-fieldtype="{type}"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2705 'static' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}"><div class="fitemtitle"><div class="fstaticlabel">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->" data-fieldtype="static"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2707 'warning' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}">{element}</div>',
2709 'nodisplay' => '');
2711 parent::__construct();
2715 * Old syntax of class constructor. Deprecated in PHP7.
2717 * @deprecated since Moodle 3.1
2719 public function MoodleQuickForm_Renderer() {
2720 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2721 self::__construct();
2725 * Set element's as adavance element
2727 * @param array $elements form elements which needs to be grouped as advance elements.
2729 function setAdvancedElements($elements){
2730 $this->_advancedElements = $elements;
2734 * Setting collapsible elements
2736 * @param array $elements
2738 function setCollapsibleElements($elements) {
2739 $this->_collapsibleElements = $elements;
2743 * What to do when starting the form
2745 * @param MoodleQuickForm $form reference of the form
2747 function startForm(&$form){
2748 global $PAGE;
2749 $this->_reqHTML = $form->getReqHTML();
2750 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2751 $this->_advancedHTML = $form->getAdvancedHTML();
2752 $this->_collapseButtons = '';
2753 $formid = $form->getAttribute('id');
2754 parent::startForm($form);
2755 if ($form->isFrozen()){
2756 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2757 } else {
2758 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2759 $this->_hiddenHtml .= $form->_pageparams;
2762 if ($form->is_form_change_checker_enabled()) {
2763 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2764 'M.core_formchangechecker.init',
2765 array(array(
2766 'formid' => $formid
2769 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2771 if (!empty($this->_collapsibleElements)) {
2772 if (count($this->_collapsibleElements) > 1) {
2773 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2774 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2775 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2777 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2779 if (!empty($this->_advancedElements)){
2780 $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2781 $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2786 * Create advance group of elements
2788 * @param MoodleQuickForm_group $group Passed by reference
2789 * @param bool $required if input is required field
2790 * @param string $error error message to display
2792 function startGroup(&$group, $required, $error){
2793 global $OUTPUT;
2795 // Make sure the element has an id.
2796 $group->_generateId();
2798 // Prepend 'fgroup_' to the ID we generated.
2799 $groupid = 'fgroup_' . $group->getAttribute('id');
2801 // Update the ID.
2802 $group->updateAttributes(array('id' => $groupid));
2803 $advanced = isset($this->_advancedElements[$group->getName()]);
2805 $html = $OUTPUT->mform_element($group, $required, $advanced, $error, false);
2806 $fromtemplate = !empty($html);
2807 if (!$fromtemplate) {
2808 if (method_exists($group, 'getElementTemplateType')) {
2809 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2810 } else {
2811 $html = $this->_elementTemplates['default'];
2814 if (isset($this->_advancedElements[$group->getName()])) {
2815 $html = str_replace(' {advanced}', ' advanced', $html);
2816 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
2817 } else {
2818 $html = str_replace(' {advanced}', '', $html);
2819 $html = str_replace('{advancedimg}', '', $html);
2821 if (method_exists($group, 'getHelpButton')) {
2822 $html = str_replace('{help}', $group->getHelpButton(), $html);
2823 } else {
2824 $html = str_replace('{help}', '', $html);
2826 $html = str_replace('{id}', $group->getAttribute('id'), $html);
2827 $html = str_replace('{name}', $group->getName(), $html);
2828 $html = str_replace('{typeclass}', 'fgroup', $html);
2829 $html = str_replace('{type}', 'group', $html);
2830 $html = str_replace('{class}', $group->getAttribute('class'), $html);
2831 $emptylabel = '';
2832 if ($group->getLabel() == '') {
2833 $emptylabel = 'femptylabel';
2835 $html = str_replace('{emptylabel}', $emptylabel, $html);
2837 $this->_templates[$group->getName()] = $html;
2838 // Fix for bug in tableless quickforms that didn't allow you to stop a
2839 // fieldset before a group of elements.
2840 // if the element name indicates the end of a fieldset, close the fieldset
2841 if (in_array($group->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
2842 $this->_html .= $this->_closeFieldsetTemplate;
2843 $this->_fieldsetsOpen--;
2845 if (!$fromtemplate) {
2846 parent::startGroup($group, $required, $error);
2847 } else {
2848 $this->_html .= $html;
2853 * Renders element
2855 * @param HTML_QuickForm_element $element element
2856 * @param bool $required if input is required field
2857 * @param string $error error message to display
2859 function renderElement(&$element, $required, $error){
2860 global $OUTPUT;
2862 // Make sure the element has an id.
2863 $element->_generateId();
2864 $advanced = isset($this->_advancedElements[$element->getName()]);
2866 $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
2867 $fromtemplate = !empty($html);
2868 if (!$fromtemplate) {
2869 // Adding stuff to place holders in template
2870 // check if this is a group element first.
2871 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2872 // So it gets substitutions for *each* element.
2873 $html = $this->_groupElementTemplate;
2874 } else if (method_exists($element, 'getElementTemplateType')) {
2875 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2876 } else {
2877 $html = $this->_elementTemplates['default'];
2879 if (isset($this->_advancedElements[$element->getName()])) {
2880 $html = str_replace(' {advanced}', ' advanced', $html);
2881 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2882 } else {
2883 $html = str_replace(' {advanced}', '', $html);
2884 $html = str_replace(' {aria-live}', '', $html);
2886 if (isset($this->_advancedElements[$element->getName()]) || $element->getName() == 'mform_showadvanced') {
2887 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
2888 } else {
2889 $html = str_replace('{advancedimg}', '', $html);
2891 $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2892 $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
2893 $html = str_replace('{type}', $element->getType(), $html);
2894 $html = str_replace('{name}', $element->getName(), $html);
2895 $html = str_replace('{class}', $element->getAttribute('class'), $html);
2896 $emptylabel = '';
2897 if ($element->getLabel() == '') {
2898 $emptylabel = 'femptylabel';
2900 $html = str_replace('{emptylabel}', $emptylabel, $html);
2901 if (method_exists($element, 'getHelpButton')) {
2902 $html = str_replace('{help}', $element->getHelpButton(), $html);
2903 } else {
2904 $html = str_replace('{help}', '', $html);
2906 } else {
2907 if ($this->_inGroup) {
2908 $this->_groupElementTemplate = $html;
2911 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2912 $this->_groupElementTemplate = $html;
2913 } else if (!isset($this->_templates[$element->getName()])) {
2914 $this->_templates[$element->getName()] = $html;
2917 if (!$fromtemplate) {
2918 parent::renderElement($element, $required, $error);
2919 } else {
2920 if (in_array($element->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
2921 $this->_html .= $this->_closeFieldsetTemplate;
2922 $this->_fieldsetsOpen--;
2924 $this->_html .= $html;
2929 * Called when visiting a form, after processing all form elements
2930 * Adds required note, form attributes, validation javascript and form content.
2932 * @global moodle_page $PAGE
2933 * @param moodleform $form Passed by reference
2935 function finishForm(&$form){
2936 global $PAGE;
2937 if ($form->isFrozen()){
2938 $this->_hiddenHtml = '';
2940 parent::finishForm($form);
2941 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2942 if (!$form->isFrozen()) {
2943 $args = $form->getLockOptionObject();
2944 if (count($args[1]) > 0) {
2945 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2950 * Called when visiting a header element
2952 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2953 * @global moodle_page $PAGE
2955 function renderHeader(&$header) {
2956 global $PAGE;
2958 $header->_generateId();
2959 $name = $header->getName();
2961 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2962 if (is_null($header->_text)) {
2963 $header_html = '';
2964 } elseif (!empty($name) && isset($this->_templates[$name])) {
2965 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2966 } else {
2967 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2970 if ($this->_fieldsetsOpen > 0) {
2971 $this->_html .= $this->_closeFieldsetTemplate;
2972 $this->_fieldsetsOpen--;
2975 // Define collapsible classes for fieldsets.
2976 $arialive = '';
2977 $fieldsetclasses = array('clearfix');
2978 if (isset($this->_collapsibleElements[$header->getName()])) {
2979 $fieldsetclasses[] = 'collapsible';
2980 if ($this->_collapsibleElements[$header->getName()]) {
2981 $fieldsetclasses[] = 'collapsed';
2985 if (isset($this->_advancedElements[$name])){
2986 $fieldsetclasses[] = 'containsadvancedelements';
2989 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2990 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
2992 $this->_html .= $openFieldsetTemplate . $header_html;
2993 $this->_fieldsetsOpen++;
2997 * Return Array of element names that indicate the end of a fieldset
2999 * @return array
3001 function getStopFieldsetElements(){
3002 return $this->_stopFieldsetElements;
3007 * Required elements validation
3009 * This class overrides QuickForm validation since it allowed space or empty tag as a value
3011 * @package core_form
3012 * @category form
3013 * @copyright 2006 Jamie Pratt <me@jamiep.org>
3014 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3016 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
3018 * Checks if an element is not empty.
3019 * This is a server-side validation, it works for both text fields and editor fields
3021 * @param string $value Value to check
3022 * @param int|string|array $options Not used yet
3023 * @return bool true if value is not empty
3025 function validate($value, $options = null) {
3026 global $CFG;
3027 if (is_array($value) && array_key_exists('text', $value)) {
3028 $value = $value['text'];
3030 if (is_array($value)) {
3031 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
3032 $value = implode('', $value);
3034 $stripvalues = array(
3035 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
3036 '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
3038 if (!empty($CFG->strictformsrequired)) {
3039 $value = preg_replace($stripvalues, '', (string)$value);
3041 if ((string)$value == '') {
3042 return false;
3044 return true;
3048 * This function returns Javascript code used to build client-side validation.
3049 * It checks if an element is not empty.
3051 * @param int $format format of data which needs to be validated.
3052 * @return array
3054 function getValidationScript($format = null) {
3055 global $CFG;
3056 if (!empty($CFG->strictformsrequired)) {
3057 if (!empty($format) && $format == FORMAT_HTML) {
3058 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
3059 } else {
3060 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
3062 } else {
3063 return array('', "{jsVar} == ''");
3069 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
3070 * @name $_HTML_QuickForm_default_renderer
3072 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
3074 /** Please keep this list in alphabetical order. */
3075 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
3076 MoodleQuickForm::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
3077 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
3078 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3079 MoodleQuickForm::registerElementType('course', "$CFG->libdir/form/course.php", 'MoodleQuickForm_course');
3080 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
3081 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
3082 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
3083 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
3084 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
3085 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
3086 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
3087 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
3088 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
3089 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
3090 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
3091 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
3092 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
3093 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
3094 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
3095 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
3096 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
3097 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
3098 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
3099 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
3100 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
3101 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
3102 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
3103 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
3104 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
3105 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
3106 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
3107 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
3108 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
3109 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
3110 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
3111 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
3112 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
3114 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");