Merge branch 'MDL-62181-33-enfix' of git://github.com/mudrd8mz/moodle into MOODLE_33_...
[moodle.git] / lib / formslib.php
blob95f6e84c73e0e269b3fef9fded7faae7c6851d5a
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 // Hook to inject logic after the definition was provided.
215 $this->after_definition();
217 // we have to know all input types before processing submission ;-)
218 $this->_process_submission($method);
222 * Old syntax of class constructor. Deprecated in PHP7.
224 * @deprecated since Moodle 3.1
226 public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
227 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
228 self::__construct($action, $customdata, $method, $target, $attributes, $editable);
232 * It should returns unique identifier for the form.
233 * Currently it will return class name, but in case two same forms have to be
234 * rendered on same page then override function to get unique form identifier.
235 * e.g This is used on multiple self enrollments page.
237 * @return string form identifier.
239 protected function get_form_identifier() {
240 $class = get_class($this);
242 return preg_replace('/[^a-z0-9_]/i', '_', $class);
246 * To autofocus on first form element or first element with error.
248 * @param string $name if this is set then the focus is forced to a field with this name
249 * @return string javascript to select form element with first error or
250 * first element if no errors. Use this as a parameter
251 * when calling print_header
253 function focus($name=NULL) {
254 $form =& $this->_form;
255 $elkeys = array_keys($form->_elementIndex);
256 $error = false;
257 if (isset($form->_errors) && 0 != count($form->_errors)){
258 $errorkeys = array_keys($form->_errors);
259 $elkeys = array_intersect($elkeys, $errorkeys);
260 $error = true;
263 if ($error or empty($name)) {
264 $names = array();
265 while (empty($names) and !empty($elkeys)) {
266 $el = array_shift($elkeys);
267 $names = $form->_getElNamesRecursive($el);
269 if (!empty($names)) {
270 $name = array_shift($names);
274 $focus = '';
275 if (!empty($name)) {
276 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
279 return $focus;
283 * Internal method. Alters submitted data to be suitable for quickforms processing.
284 * Must be called when the form is fully set up.
286 * @param string $method name of the method which alters submitted data
288 function _process_submission($method) {
289 $submission = array();
290 if (!empty($this->_ajaxformdata)) {
291 $submission = $this->_ajaxformdata;
292 } else if ($method == 'post') {
293 if (!empty($_POST)) {
294 $submission = $_POST;
296 } else {
297 $submission = $_GET;
298 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
301 // following trick is needed to enable proper sesskey checks when using GET forms
302 // the _qf__.$this->_formname serves as a marker that form was actually submitted
303 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
304 if (!confirm_sesskey()) {
305 print_error('invalidsesskey');
307 $files = $_FILES;
308 } else {
309 $submission = array();
310 $files = array();
312 $this->detectMissingSetType();
314 $this->_form->updateSubmission($submission, $files);
318 * Internal method - should not be used anywhere.
319 * @deprecated since 2.6
320 * @return array $_POST.
322 protected function _get_post_params() {
323 return $_POST;
327 * Internal method. Validates all old-style deprecated uploaded files.
328 * The new way is to upload files via repository api.
330 * @param array $files list of files to be validated
331 * @return bool|array Success or an array of errors
333 function _validate_files(&$files) {
334 global $CFG, $COURSE;
336 $files = array();
338 if (empty($_FILES)) {
339 // we do not need to do any checks because no files were submitted
340 // note: server side rules do not work for files - use custom verification in validate() instead
341 return true;
344 $errors = array();
345 $filenames = array();
347 // now check that we really want each file
348 foreach ($_FILES as $elname=>$file) {
349 $required = $this->_form->isElementRequired($elname);
351 if ($file['error'] == 4 and $file['size'] == 0) {
352 if ($required) {
353 $errors[$elname] = get_string('required');
355 unset($_FILES[$elname]);
356 continue;
359 if (!empty($file['error'])) {
360 $errors[$elname] = file_get_upload_error($file['error']);
361 unset($_FILES[$elname]);
362 continue;
365 if (!is_uploaded_file($file['tmp_name'])) {
366 // TODO: improve error message
367 $errors[$elname] = get_string('error');
368 unset($_FILES[$elname]);
369 continue;
372 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
373 // hmm, this file was not requested
374 unset($_FILES[$elname]);
375 continue;
378 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
380 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
381 if ($filename === '') {
382 // TODO: improve error message - wrong chars
383 $errors[$elname] = get_string('error');
384 unset($_FILES[$elname]);
385 continue;
387 if (in_array($filename, $filenames)) {
388 // TODO: improve error message - duplicate name
389 $errors[$elname] = get_string('error');
390 unset($_FILES[$elname]);
391 continue;
393 $filenames[] = $filename;
394 $_FILES[$elname]['name'] = $filename;
396 $files[$elname] = $_FILES[$elname]['tmp_name'];
399 // return errors if found
400 if (count($errors) == 0){
401 return true;
403 } else {
404 $files = array();
405 return $errors;
410 * Internal method. Validates filepicker and filemanager files if they are
411 * set as required fields. Also, sets the error message if encountered one.
413 * @return bool|array with errors
415 protected function validate_draft_files() {
416 global $USER;
417 $mform =& $this->_form;
419 $errors = array();
420 //Go through all the required elements and make sure you hit filepicker or
421 //filemanager element.
422 foreach ($mform->_rules as $elementname => $rules) {
423 $elementtype = $mform->getElementType($elementname);
424 //If element is of type filepicker then do validation
425 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
426 //Check if rule defined is required rule
427 foreach ($rules as $rule) {
428 if ($rule['type'] == 'required') {
429 $draftid = (int)$mform->getSubmitValue($elementname);
430 $fs = get_file_storage();
431 $context = context_user::instance($USER->id);
432 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
433 $errors[$elementname] = $rule['message'];
439 // Check all the filemanager elements to make sure they do not have too many
440 // files in them.
441 foreach ($mform->_elements as $element) {
442 if ($element->_type == 'filemanager') {
443 $maxfiles = $element->getMaxfiles();
444 if ($maxfiles > 0) {
445 $draftid = (int)$element->getValue();
446 $fs = get_file_storage();
447 $context = context_user::instance($USER->id);
448 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
449 if (count($files) > $maxfiles) {
450 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
455 if (empty($errors)) {
456 return true;
457 } else {
458 return $errors;
463 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
464 * form definition (new entry form); this function is used to load in data where values
465 * already exist and data is being edited (edit entry form).
467 * note: $slashed param removed
469 * @param stdClass|array $default_values object or array of default values
471 function set_data($default_values) {
472 if (is_object($default_values)) {
473 $default_values = (array)$default_values;
475 $this->_form->setDefaults($default_values);
479 * Check that form was submitted. Does not check validity of submitted data.
481 * @return bool true if form properly submitted
483 function is_submitted() {
484 return $this->_form->isSubmitted();
488 * Checks if button pressed is not for submitting the form
490 * @staticvar bool $nosubmit keeps track of no submit button
491 * @return bool
493 function no_submit_button_pressed(){
494 static $nosubmit = null; // one check is enough
495 if (!is_null($nosubmit)){
496 return $nosubmit;
498 $mform =& $this->_form;
499 $nosubmit = false;
500 if (!$this->is_submitted()){
501 return false;
503 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
504 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
505 $nosubmit = true;
506 break;
509 return $nosubmit;
514 * Check that form data is valid.
515 * You should almost always use this, rather than {@link validate_defined_fields}
517 * @return bool true if form data valid
519 function is_validated() {
520 //finalize the form definition before any processing
521 if (!$this->_definition_finalized) {
522 $this->_definition_finalized = true;
523 $this->definition_after_data();
526 return $this->validate_defined_fields();
530 * Validate the form.
532 * You almost always want to call {@link is_validated} instead of this
533 * because it calls {@link definition_after_data} first, before validating the form,
534 * which is what you want in 99% of cases.
536 * This is provided as a separate function for those special cases where
537 * you want the form validated before definition_after_data is called
538 * for example, to selectively add new elements depending on a no_submit_button press,
539 * but only when the form is valid when the no_submit_button is pressed,
541 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
542 * is NOT to validate the form when a no submit button has been pressed.
543 * pass true here to override this behaviour
545 * @return bool true if form data valid
547 function validate_defined_fields($validateonnosubmit=false) {
548 $mform =& $this->_form;
549 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
550 return false;
551 } elseif ($this->_validated === null) {
552 $internal_val = $mform->validate();
554 $files = array();
555 $file_val = $this->_validate_files($files);
556 //check draft files for validation and flag them if required files
557 //are not in draft area.
558 $draftfilevalue = $this->validate_draft_files();
560 if ($file_val !== true && $draftfilevalue !== true) {
561 $file_val = array_merge($file_val, $draftfilevalue);
562 } else if ($draftfilevalue !== true) {
563 $file_val = $draftfilevalue;
564 } //default is file_val, so no need to assign.
566 if ($file_val !== true) {
567 if (!empty($file_val)) {
568 foreach ($file_val as $element=>$msg) {
569 $mform->setElementError($element, $msg);
572 $file_val = false;
575 $data = $mform->exportValues();
576 $moodle_val = $this->validation($data, $files);
577 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
578 // non-empty array means errors
579 foreach ($moodle_val as $element=>$msg) {
580 $mform->setElementError($element, $msg);
582 $moodle_val = false;
584 } else {
585 // anything else means validation ok
586 $moodle_val = true;
589 $this->_validated = ($internal_val and $moodle_val and $file_val);
591 return $this->_validated;
595 * Return true if a cancel button has been pressed resulting in the form being submitted.
597 * @return bool true if a cancel button has been pressed
599 function is_cancelled(){
600 $mform =& $this->_form;
601 if ($mform->isSubmitted()){
602 foreach ($mform->_cancelButtons as $cancelbutton){
603 if (optional_param($cancelbutton, 0, PARAM_RAW)){
604 return true;
608 return false;
612 * Return submitted data if properly submitted or returns NULL if validation fails or
613 * if there is no submitted data.
615 * note: $slashed param removed
617 * @return object submitted data; NULL if not valid or not submitted or cancelled
619 function get_data() {
620 $mform =& $this->_form;
622 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
623 $data = $mform->exportValues();
624 unset($data['sesskey']); // we do not need to return sesskey
625 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
626 if (empty($data)) {
627 return NULL;
628 } else {
629 return (object)$data;
631 } else {
632 return NULL;
637 * Return submitted data without validation or NULL if there is no submitted data.
638 * note: $slashed param removed
640 * @return object submitted data; NULL if not submitted
642 function get_submitted_data() {
643 $mform =& $this->_form;
645 if ($this->is_submitted()) {
646 $data = $mform->exportValues();
647 unset($data['sesskey']); // we do not need to return sesskey
648 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
649 if (empty($data)) {
650 return NULL;
651 } else {
652 return (object)$data;
654 } else {
655 return NULL;
660 * Save verified uploaded files into directory. Upload process can be customised from definition()
662 * @deprecated since Moodle 2.0
663 * @todo MDL-31294 remove this api
664 * @see moodleform::save_stored_file()
665 * @see moodleform::save_file()
666 * @param string $destination path where file should be stored
667 * @return bool Always false
669 function save_files($destination) {
670 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
671 return false;
675 * Returns name of uploaded file.
677 * @param string $elname first element if null
678 * @return string|bool false in case of failure, string if ok
680 function get_new_filename($elname=null) {
681 global $USER;
683 if (!$this->is_submitted() or !$this->is_validated()) {
684 return false;
687 if (is_null($elname)) {
688 if (empty($_FILES)) {
689 return false;
691 reset($_FILES);
692 $elname = key($_FILES);
695 if (empty($elname)) {
696 return false;
699 $element = $this->_form->getElement($elname);
701 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
702 $values = $this->_form->exportValues($elname);
703 if (empty($values[$elname])) {
704 return false;
706 $draftid = $values[$elname];
707 $fs = get_file_storage();
708 $context = context_user::instance($USER->id);
709 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
710 return false;
712 $file = reset($files);
713 return $file->get_filename();
716 if (!isset($_FILES[$elname])) {
717 return false;
720 return $_FILES[$elname]['name'];
724 * Save file to standard filesystem
726 * @param string $elname name of element
727 * @param string $pathname full path name of file
728 * @param bool $override override file if exists
729 * @return bool success
731 function save_file($elname, $pathname, $override=false) {
732 global $USER;
734 if (!$this->is_submitted() or !$this->is_validated()) {
735 return false;
737 if (file_exists($pathname)) {
738 if ($override) {
739 if (!@unlink($pathname)) {
740 return false;
742 } else {
743 return false;
747 $element = $this->_form->getElement($elname);
749 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
750 $values = $this->_form->exportValues($elname);
751 if (empty($values[$elname])) {
752 return false;
754 $draftid = $values[$elname];
755 $fs = get_file_storage();
756 $context = context_user::instance($USER->id);
757 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
758 return false;
760 $file = reset($files);
762 return $file->copy_content_to($pathname);
764 } else if (isset($_FILES[$elname])) {
765 return copy($_FILES[$elname]['tmp_name'], $pathname);
768 return false;
772 * Returns a temporary file, do not forget to delete after not needed any more.
774 * @param string $elname name of the elmenet
775 * @return string|bool either string or false
777 function save_temp_file($elname) {
778 if (!$this->get_new_filename($elname)) {
779 return false;
781 if (!$dir = make_temp_directory('forms')) {
782 return false;
784 if (!$tempfile = tempnam($dir, 'tempup_')) {
785 return false;
787 if (!$this->save_file($elname, $tempfile, true)) {
788 // something went wrong
789 @unlink($tempfile);
790 return false;
793 return $tempfile;
797 * Get draft files of a form element
798 * This is a protected method which will be used only inside moodleforms
800 * @param string $elname name of element
801 * @return array|bool|null
803 protected function get_draft_files($elname) {
804 global $USER;
806 if (!$this->is_submitted()) {
807 return false;
810 $element = $this->_form->getElement($elname);
812 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
813 $values = $this->_form->exportValues($elname);
814 if (empty($values[$elname])) {
815 return false;
817 $draftid = $values[$elname];
818 $fs = get_file_storage();
819 $context = context_user::instance($USER->id);
820 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
821 return null;
823 return $files;
825 return null;
829 * Save file to local filesystem pool
831 * @param string $elname name of element
832 * @param int $newcontextid id of context
833 * @param string $newcomponent name of the component
834 * @param string $newfilearea name of file area
835 * @param int $newitemid item id
836 * @param string $newfilepath path of file where it get stored
837 * @param string $newfilename use specified filename, if not specified name of uploaded file used
838 * @param bool $overwrite overwrite file if exists
839 * @param int $newuserid new userid if required
840 * @return mixed stored_file object or false if error; may throw exception if duplicate found
842 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
843 $newfilename=null, $overwrite=false, $newuserid=null) {
844 global $USER;
846 if (!$this->is_submitted() or !$this->is_validated()) {
847 return false;
850 if (empty($newuserid)) {
851 $newuserid = $USER->id;
854 $element = $this->_form->getElement($elname);
855 $fs = get_file_storage();
857 if ($element instanceof MoodleQuickForm_filepicker) {
858 $values = $this->_form->exportValues($elname);
859 if (empty($values[$elname])) {
860 return false;
862 $draftid = $values[$elname];
863 $context = context_user::instance($USER->id);
864 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
865 return false;
867 $file = reset($files);
868 if (is_null($newfilename)) {
869 $newfilename = $file->get_filename();
872 if ($overwrite) {
873 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
874 if (!$oldfile->delete()) {
875 return false;
880 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
881 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
882 return $fs->create_file_from_storedfile($file_record, $file);
884 } else if (isset($_FILES[$elname])) {
885 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
887 if ($overwrite) {
888 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
889 if (!$oldfile->delete()) {
890 return false;
895 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
896 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
897 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
900 return false;
904 * Get content of uploaded file.
906 * @param string $elname name of file upload element
907 * @return string|bool false in case of failure, string if ok
909 function get_file_content($elname) {
910 global $USER;
912 if (!$this->is_submitted() or !$this->is_validated()) {
913 return false;
916 $element = $this->_form->getElement($elname);
918 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
919 $values = $this->_form->exportValues($elname);
920 if (empty($values[$elname])) {
921 return false;
923 $draftid = $values[$elname];
924 $fs = get_file_storage();
925 $context = context_user::instance($USER->id);
926 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
927 return false;
929 $file = reset($files);
931 return $file->get_content();
933 } else if (isset($_FILES[$elname])) {
934 return file_get_contents($_FILES[$elname]['tmp_name']);
937 return false;
941 * Print html form.
943 function display() {
944 //finalize the form definition if not yet done
945 if (!$this->_definition_finalized) {
946 $this->_definition_finalized = true;
947 $this->definition_after_data();
950 $this->_form->display();
954 * Renders the html form (same as display, but returns the result).
956 * Note that you can only output this rendered result once per page, as
957 * it contains IDs which must be unique.
959 * @return string HTML code for the form
961 public function render() {
962 ob_start();
963 $this->display();
964 $out = ob_get_contents();
965 ob_end_clean();
966 return $out;
970 * Form definition. Abstract method - always override!
972 protected abstract function definition();
975 * After definition hook.
977 * This is useful for intermediate classes to inject logic after the definition was
978 * provided without requiring developers to call the parent {{@link self::definition()}}
979 * as it's not obvious by design. The 'intermediate' class is 'MyClass extends
980 * IntermediateClass extends moodleform'.
982 * Classes overriding this method should always call the parent. We may not add
983 * anything specifically in this instance of the method, but intermediate classes
984 * are likely to do so, and so it is a good practice to always call the parent.
986 * @return void
988 protected function after_definition() {
992 * Dummy stub method - override if you need to setup the form depending on current
993 * values. This method is called after definition(), data submission and set_data().
994 * All form setup that is dependent on form values should go in here.
996 function definition_after_data(){
1000 * Dummy stub method - override if you needed to perform some extra validation.
1001 * If there are errors return array of errors ("fieldname"=>"error message"),
1002 * otherwise true if ok.
1004 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
1006 * @param array $data array of ("fieldname"=>value) of submitted data
1007 * @param array $files array of uploaded files "element_name"=>tmp_file_path
1008 * @return array of "element_name"=>"error_description" if there are errors,
1009 * or an empty array if everything is OK (true allowed for backwards compatibility too).
1011 function validation($data, $files) {
1012 return array();
1016 * Helper used by {@link repeat_elements()}.
1018 * @param int $i the index of this element.
1019 * @param HTML_QuickForm_element $elementclone
1020 * @param array $namecloned array of names
1022 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1023 $name = $elementclone->getName();
1024 $namecloned[] = $name;
1026 if (!empty($name)) {
1027 $elementclone->setName($name."[$i]");
1030 if (is_a($elementclone, 'HTML_QuickForm_header')) {
1031 $value = $elementclone->_text;
1032 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1034 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1035 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1037 } else {
1038 $value=$elementclone->getLabel();
1039 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1044 * Method to add a repeating group of elements to a form.
1046 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1047 * @param int $repeats no of times to repeat elements initially
1048 * @param array $options a nested array. The first array key is the element name.
1049 * the second array key is the type of option to set, and depend on that option,
1050 * the value takes different forms.
1051 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1052 * 'type' - PARAM_* type.
1053 * 'helpbutton' - array containing the helpbutton params.
1054 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1055 * 'rule' - array containing the addRule arguments after the element name.
1056 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1057 * 'advanced' - whether this element is hidden by 'Show more ...'.
1058 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1059 * @param string $addfieldsname name for button to add more fields
1060 * @param int $addfieldsno how many fields to add at a time
1061 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1062 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1063 * @return int no of repeats of element in this page
1065 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1066 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1067 if ($addstring===null){
1068 $addstring = get_string('addfields', 'form', $addfieldsno);
1069 } else {
1070 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1072 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1073 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1074 if (!empty($addfields)){
1075 $repeats += $addfieldsno;
1077 $mform =& $this->_form;
1078 $mform->registerNoSubmitButton($addfieldsname);
1079 $mform->addElement('hidden', $repeathiddenname, $repeats);
1080 $mform->setType($repeathiddenname, PARAM_INT);
1081 //value not to be overridden by submitted value
1082 $mform->setConstants(array($repeathiddenname=>$repeats));
1083 $namecloned = array();
1084 for ($i = 0; $i < $repeats; $i++) {
1085 foreach ($elementobjs as $elementobj){
1086 $elementclone = fullclone($elementobj);
1087 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1089 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1090 foreach ($elementclone->getElements() as $el) {
1091 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1093 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1096 $mform->addElement($elementclone);
1099 for ($i=0; $i<$repeats; $i++) {
1100 foreach ($options as $elementname => $elementoptions){
1101 $pos=strpos($elementname, '[');
1102 if ($pos!==FALSE){
1103 $realelementname = substr($elementname, 0, $pos)."[$i]";
1104 $realelementname .= substr($elementname, $pos);
1105 }else {
1106 $realelementname = $elementname."[$i]";
1108 foreach ($elementoptions as $option => $params){
1110 switch ($option){
1111 case 'default' :
1112 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1113 break;
1114 case 'helpbutton' :
1115 $params = array_merge(array($realelementname), $params);
1116 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1117 break;
1118 case 'disabledif' :
1119 foreach ($namecloned as $num => $name){
1120 if ($params[0] == $name){
1121 $params[0] = $params[0]."[$i]";
1122 break;
1125 $params = array_merge(array($realelementname), $params);
1126 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1127 break;
1128 case 'rule' :
1129 if (is_string($params)){
1130 $params = array(null, $params, null, 'client');
1132 $params = array_merge(array($realelementname), $params);
1133 call_user_func_array(array(&$mform, 'addRule'), $params);
1134 break;
1136 case 'type':
1137 $mform->setType($realelementname, $params);
1138 break;
1140 case 'expanded':
1141 $mform->setExpanded($realelementname, $params);
1142 break;
1144 case 'advanced' :
1145 $mform->setAdvanced($realelementname, $params);
1146 break;
1151 $mform->addElement('submit', $addfieldsname, $addstring);
1153 if (!$addbuttoninside) {
1154 $mform->closeHeaderBefore($addfieldsname);
1157 return $repeats;
1161 * Adds a link/button that controls the checked state of a group of checkboxes.
1163 * @param int $groupid The id of the group of advcheckboxes this element controls
1164 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1165 * @param array $attributes associative array of HTML attributes
1166 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1168 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1169 global $CFG, $PAGE;
1171 // Name of the controller button
1172 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1173 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1174 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1176 // Set the default text if none was specified
1177 if (empty($text)) {
1178 $text = get_string('selectallornone', 'form');
1181 $mform = $this->_form;
1182 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1183 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1185 $newselectvalue = $selectvalue;
1186 if (is_null($selectvalue)) {
1187 $newselectvalue = $originalValue;
1188 } else if (!is_null($contollerbutton)) {
1189 $newselectvalue = (int) !$selectvalue;
1191 // set checkbox state depending on orignal/submitted value by controoler button
1192 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1193 foreach ($mform->_elements as $element) {
1194 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1195 $element->getAttribute('class') == $checkboxgroupclass &&
1196 !$element->isFrozen()) {
1197 $mform->setConstants(array($element->getName() => $newselectvalue));
1202 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1203 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1204 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1206 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1207 array(
1208 array('groupid' => $groupid,
1209 'checkboxclass' => $checkboxgroupclass,
1210 'checkboxcontroller' => $checkboxcontrollerparam,
1211 'controllerbutton' => $checkboxcontrollername)
1215 require_once("$CFG->libdir/form/submit.php");
1216 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1217 $mform->addElement($submitlink);
1218 $mform->registerNoSubmitButton($checkboxcontrollername);
1219 $mform->setDefault($checkboxcontrollername, $text);
1223 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1224 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1225 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1226 * get data with get_data().
1228 * @param bool $cancel whether to show cancel button, default true
1229 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1231 function add_action_buttons($cancel = true, $submitlabel=null){
1232 if (is_null($submitlabel)){
1233 $submitlabel = get_string('savechanges');
1235 $mform =& $this->_form;
1236 if ($cancel){
1237 //when two elements we need a group
1238 $buttonarray=array();
1239 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1240 $buttonarray[] = &$mform->createElement('cancel');
1241 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1242 $mform->closeHeaderBefore('buttonar');
1243 } else {
1244 //no group needed
1245 $mform->addElement('submit', 'submitbutton', $submitlabel);
1246 $mform->closeHeaderBefore('submitbutton');
1251 * Adds an initialisation call for a standard JavaScript enhancement.
1253 * This function is designed to add an initialisation call for a JavaScript
1254 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1256 * Current options:
1257 * - Selectboxes
1258 * - smartselect: Turns a nbsp indented select box into a custom drop down
1259 * control that supports multilevel and category selection.
1260 * $enhancement = 'smartselect';
1261 * $options = array('selectablecategories' => true|false)
1263 * @param string|element $element form element for which Javascript needs to be initalized
1264 * @param string $enhancement which init function should be called
1265 * @param array $options options passed to javascript
1266 * @param array $strings strings for javascript
1267 * @deprecated since Moodle 3.3 MDL-57471
1269 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1270 debugging('$mform->init_javascript_enhancement() is deprecated and no longer does anything. '.
1271 'smartselect uses should be converted to the searchableselector form element.', DEBUG_DEVELOPER);
1275 * Returns a JS module definition for the mforms JS
1277 * @return array
1279 public static function get_js_module() {
1280 global $CFG;
1281 return array(
1282 'name' => 'mform',
1283 'fullpath' => '/lib/form/form.js',
1284 'requires' => array('base', 'node')
1289 * Detects elements with missing setType() declerations.
1291 * Finds elements in the form which should a PARAM_ type set and throws a
1292 * developer debug warning for any elements without it. This is to reduce the
1293 * risk of potential security issues by developers mistakenly forgetting to set
1294 * the type.
1296 * @return void
1298 private function detectMissingSetType() {
1299 global $CFG;
1301 if (!$CFG->debugdeveloper) {
1302 // Only for devs.
1303 return;
1306 $mform = $this->_form;
1307 foreach ($mform->_elements as $element) {
1308 $group = false;
1309 $elements = array($element);
1311 if ($element->getType() == 'group') {
1312 $group = $element;
1313 $elements = $element->getElements();
1316 foreach ($elements as $index => $element) {
1317 switch ($element->getType()) {
1318 case 'hidden':
1319 case 'text':
1320 case 'url':
1321 if ($group) {
1322 $name = $group->getElementName($index);
1323 } else {
1324 $name = $element->getName();
1326 $key = $name;
1327 $found = array_key_exists($key, $mform->_types);
1328 // For repeated elements we need to look for
1329 // the "main" type, not for the one present
1330 // on each repetition. All the stuff in formslib
1331 // (repeat_elements(), updateSubmission()... seems
1332 // to work that way.
1333 while (!$found && strrpos($key, '[') !== false) {
1334 $pos = strrpos($key, '[');
1335 $key = substr($key, 0, $pos);
1336 $found = array_key_exists($key, $mform->_types);
1338 if (!$found) {
1339 debugging("Did you remember to call setType() for '$name'? ".
1340 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1342 break;
1349 * Used by tests to simulate submitted form data submission from the user.
1351 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1352 * get_data.
1354 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1355 * global arrays after each test.
1357 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1358 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1359 * @param string $method 'post' or 'get', defaults to 'post'.
1360 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1361 * a different value here for some forms that are used more than once on the
1362 * same page.
1364 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1365 $formidentifier = null) {
1366 $_FILES = $simulatedsubmittedfiles;
1367 if ($formidentifier === null) {
1368 $formidentifier = get_called_class();
1369 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1371 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1372 $simulatedsubmitteddata['sesskey'] = sesskey();
1373 if (strtolower($method) === 'get') {
1374 $_GET = $simulatedsubmitteddata;
1375 } else {
1376 $_POST = $simulatedsubmitteddata;
1382 * MoodleQuickForm implementation
1384 * You never extend this class directly. The class methods of this class are available from
1385 * the private $this->_form property on moodleform and its children. You generally only
1386 * call methods on this class from within abstract methods that you override on moodleform such
1387 * as definition and definition_after_data
1389 * @package core_form
1390 * @category form
1391 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1394 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1395 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1396 var $_types = array();
1398 /** @var array dependent state for the element/'s */
1399 var $_dependencies = array();
1401 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1402 var $_noSubmitButtons=array();
1404 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1405 var $_cancelButtons=array();
1407 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1408 var $_advancedElements = array();
1411 * Array whose keys are element names and values are the desired collapsible state.
1412 * True for collapsed, False for expanded. If not present, set to default in
1413 * {@link self::accept()}.
1415 * @var array
1417 var $_collapsibleElements = array();
1420 * Whether to enable shortforms for this form
1422 * @var boolean
1424 var $_disableShortforms = false;
1426 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1427 protected $_use_form_change_checker = true;
1430 * The form name is derived from the class name of the wrapper minus the trailing form
1431 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1432 * @var string
1434 var $_formName = '';
1437 * String with the html for hidden params passed in as part of a moodle_url
1438 * object for the action. Output in the form.
1439 * @var string
1441 var $_pageparams = '';
1444 * Whether the form contains any client-side validation or not.
1445 * @var bool
1447 protected $clientvalidation = false;
1450 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1452 * @staticvar int $formcounter counts number of forms
1453 * @param string $formName Form's name.
1454 * @param string $method Form's method defaults to 'POST'
1455 * @param string|moodle_url $action Form's action
1456 * @param string $target (optional)Form's target defaults to none
1457 * @param mixed $attributes (optional)Extra attributes for <form> tag
1459 public function __construct($formName, $method, $action, $target='', $attributes=null) {
1460 global $CFG, $OUTPUT;
1462 static $formcounter = 1;
1464 // TODO MDL-52313 Replace with the call to parent::__construct().
1465 HTML_Common::__construct($attributes);
1466 $target = empty($target) ? array() : array('target' => $target);
1467 $this->_formName = $formName;
1468 if (is_a($action, 'moodle_url')){
1469 $this->_pageparams = html_writer::input_hidden_params($action);
1470 $action = $action->out_omit_querystring();
1471 } else {
1472 $this->_pageparams = '';
1474 // No 'name' atttribute for form in xhtml strict :
1475 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1476 if (is_null($this->getAttribute('id'))) {
1477 $attributes['id'] = 'mform' . $formcounter;
1479 $formcounter++;
1480 $this->updateAttributes($attributes);
1482 // This is custom stuff for Moodle :
1483 $oldclass= $this->getAttribute('class');
1484 if (!empty($oldclass)){
1485 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1486 }else {
1487 $this->updateAttributes(array('class'=>'mform'));
1489 $this->_reqHTML = '<span class="req">' . $OUTPUT->pix_icon('req', get_string('requiredelement', 'form')) . '</span>';
1490 $this->_advancedHTML = '<span class="adv">' . $OUTPUT->pix_icon('adv', get_string('advancedelement', 'form')) . '</span>';
1491 $this->setRequiredNote(get_string('somefieldsrequired', 'form', $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'))));
1495 * Old syntax of class constructor. Deprecated in PHP7.
1497 * @deprecated since Moodle 3.1
1499 public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1500 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1501 self::__construct($formName, $method, $action, $target, $attributes);
1505 * Use this method to indicate an element in a form is an advanced field. If items in a form
1506 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1507 * form so the user can decide whether to display advanced form controls.
1509 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1511 * @param string $elementName group or element name (not the element name of something inside a group).
1512 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1514 function setAdvanced($elementName, $advanced = true) {
1515 if ($advanced){
1516 $this->_advancedElements[$elementName]='';
1517 } elseif (isset($this->_advancedElements[$elementName])) {
1518 unset($this->_advancedElements[$elementName]);
1523 * Use this method to indicate that the fieldset should be shown as expanded.
1524 * The method is applicable to header elements only.
1526 * @param string $headername header element name
1527 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1528 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1529 * the form was submitted.
1530 * @return void
1532 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1533 if (empty($headername)) {
1534 return;
1536 $element = $this->getElement($headername);
1537 if ($element->getType() != 'header') {
1538 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1539 return;
1541 if (!$headerid = $element->getAttribute('id')) {
1542 $element->_generateId();
1543 $headerid = $element->getAttribute('id');
1545 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1546 // See if the form has been submitted already.
1547 $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1548 if (!$ignoreuserstate && $formexpanded != -1) {
1549 // Override expanded state with the form variable.
1550 $expanded = $formexpanded;
1552 // Create the form element for storing expanded state.
1553 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1554 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1555 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1557 $this->_collapsibleElements[$headername] = !$expanded;
1561 * Use this method to add show more/less status element required for passing
1562 * over the advanced elements visibility status on the form submission.
1564 * @param string $headerName header element name.
1565 * @param boolean $showmore default false sets the advanced elements to be hidden.
1567 function addAdvancedStatusElement($headerid, $showmore=false){
1568 // Add extra hidden element to store advanced items state for each section.
1569 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1570 // See if we the form has been submitted already.
1571 $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1572 if (!$showmore && $formshowmore != -1) {
1573 // Override showmore state with the form variable.
1574 $showmore = $formshowmore;
1576 // Create the form element for storing advanced items state.
1577 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1578 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1579 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1584 * This function has been deprecated. Show advanced has been replaced by
1585 * "Show more.../Show less..." in the shortforms javascript module.
1587 * @deprecated since Moodle 2.5
1588 * @param bool $showadvancedNow if true will show advanced elements.
1590 function setShowAdvanced($showadvancedNow = null){
1591 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1595 * This function has been deprecated. Show advanced has been replaced by
1596 * "Show more.../Show less..." in the shortforms javascript module.
1598 * @deprecated since Moodle 2.5
1599 * @return bool (Always false)
1601 function getShowAdvanced(){
1602 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1603 return false;
1607 * Use this method to indicate that the form will not be using shortforms.
1609 * @param boolean $disable default true, controls if the shortforms are disabled.
1611 function setDisableShortforms ($disable = true) {
1612 $this->_disableShortforms = $disable;
1616 * Call this method if you don't want the formchangechecker JavaScript to be
1617 * automatically initialised for this form.
1619 public function disable_form_change_checker() {
1620 $this->_use_form_change_checker = false;
1624 * If you have called {@link disable_form_change_checker()} then you can use
1625 * this method to re-enable it. It is enabled by default, so normally you don't
1626 * need to call this.
1628 public function enable_form_change_checker() {
1629 $this->_use_form_change_checker = true;
1633 * @return bool whether this form should automatically initialise
1634 * formchangechecker for itself.
1636 public function is_form_change_checker_enabled() {
1637 return $this->_use_form_change_checker;
1641 * Accepts a renderer
1643 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1645 function accept(&$renderer) {
1646 if (method_exists($renderer, 'setAdvancedElements')){
1647 //Check for visible fieldsets where all elements are advanced
1648 //and mark these headers as advanced as well.
1649 //Also mark all elements in a advanced header as advanced.
1650 $stopFields = $renderer->getStopFieldSetElements();
1651 $lastHeader = null;
1652 $lastHeaderAdvanced = false;
1653 $anyAdvanced = false;
1654 $anyError = false;
1655 foreach (array_keys($this->_elements) as $elementIndex){
1656 $element =& $this->_elements[$elementIndex];
1658 // if closing header and any contained element was advanced then mark it as advanced
1659 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1660 if ($anyAdvanced && !is_null($lastHeader)) {
1661 $lastHeader->_generateId();
1662 $this->setAdvanced($lastHeader->getName());
1663 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1665 $lastHeaderAdvanced = false;
1666 unset($lastHeader);
1667 $lastHeader = null;
1668 } elseif ($lastHeaderAdvanced) {
1669 $this->setAdvanced($element->getName());
1672 if ($element->getType()=='header'){
1673 $lastHeader =& $element;
1674 $anyAdvanced = false;
1675 $anyError = false;
1676 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1677 } elseif (isset($this->_advancedElements[$element->getName()])){
1678 $anyAdvanced = true;
1679 if (isset($this->_errors[$element->getName()])) {
1680 $anyError = true;
1684 // the last header may not be closed yet...
1685 if ($anyAdvanced && !is_null($lastHeader)){
1686 $this->setAdvanced($lastHeader->getName());
1687 $lastHeader->_generateId();
1688 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1690 $renderer->setAdvancedElements($this->_advancedElements);
1692 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1694 // Count the number of sections.
1695 $headerscount = 0;
1696 foreach (array_keys($this->_elements) as $elementIndex){
1697 $element =& $this->_elements[$elementIndex];
1698 if ($element->getType() == 'header') {
1699 $headerscount++;
1703 $anyrequiredorerror = false;
1704 $headercounter = 0;
1705 $headername = null;
1706 foreach (array_keys($this->_elements) as $elementIndex){
1707 $element =& $this->_elements[$elementIndex];
1709 if ($element->getType() == 'header') {
1710 $headercounter++;
1711 $element->_generateId();
1712 $headername = $element->getName();
1713 $anyrequiredorerror = false;
1714 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1715 $anyrequiredorerror = true;
1716 } else {
1717 // Do not reset $anyrequiredorerror to false because we do not want any other element
1718 // in this header (fieldset) to possibly revert the state given.
1721 if ($element->getType() == 'header') {
1722 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1723 // By default the first section is always expanded, except if a state has already been set.
1724 $this->setExpanded($headername, true);
1725 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1726 // The second section is always expanded if the form only contains 2 sections),
1727 // except if a state has already been set.
1728 $this->setExpanded($headername, true);
1730 } else if ($anyrequiredorerror) {
1731 // If any error or required field are present within the header, we need to expand it.
1732 $this->setExpanded($headername, true, true);
1733 } else if (!isset($this->_collapsibleElements[$headername])) {
1734 // Define element as collapsed by default.
1735 $this->setExpanded($headername, false);
1739 // Pass the array to renderer object.
1740 $renderer->setCollapsibleElements($this->_collapsibleElements);
1742 parent::accept($renderer);
1746 * Adds one or more element names that indicate the end of a fieldset
1748 * @param string $elementName name of the element
1750 function closeHeaderBefore($elementName){
1751 $renderer =& $this->defaultRenderer();
1752 $renderer->addStopFieldsetElements($elementName);
1756 * Set an element to be forced to flow LTR.
1758 * The element must exist and support this functionality. Also note that
1759 * when setting the type of a field (@link self::setType} we try to guess the
1760 * whether the field should be force to LTR or not. Make sure you're always
1761 * calling this method last.
1763 * @param string $elementname The element name.
1764 * @param bool $value When false, disables force LTR, else enables it.
1766 public function setForceLtr($elementname, $value = true) {
1767 $this->getElement($elementname)->set_force_ltr($value);
1771 * Should be used for all elements of a form except for select, radio and checkboxes which
1772 * clean their own data.
1774 * @param string $elementname
1775 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1776 * {@link lib/moodlelib.php} for defined parameter types
1778 function setType($elementname, $paramtype) {
1779 $this->_types[$elementname] = $paramtype;
1781 // This will not always get it right, but it should be accurate in most cases.
1782 // When inaccurate use setForceLtr().
1783 if (!is_rtl_compatible($paramtype)
1784 && $this->elementExists($elementname)
1785 && ($element =& $this->getElement($elementname))
1786 && method_exists($element, 'set_force_ltr')) {
1788 $element->set_force_ltr(true);
1793 * This can be used to set several types at once.
1795 * @param array $paramtypes types of parameters.
1796 * @see MoodleQuickForm::setType
1798 function setTypes($paramtypes) {
1799 foreach ($paramtypes as $elementname => $paramtype) {
1800 $this->setType($elementname, $paramtype);
1805 * Return the type(s) to use to clean an element.
1807 * In the case where the element has an array as a value, we will try to obtain a
1808 * type defined for that specific key, and recursively until done.
1810 * This method does not work reverse, you cannot pass a nested element and hoping to
1811 * fallback on the clean type of a parent. This method intends to be used with the
1812 * main element, which will generate child types if needed, not the other way around.
1814 * Example scenario:
1816 * You have defined a new repeated element containing a text field called 'foo'.
1817 * By default there will always be 2 occurence of 'foo' in the form. Even though
1818 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1819 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1820 * $mform->setType('foo[0]', PARAM_FLOAT).
1822 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1823 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1824 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1825 * get the default clean type returned (param $default).
1827 * @param string $elementname name of the element.
1828 * @param mixed $value value that should be cleaned.
1829 * @param int $default default constant value to be returned (PARAM_...)
1830 * @return string|array constant value or array of constant values (PARAM_...)
1832 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1833 $type = $default;
1834 if (array_key_exists($elementname, $this->_types)) {
1835 $type = $this->_types[$elementname];
1837 if (is_array($value)) {
1838 $default = $type;
1839 $type = array();
1840 foreach ($value as $subkey => $subvalue) {
1841 $typekey = "$elementname" . "[$subkey]";
1842 if (array_key_exists($typekey, $this->_types)) {
1843 $subtype = $this->_types[$typekey];
1844 } else {
1845 $subtype = $default;
1847 if (is_array($subvalue)) {
1848 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1849 } else {
1850 $type[$subkey] = $subtype;
1854 return $type;
1858 * Return the cleaned value using the passed type(s).
1860 * @param mixed $value value that has to be cleaned.
1861 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1862 * @return mixed cleaned up value.
1864 public function getCleanedValue($value, $type) {
1865 if (is_array($type) && is_array($value)) {
1866 foreach ($type as $key => $param) {
1867 $value[$key] = $this->getCleanedValue($value[$key], $param);
1869 } else if (!is_array($type) && !is_array($value)) {
1870 $value = clean_param($value, $type);
1871 } else if (!is_array($type) && is_array($value)) {
1872 $value = clean_param_array($value, $type, true);
1873 } else {
1874 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1876 return $value;
1880 * Updates submitted values
1882 * @param array $submission submitted values
1883 * @param array $files list of files
1885 function updateSubmission($submission, $files) {
1886 $this->_flagSubmitted = false;
1888 if (empty($submission)) {
1889 $this->_submitValues = array();
1890 } else {
1891 foreach ($submission as $key => $s) {
1892 $type = $this->getCleanType($key, $s);
1893 $submission[$key] = $this->getCleanedValue($s, $type);
1895 $this->_submitValues = $submission;
1896 $this->_flagSubmitted = true;
1899 if (empty($files)) {
1900 $this->_submitFiles = array();
1901 } else {
1902 $this->_submitFiles = $files;
1903 $this->_flagSubmitted = true;
1906 // need to tell all elements that they need to update their value attribute.
1907 foreach (array_keys($this->_elements) as $key) {
1908 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1913 * Returns HTML for required elements
1915 * @return string
1917 function getReqHTML(){
1918 return $this->_reqHTML;
1922 * Returns HTML for advanced elements
1924 * @return string
1926 function getAdvancedHTML(){
1927 return $this->_advancedHTML;
1931 * Initializes a default form value. Used to specify the default for a new entry where
1932 * no data is loaded in using moodleform::set_data()
1934 * note: $slashed param removed
1936 * @param string $elementName element name
1937 * @param mixed $defaultValue values for that element name
1939 function setDefault($elementName, $defaultValue){
1940 $this->setDefaults(array($elementName=>$defaultValue));
1944 * Add a help button to element, only one button per element is allowed.
1946 * This is new, simplified and preferable method of setting a help icon on form elements.
1947 * It uses the new $OUTPUT->help_icon().
1949 * Typically, you will provide the same identifier and the component as you have used for the
1950 * label of the element. The string identifier with the _help suffix added is then used
1951 * as the help string.
1953 * There has to be two strings defined:
1954 * 1/ get_string($identifier, $component) - the title of the help page
1955 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1957 * @since Moodle 2.0
1958 * @param string $elementname name of the element to add the item to
1959 * @param string $identifier help string identifier without _help suffix
1960 * @param string $component component name to look the help string in
1961 * @param string $linktext optional text to display next to the icon
1962 * @param bool $suppresscheck set to true if the element may not exist
1964 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1965 global $OUTPUT;
1966 if (array_key_exists($elementname, $this->_elementIndex)) {
1967 $element = $this->_elements[$this->_elementIndex[$elementname]];
1968 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1969 } else if (!$suppresscheck) {
1970 debugging(get_string('nonexistentformelements', 'form', $elementname));
1975 * Set constant value not overridden by _POST or _GET
1976 * note: this does not work for complex names with [] :-(
1978 * @param string $elname name of element
1979 * @param mixed $value
1981 function setConstant($elname, $value) {
1982 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1983 $element =& $this->getElement($elname);
1984 $element->onQuickFormEvent('updateValue', null, $this);
1988 * export submitted values
1990 * @param string $elementList list of elements in form
1991 * @return array
1993 function exportValues($elementList = null){
1994 $unfiltered = array();
1995 if (null === $elementList) {
1996 // iterate over all elements, calling their exportValue() methods
1997 foreach (array_keys($this->_elements) as $key) {
1998 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1999 $varname = $this->_elements[$key]->_attributes['name'];
2000 $value = '';
2001 // If we have a default value then export it.
2002 if (isset($this->_defaultValues[$varname])) {
2003 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
2005 } else {
2006 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
2009 if (is_array($value)) {
2010 // This shit throws a bogus warning in PHP 4.3.x
2011 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2014 } else {
2015 if (!is_array($elementList)) {
2016 $elementList = array_map('trim', explode(',', $elementList));
2018 foreach ($elementList as $elementName) {
2019 $value = $this->exportValue($elementName);
2020 if (@PEAR::isError($value)) {
2021 return $value;
2023 //oh, stock QuickFOrm was returning array of arrays!
2024 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2028 if (is_array($this->_constantValues)) {
2029 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
2031 return $unfiltered;
2035 * This is a bit of a hack, and it duplicates the code in
2036 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
2037 * reliably calling that code. (Think about date selectors, for example.)
2038 * @param string $name the element name.
2039 * @param mixed $value the fixed value to set.
2040 * @return mixed the appropriate array to add to the $unfiltered array.
2042 protected function prepare_fixed_value($name, $value) {
2043 if (null === $value) {
2044 return null;
2045 } else {
2046 if (!strpos($name, '[')) {
2047 return array($name => $value);
2048 } else {
2049 $valueAry = array();
2050 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2051 eval("\$valueAry$myIndex = \$value;");
2052 return $valueAry;
2058 * Adds a validation rule for the given field
2060 * If the element is in fact a group, it will be considered as a whole.
2061 * To validate grouped elements as separated entities,
2062 * use addGroupRule instead of addRule.
2064 * @param string $element Form element name
2065 * @param string $message Message to display for invalid data
2066 * @param string $type Rule type, use getRegisteredRules() to get types
2067 * @param string $format (optional)Required for extra rule data
2068 * @param string $validation (optional)Where to perform validation: "server", "client"
2069 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2070 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2072 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2074 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2075 if ($validation == 'client') {
2076 $this->clientvalidation = true;
2082 * Adds a validation rule for the given group of elements
2084 * Only groups with a name can be assigned a validation rule
2085 * Use addGroupRule when you need to validate elements inside the group.
2086 * Use addRule if you need to validate the group as a whole. In this case,
2087 * the same rule will be applied to all elements in the group.
2088 * Use addRule if you need to validate the group against a function.
2090 * @param string $group Form group name
2091 * @param array|string $arg1 Array for multiple elements or error message string for one element
2092 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2093 * @param string $format (optional)Required for extra rule data
2094 * @param int $howmany (optional)How many valid elements should be in the group
2095 * @param string $validation (optional)Where to perform validation: "server", "client"
2096 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2098 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2100 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2101 if (is_array($arg1)) {
2102 foreach ($arg1 as $rules) {
2103 foreach ($rules as $rule) {
2104 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2105 if ($validation == 'client') {
2106 $this->clientvalidation = true;
2110 } elseif (is_string($arg1)) {
2111 if ($validation == 'client') {
2112 $this->clientvalidation = true;
2118 * Returns the client side validation script
2120 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2121 * and slightly modified to run rules per-element
2122 * Needed to override this because of an error with client side validation of grouped elements.
2124 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2126 function getValidationScript()
2128 global $PAGE;
2130 if (empty($this->_rules) || $this->clientvalidation === false) {
2131 return '';
2134 include_once('HTML/QuickForm/RuleRegistry.php');
2135 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2136 $test = array();
2137 $js_escape = array(
2138 "\r" => '\r',
2139 "\n" => '\n',
2140 "\t" => '\t',
2141 "'" => "\\'",
2142 '"' => '\"',
2143 '\\' => '\\\\'
2146 foreach ($this->_rules as $elementName => $rules) {
2147 foreach ($rules as $rule) {
2148 if ('client' == $rule['validation']) {
2149 unset($element); //TODO: find out how to properly initialize it
2151 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2152 $rule['message'] = strtr($rule['message'], $js_escape);
2154 if (isset($rule['group'])) {
2155 $group =& $this->getElement($rule['group']);
2156 // No JavaScript validation for frozen elements
2157 if ($group->isFrozen()) {
2158 continue 2;
2160 $elements =& $group->getElements();
2161 foreach (array_keys($elements) as $key) {
2162 if ($elementName == $group->getElementName($key)) {
2163 $element =& $elements[$key];
2164 break;
2167 } elseif ($dependent) {
2168 $element = array();
2169 $element[] =& $this->getElement($elementName);
2170 foreach ($rule['dependent'] as $elName) {
2171 $element[] =& $this->getElement($elName);
2173 } else {
2174 $element =& $this->getElement($elementName);
2176 // No JavaScript validation for frozen elements
2177 if (is_object($element) && $element->isFrozen()) {
2178 continue 2;
2179 } elseif (is_array($element)) {
2180 foreach (array_keys($element) as $key) {
2181 if ($element[$key]->isFrozen()) {
2182 continue 3;
2186 //for editor element, [text] is appended to the name.
2187 $fullelementname = $elementName;
2188 if (is_object($element) && $element->getType() == 'editor') {
2189 if ($element->getType() == 'editor') {
2190 $fullelementname .= '[text]';
2191 // Add format to rule as moodleform check which format is supported by browser
2192 // it is not set anywhere... So small hack to make sure we pass it down to quickform.
2193 if (is_null($rule['format'])) {
2194 $rule['format'] = $element->getFormat();
2198 // Fix for bug displaying errors for elements in a group
2199 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2200 $test[$fullelementname][1]=$element;
2201 //end of fix
2206 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2207 // the form, and then that form field gets corrupted by the code that follows.
2208 unset($element);
2210 $js = '
2212 require(["core/event", "jquery"], function(Event, $) {
2214 function qf_errorHandler(element, _qfMsg, escapedName) {
2215 var event = $.Event(Event.Events.FORM_FIELD_VALIDATION);
2216 $(element).trigger(event, _qfMsg);
2217 if (event.isDefaultPrevented()) {
2218 return _qfMsg == \'\';
2219 } else {
2220 // Legacy mforms.
2221 var div = element.parentNode;
2223 if ((div == undefined) || (element.name == undefined)) {
2224 // No checking can be done for undefined elements so let server handle it.
2225 return true;
2228 if (_qfMsg != \'\') {
2229 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2230 if (!errorSpan) {
2231 errorSpan = document.createElement("span");
2232 errorSpan.id = \'id_error_\' + escapedName;
2233 errorSpan.className = "error";
2234 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2235 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2236 document.getElementById(errorSpan.id).focus();
2239 while (errorSpan.firstChild) {
2240 errorSpan.removeChild(errorSpan.firstChild);
2243 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2245 if (div.className.substr(div.className.length - 6, 6) != " error"
2246 && div.className != "error") {
2247 div.className += " error";
2248 linebreak = document.createElement("br");
2249 linebreak.className = "error";
2250 linebreak.id = \'id_error_break_\' + escapedName;
2251 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2254 return false;
2255 } else {
2256 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2257 if (errorSpan) {
2258 errorSpan.parentNode.removeChild(errorSpan);
2260 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2261 if (linebreak) {
2262 linebreak.parentNode.removeChild(linebreak);
2265 if (div.className.substr(div.className.length - 6, 6) == " error") {
2266 div.className = div.className.substr(0, div.className.length - 6);
2267 } else if (div.className == "error") {
2268 div.className = "";
2271 return true;
2272 } // End if.
2273 } // End if.
2274 } // End function.
2276 $validateJS = '';
2277 foreach ($test as $elementName => $jsandelement) {
2278 // Fix for bug displaying errors for elements in a group
2279 //unset($element);
2280 list($jsArr,$element)=$jsandelement;
2281 //end of fix
2282 $escapedElementName = preg_replace_callback(
2283 '/[_\[\]-]/',
2284 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2285 $elementName);
2286 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
2288 if (!is_array($element)) {
2289 $element = [$element];
2291 foreach ($element as $elem) {
2292 if (key_exists('id', $elem->_attributes)) {
2293 $js .= '
2294 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2295 if (undefined == element) {
2296 //required element was not found, then let form be submitted without client side validation
2297 return true;
2299 var value = \'\';
2300 var errFlag = new Array();
2301 var _qfGroups = {};
2302 var _qfMsg = \'\';
2303 var frm = element.parentNode;
2304 if ((undefined != element.name) && (frm != undefined)) {
2305 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2306 frm = frm.parentNode;
2308 ' . join("\n", $jsArr) . '
2309 return qf_errorHandler(element, _qfMsg, escapedName);
2310 } else {
2311 //element name should be defined else error msg will not be displayed.
2312 return true;
2316 document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'blur\', function(ev) {
2317 ' . $valFunc . '
2319 document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'change\', function(ev) {
2320 ' . $valFunc . '
2325 $validateJS .= '
2326 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2327 if (!ret && !first_focus) {
2328 first_focus = true;
2329 Y.use(\'moodle-core-event\', function() {
2330 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes['id'] . '\',
2331 elementid: \'id_error_' . $escapedElementName . '\'});
2332 document.getElementById(\'id_error_' . $escapedElementName . '\').focus();
2337 // Fix for bug displaying errors for elements in a group
2338 //unset($element);
2339 //$element =& $this->getElement($elementName);
2340 //end of fix
2341 //$onBlur = $element->getAttribute('onBlur');
2342 //$onChange = $element->getAttribute('onChange');
2343 //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2344 //'onChange' => $onChange . $valFunc));
2346 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2347 $js .= '
2349 function validate_' . $this->_formName . '() {
2350 if (skipClientValidation) {
2351 return true;
2353 var ret = true;
2355 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2356 var first_focus = false;
2357 ' . $validateJS . ';
2358 return ret;
2362 document.getElementById(\'' . $this->_attributes['id'] . '\').addEventListener(\'submit\', function(ev) {
2363 try {
2364 var myValidator = validate_' . $this->_formName . ';
2365 } catch(e) {
2366 return true;
2368 if (typeof window.tinyMCE !== \'undefined\') {
2369 window.tinyMCE.triggerSave();
2371 if (!myValidator()) {
2372 ev.preventDefault();
2379 $PAGE->requires->js_amd_inline($js);
2381 // Global variable used to skip the client validation.
2382 return html_writer::tag('script', 'var skipClientValidation = false;');
2383 } // end func getValidationScript
2386 * Sets default error message
2388 function _setDefaultRuleMessages(){
2389 foreach ($this->_rules as $field => $rulesarr){
2390 foreach ($rulesarr as $key => $rule){
2391 if ($rule['message']===null){
2392 $a=new stdClass();
2393 $a->format=$rule['format'];
2394 $str=get_string('err_'.$rule['type'], 'form', $a);
2395 if (strpos($str, '[[')!==0){
2396 $this->_rules[$field][$key]['message']=$str;
2404 * Get list of attributes which have dependencies
2406 * @return array
2408 function getLockOptionObject(){
2409 $result = array();
2410 foreach ($this->_dependencies as $dependentOn => $conditions){
2411 $result[$dependentOn] = array();
2412 foreach ($conditions as $condition=>$values) {
2413 $result[$dependentOn][$condition] = array();
2414 foreach ($values as $value=>$dependents) {
2415 $result[$dependentOn][$condition][$value] = array();
2416 $i = 0;
2417 foreach ($dependents as $dependent) {
2418 $elements = $this->_getElNamesRecursive($dependent);
2419 if (empty($elements)) {
2420 // probably element inside of some group
2421 $elements = array($dependent);
2423 foreach($elements as $element) {
2424 if ($element == $dependentOn) {
2425 continue;
2427 $result[$dependentOn][$condition][$value][] = $element;
2433 return array($this->getAttribute('id'), $result);
2437 * Get names of element or elements in a group.
2439 * @param HTML_QuickForm_group|element $element element group or element object
2440 * @return array
2442 function _getElNamesRecursive($element) {
2443 if (is_string($element)) {
2444 if (!$this->elementExists($element)) {
2445 return array();
2447 $element = $this->getElement($element);
2450 if (is_a($element, 'HTML_QuickForm_group')) {
2451 $elsInGroup = $element->getElements();
2452 $elNames = array();
2453 foreach ($elsInGroup as $elInGroup){
2454 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2455 // Groups nested in groups: append the group name to the element and then change it back.
2456 // We will be appending group name again in MoodleQuickForm_group::export_for_template().
2457 $oldname = $elInGroup->getName();
2458 if ($element->_appendName) {
2459 $elInGroup->setName($element->getName() . '[' . $oldname . ']');
2461 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2462 $elInGroup->setName($oldname);
2463 } else {
2464 $elNames[] = $element->getElementName($elInGroup->getName());
2468 } else if (is_a($element, 'HTML_QuickForm_header')) {
2469 return array();
2471 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2472 return array();
2474 } else if (method_exists($element, 'getPrivateName') &&
2475 !($element instanceof HTML_QuickForm_advcheckbox)) {
2476 // The advcheckbox element implements a method called getPrivateName,
2477 // but in a way that is not compatible with the generic API, so we
2478 // have to explicitly exclude it.
2479 return array($element->getPrivateName());
2481 } else {
2482 $elNames = array($element->getName());
2485 return $elNames;
2489 * Adds a dependency for $elementName which will be disabled if $condition is met.
2490 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2491 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2492 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2493 * of the $dependentOn element is $condition (such as equal) to $value.
2495 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2496 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2497 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2499 * @param string $elementName the name of the element which will be disabled
2500 * @param string $dependentOn the name of the element whose state will be checked for condition
2501 * @param string $condition the condition to check
2502 * @param mixed $value used in conjunction with condition.
2504 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2505 // Multiple selects allow for a multiple selection, we transform the array to string here as
2506 // an array cannot be used as a key in an associative array.
2507 if (is_array($value)) {
2508 $value = implode('|', $value);
2510 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2511 $this->_dependencies[$dependentOn] = array();
2513 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2514 $this->_dependencies[$dependentOn][$condition] = array();
2516 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2517 $this->_dependencies[$dependentOn][$condition][$value] = array();
2519 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2523 * Registers button as no submit button
2525 * @param string $buttonname name of the button
2527 function registerNoSubmitButton($buttonname){
2528 $this->_noSubmitButtons[]=$buttonname;
2532 * Checks if button is a no submit button, i.e it doesn't submit form
2534 * @param string $buttonname name of the button to check
2535 * @return bool
2537 function isNoSubmitButton($buttonname){
2538 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2542 * Registers a button as cancel button
2544 * @param string $addfieldsname name of the button
2546 function _registerCancelButton($addfieldsname){
2547 $this->_cancelButtons[]=$addfieldsname;
2551 * Displays elements without HTML input tags.
2552 * This method is different to freeze() in that it makes sure no hidden
2553 * elements are included in the form.
2554 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2556 * This function also removes all previously defined rules.
2558 * @param string|array $elementList array or string of element(s) to be frozen
2559 * @return object|bool if element list is not empty then return error object, else true
2561 function hardFreeze($elementList=null)
2563 if (!isset($elementList)) {
2564 $this->_freezeAll = true;
2565 $elementList = array();
2566 } else {
2567 if (!is_array($elementList)) {
2568 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2570 $elementList = array_flip($elementList);
2573 foreach (array_keys($this->_elements) as $key) {
2574 $name = $this->_elements[$key]->getName();
2575 if ($this->_freezeAll || isset($elementList[$name])) {
2576 $this->_elements[$key]->freeze();
2577 $this->_elements[$key]->setPersistantFreeze(false);
2578 unset($elementList[$name]);
2580 // remove all rules
2581 $this->_rules[$name] = array();
2582 // if field is required, remove the rule
2583 $unset = array_search($name, $this->_required);
2584 if ($unset !== false) {
2585 unset($this->_required[$unset]);
2590 if (!empty($elementList)) {
2591 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);
2593 return true;
2597 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2599 * This function also removes all previously defined rules of elements it freezes.
2601 * @throws HTML_QuickForm_Error
2602 * @param array $elementList array or string of element(s) not to be frozen
2603 * @return bool returns true
2605 function hardFreezeAllVisibleExcept($elementList)
2607 $elementList = array_flip($elementList);
2608 foreach (array_keys($this->_elements) as $key) {
2609 $name = $this->_elements[$key]->getName();
2610 $type = $this->_elements[$key]->getType();
2612 if ($type == 'hidden'){
2613 // leave hidden types as they are
2614 } elseif (!isset($elementList[$name])) {
2615 $this->_elements[$key]->freeze();
2616 $this->_elements[$key]->setPersistantFreeze(false);
2618 // remove all rules
2619 $this->_rules[$name] = array();
2620 // if field is required, remove the rule
2621 $unset = array_search($name, $this->_required);
2622 if ($unset !== false) {
2623 unset($this->_required[$unset]);
2627 return true;
2631 * Tells whether the form was already submitted
2633 * This is useful since the _submitFiles and _submitValues arrays
2634 * may be completely empty after the trackSubmit value is removed.
2636 * @return bool
2638 function isSubmitted()
2640 return parent::isSubmitted() && (!$this->isFrozen());
2645 * MoodleQuickForm renderer
2647 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2648 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2650 * Stylesheet is part of standard theme and should be automatically included.
2652 * @package core_form
2653 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2654 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2656 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2658 /** @var array Element template array */
2659 var $_elementTemplates;
2662 * Template used when opening a hidden fieldset
2663 * (i.e. a fieldset that is opened when there is no header element)
2664 * @var string
2666 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2668 /** @var string Header Template string */
2669 var $_headerTemplate =
2670 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2672 /** @var string Template used when opening a fieldset */
2673 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2675 /** @var string Template used when closing a fieldset */
2676 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2678 /** @var string Required Note template string */
2679 var $_requiredNoteTemplate =
2680 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2683 * Collapsible buttons string template.
2685 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2686 * until the Javascript has been fully loaded.
2688 * @var string
2690 var $_collapseButtonsTemplate =
2691 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2694 * Array whose keys are element names. If the key exists this is a advanced element
2696 * @var array
2698 var $_advancedElements = array();
2701 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2703 * @var array
2705 var $_collapsibleElements = array();
2708 * @var string Contains the collapsible buttons to add to the form.
2710 var $_collapseButtons = '';
2713 * Constructor
2715 public function __construct() {
2716 // switch next two lines for ol li containers for form items.
2717 // $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>');
2718 $this->_elementTemplates = array(
2719 '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>',
2721 'actionbuttons' => "\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{typeclass} {class}"><div class="felement {typeclass}" data-fieldtype="{type}">{element}</div></div>',
2723 '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>',
2725 '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>',
2727 'warning' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}">{element}</div>',
2729 'nodisplay' => '');
2731 parent::__construct();
2735 * Old syntax of class constructor. Deprecated in PHP7.
2737 * @deprecated since Moodle 3.1
2739 public function MoodleQuickForm_Renderer() {
2740 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2741 self::__construct();
2745 * Set element's as adavance element
2747 * @param array $elements form elements which needs to be grouped as advance elements.
2749 function setAdvancedElements($elements){
2750 $this->_advancedElements = $elements;
2754 * Setting collapsible elements
2756 * @param array $elements
2758 function setCollapsibleElements($elements) {
2759 $this->_collapsibleElements = $elements;
2763 * What to do when starting the form
2765 * @param MoodleQuickForm $form reference of the form
2767 function startForm(&$form){
2768 global $PAGE;
2769 $this->_reqHTML = $form->getReqHTML();
2770 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2771 $this->_advancedHTML = $form->getAdvancedHTML();
2772 $this->_collapseButtons = '';
2773 $formid = $form->getAttribute('id');
2774 parent::startForm($form);
2775 if ($form->isFrozen()){
2776 $this->_formTemplate = "\n<div id=\"$formid\" class=\"mform frozen\">\n{collapsebtns}\n{content}\n</div>";
2777 } else {
2778 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2779 $this->_hiddenHtml .= $form->_pageparams;
2782 if ($form->is_form_change_checker_enabled()) {
2783 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2784 'M.core_formchangechecker.init',
2785 array(array(
2786 'formid' => $formid
2789 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2791 if (!empty($this->_collapsibleElements)) {
2792 if (count($this->_collapsibleElements) > 1) {
2793 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2794 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2795 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2797 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2799 if (!empty($this->_advancedElements)){
2800 $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2801 $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2806 * Create advance group of elements
2808 * @param MoodleQuickForm_group $group Passed by reference
2809 * @param bool $required if input is required field
2810 * @param string $error error message to display
2812 function startGroup(&$group, $required, $error){
2813 global $OUTPUT;
2815 // Make sure the element has an id.
2816 $group->_generateId();
2818 // Prepend 'fgroup_' to the ID we generated.
2819 $groupid = 'fgroup_' . $group->getAttribute('id');
2821 // Update the ID.
2822 $group->updateAttributes(array('id' => $groupid));
2823 $advanced = isset($this->_advancedElements[$group->getName()]);
2825 $html = $OUTPUT->mform_element($group, $required, $advanced, $error, false);
2826 $fromtemplate = !empty($html);
2827 if (!$fromtemplate) {
2828 if (method_exists($group, 'getElementTemplateType')) {
2829 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2830 } else {
2831 $html = $this->_elementTemplates['default'];
2834 if (isset($this->_advancedElements[$group->getName()])) {
2835 $html = str_replace(' {advanced}', ' advanced', $html);
2836 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
2837 } else {
2838 $html = str_replace(' {advanced}', '', $html);
2839 $html = str_replace('{advancedimg}', '', $html);
2841 if (method_exists($group, 'getHelpButton')) {
2842 $html = str_replace('{help}', $group->getHelpButton(), $html);
2843 } else {
2844 $html = str_replace('{help}', '', $html);
2846 $html = str_replace('{id}', $group->getAttribute('id'), $html);
2847 $html = str_replace('{name}', $group->getName(), $html);
2848 $html = str_replace('{typeclass}', 'fgroup', $html);
2849 $html = str_replace('{type}', 'group', $html);
2850 $html = str_replace('{class}', $group->getAttribute('class'), $html);
2851 $emptylabel = '';
2852 if ($group->getLabel() == '') {
2853 $emptylabel = 'femptylabel';
2855 $html = str_replace('{emptylabel}', $emptylabel, $html);
2857 $this->_templates[$group->getName()] = $html;
2858 // Fix for bug in tableless quickforms that didn't allow you to stop a
2859 // fieldset before a group of elements.
2860 // if the element name indicates the end of a fieldset, close the fieldset
2861 if (in_array($group->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
2862 $this->_html .= $this->_closeFieldsetTemplate;
2863 $this->_fieldsetsOpen--;
2865 if (!$fromtemplate) {
2866 parent::startGroup($group, $required, $error);
2867 } else {
2868 $this->_html .= $html;
2873 * Renders element
2875 * @param HTML_QuickForm_element $element element
2876 * @param bool $required if input is required field
2877 * @param string $error error message to display
2879 function renderElement(&$element, $required, $error){
2880 global $OUTPUT;
2882 // Make sure the element has an id.
2883 $element->_generateId();
2884 $advanced = isset($this->_advancedElements[$element->getName()]);
2886 $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
2887 $fromtemplate = !empty($html);
2888 if (!$fromtemplate) {
2889 // Adding stuff to place holders in template
2890 // check if this is a group element first.
2891 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2892 // So it gets substitutions for *each* element.
2893 $html = $this->_groupElementTemplate;
2894 } else if (method_exists($element, 'getElementTemplateType')) {
2895 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2896 } else {
2897 $html = $this->_elementTemplates['default'];
2899 if (isset($this->_advancedElements[$element->getName()])) {
2900 $html = str_replace(' {advanced}', ' advanced', $html);
2901 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2902 } else {
2903 $html = str_replace(' {advanced}', '', $html);
2904 $html = str_replace(' {aria-live}', '', $html);
2906 if (isset($this->_advancedElements[$element->getName()]) || $element->getName() == 'mform_showadvanced') {
2907 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
2908 } else {
2909 $html = str_replace('{advancedimg}', '', $html);
2911 $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2912 $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
2913 $html = str_replace('{type}', $element->getType(), $html);
2914 $html = str_replace('{name}', $element->getName(), $html);
2915 $html = str_replace('{class}', $element->getAttribute('class'), $html);
2916 $emptylabel = '';
2917 if ($element->getLabel() == '') {
2918 $emptylabel = 'femptylabel';
2920 $html = str_replace('{emptylabel}', $emptylabel, $html);
2921 if (method_exists($element, 'getHelpButton')) {
2922 $html = str_replace('{help}', $element->getHelpButton(), $html);
2923 } else {
2924 $html = str_replace('{help}', '', $html);
2926 } else {
2927 if ($this->_inGroup) {
2928 $this->_groupElementTemplate = $html;
2931 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2932 $this->_groupElementTemplate = $html;
2933 } else if (!isset($this->_templates[$element->getName()])) {
2934 $this->_templates[$element->getName()] = $html;
2937 if (!$fromtemplate) {
2938 parent::renderElement($element, $required, $error);
2939 } else {
2940 if (in_array($element->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
2941 $this->_html .= $this->_closeFieldsetTemplate;
2942 $this->_fieldsetsOpen--;
2944 $this->_html .= $html;
2949 * Called when visiting a form, after processing all form elements
2950 * Adds required note, form attributes, validation javascript and form content.
2952 * @global moodle_page $PAGE
2953 * @param moodleform $form Passed by reference
2955 function finishForm(&$form){
2956 global $PAGE;
2957 if ($form->isFrozen()){
2958 $this->_hiddenHtml = '';
2960 parent::finishForm($form);
2961 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2962 if (!$form->isFrozen()) {
2963 $args = $form->getLockOptionObject();
2964 if (count($args[1]) > 0) {
2965 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2970 * Called when visiting a header element
2972 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2973 * @global moodle_page $PAGE
2975 function renderHeader(&$header) {
2976 global $PAGE;
2978 $header->_generateId();
2979 $name = $header->getName();
2981 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2982 if (is_null($header->_text)) {
2983 $header_html = '';
2984 } elseif (!empty($name) && isset($this->_templates[$name])) {
2985 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2986 } else {
2987 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2990 if ($this->_fieldsetsOpen > 0) {
2991 $this->_html .= $this->_closeFieldsetTemplate;
2992 $this->_fieldsetsOpen--;
2995 // Define collapsible classes for fieldsets.
2996 $arialive = '';
2997 $fieldsetclasses = array('clearfix');
2998 if (isset($this->_collapsibleElements[$header->getName()])) {
2999 $fieldsetclasses[] = 'collapsible';
3000 if ($this->_collapsibleElements[$header->getName()]) {
3001 $fieldsetclasses[] = 'collapsed';
3005 if (isset($this->_advancedElements[$name])){
3006 $fieldsetclasses[] = 'containsadvancedelements';
3009 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
3010 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
3012 $this->_html .= $openFieldsetTemplate . $header_html;
3013 $this->_fieldsetsOpen++;
3017 * Return Array of element names that indicate the end of a fieldset
3019 * @return array
3021 function getStopFieldsetElements(){
3022 return $this->_stopFieldsetElements;
3027 * Required elements validation
3029 * This class overrides QuickForm validation since it allowed space or empty tag as a value
3031 * @package core_form
3032 * @category form
3033 * @copyright 2006 Jamie Pratt <me@jamiep.org>
3034 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3036 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
3038 * Checks if an element is not empty.
3039 * This is a server-side validation, it works for both text fields and editor fields
3041 * @param string $value Value to check
3042 * @param int|string|array $options Not used yet
3043 * @return bool true if value is not empty
3045 function validate($value, $options = null) {
3046 global $CFG;
3047 if (is_array($value) && array_key_exists('text', $value)) {
3048 $value = $value['text'];
3050 if (is_array($value)) {
3051 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
3052 $value = implode('', $value);
3054 $stripvalues = array(
3055 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
3056 '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
3058 if (!empty($CFG->strictformsrequired)) {
3059 $value = preg_replace($stripvalues, '', (string)$value);
3061 if ((string)$value == '') {
3062 return false;
3064 return true;
3068 * This function returns Javascript code used to build client-side validation.
3069 * It checks if an element is not empty.
3071 * @param int $format format of data which needs to be validated.
3072 * @return array
3074 function getValidationScript($format = null) {
3075 global $CFG;
3076 if (!empty($CFG->strictformsrequired)) {
3077 if (!empty($format) && $format == FORMAT_HTML) {
3078 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
3079 } else {
3080 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
3082 } else {
3083 return array('', "{jsVar} == ''");
3089 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
3090 * @name $_HTML_QuickForm_default_renderer
3092 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
3094 /** Please keep this list in alphabetical order. */
3095 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
3096 MoodleQuickForm::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
3097 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
3098 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3099 MoodleQuickForm::registerElementType('course', "$CFG->libdir/form/course.php", 'MoodleQuickForm_course');
3100 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
3101 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
3102 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
3103 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
3104 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
3105 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
3106 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
3107 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
3108 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
3109 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
3110 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
3111 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
3112 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
3113 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
3114 MoodleQuickForm::registerElementType('defaultcustom', "$CFG->libdir/form/defaultcustom.php", 'MoodleQuickForm_defaultcustom');
3115 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
3116 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
3117 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
3118 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
3119 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
3120 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
3121 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
3122 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
3123 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
3124 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
3125 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
3126 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
3127 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
3128 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
3129 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
3130 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
3131 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
3132 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
3133 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
3135 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");