MDL-62982 core_form: Final deprecation of the htmleditor form element
[moodle.git] / lib / formslib.php
CommitLineData
ba21c9d4 1<?php
117bd748
PS
2// This file is part of Moodle - http://moodle.org/
3//
ba21c9d4 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.
117bd748 13//
ba21c9d4 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/>.
16
da6f8763 17/**
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
da1320da 19 *
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.
24 *
25 * See examples of use of this library in course/edit.php and course/edit_form.php
26 *
27 * A few notes :
78bfb562 28 * form definition is used for both printing of form and processing and should be the same
da1320da 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.
32 *
6c1fd304
RT
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
da6f8763 36 */
37
78bfb562
PS
38defined('MOODLE_INTERNAL') || die();
39
40/** setup.php includes our hacked pear libs first */
da6f8763 41require_once 'HTML/QuickForm.php';
42require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43require_once 'HTML/QuickForm/Renderer/Tableless.php';
7b5702b6 44require_once 'HTML/QuickForm/Rule.php';
da6f8763 45
a83ad946 46require_once $CFG->libdir.'/filelib.php';
49292f8c 47
6c1fd304
RT
48/**
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
50 */
832e13f1 51define('EDITOR_UNLIMITED_FILES', -1);
52
a23f0aaf 53/**
54 * Callback called when PEAR throws an error
55 *
56 * @param PEAR_Error $error
57 */
58function pear_handle_error($error){
59 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
60 echo '<br /> <strong>Backtrace </strong>:';
61 print_object($error->backtrace);
62}
63
96f81ea3 64if ($CFG->debugdeveloper) {
fabbf439
PS
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';
864cc1de 68}
69
ba21c9d4 70/**
6c1fd304 71 * Initalize javascript for date type form element
117bd748 72 *
6c1fd304 73 * @staticvar bool $done make sure it gets initalize once.
e5473854 74 * @global moodle_page $PAGE
ba21c9d4 75 */
8e7cebb0 76function form_init_date_js() {
cf615522 77 global $PAGE;
8e7cebb0 78 static $done = false;
79 if (!$done) {
57876874 80 $done = true;
f6554146 81 $calendar = \core_calendar\type_factory::get_calendar_instance();
57876874
MG
82 if ($calendar->get_name() !== 'gregorian') {
83 // The YUI2 calendar only supports the gregorian calendar type.
84 return;
85 }
e5473854
SH
86 $module = 'moodle-form-dateselector';
87 $function = 'M.form.dateselector.init_date_selectors';
45fb8b59
RT
88 $defaulttimezone = date_default_timezone_get();
89
a0658f00 90 $config = array(array(
f6554146 91 'firstdayofweek' => $calendar->get_starting_weekday(),
45fb8b59
RT
92 'mon' => date_format_string(strtotime("Monday"), '%a', $defaulttimezone),
93 'tue' => date_format_string(strtotime("Tuesday"), '%a', $defaulttimezone),
94 'wed' => date_format_string(strtotime("Wednesday"), '%a', $defaulttimezone),
95 'thu' => date_format_string(strtotime("Thursday"), '%a', $defaulttimezone),
96 'fri' => date_format_string(strtotime("Friday"), '%a', $defaulttimezone),
97 'sat' => date_format_string(strtotime("Saturday"), '%a', $defaulttimezone),
98 'sun' => date_format_string(strtotime("Sunday"), '%a', $defaulttimezone),
99 'january' => date_format_string(strtotime("January 1"), '%B', $defaulttimezone),
100 'february' => date_format_string(strtotime("February 1"), '%B', $defaulttimezone),
101 'march' => date_format_string(strtotime("March 1"), '%B', $defaulttimezone),
102 'april' => date_format_string(strtotime("April 1"), '%B', $defaulttimezone),
103 'may' => date_format_string(strtotime("May 1"), '%B', $defaulttimezone),
104 'june' => date_format_string(strtotime("June 1"), '%B', $defaulttimezone),
105 'july' => date_format_string(strtotime("July 1"), '%B', $defaulttimezone),
106 'august' => date_format_string(strtotime("August 1"), '%B', $defaulttimezone),
107 'september' => date_format_string(strtotime("September 1"), '%B', $defaulttimezone),
108 'october' => date_format_string(strtotime("October 1"), '%B', $defaulttimezone),
109 'november' => date_format_string(strtotime("November 1"), '%B', $defaulttimezone),
110 'december' => date_format_string(strtotime("December 1"), '%B', $defaulttimezone)
a0658f00 111 ));
e5473854 112 $PAGE->requires->yui_module($module, $function, $config);
8e7cebb0 113 }
114}
f07b9627 115
05f5c40c 116/**
6c1fd304
RT
117 * Wrapper that separates quickforms syntax from moodle code
118 *
da1320da 119 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
6073a598 120 * use this class you should write a class definition which extends this class or a more specific
da1320da 121 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
122 *
123 * You will write your own definition() method which performs the form set up.
ba21c9d4 124 *
6c1fd304
RT
125 * @package core_form
126 * @copyright 2006 Jamie Pratt <me@jamiep.org>
ba21c9d4 127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6c1fd304 128 * @todo MDL-19380 rethink the file scanning
05f5c40c 129 */
afd63fe5 130abstract class moodleform {
6c1fd304 131 /** @var string name of the form */
172dd12c 132 protected $_formname; // form name
6c1fd304
RT
133
134 /** @var MoodleQuickForm quickform object definition */
172dd12c 135 protected $_form;
6c1fd304
RT
136
137 /** @var array globals workaround */
172dd12c 138 protected $_customdata;
6c1fd304 139
84a32f15
DW
140 /** @var array submitted form data when using mforms with ajax */
141 protected $_ajaxformdata;
142
6c1fd304 143 /** @var object definition_after_data executed flag */
172dd12c 144 protected $_definition_finalized = false;
ebd3c7ac 145
8b9ca065
DTR
146 /** @var bool|null stores the validation result of this form or null if not yet validated */
147 protected $_validated = null;
148
da1320da 149 /**
150 * The constructor function calls the abstract function definition() and it will then
151 * process and clean and attempt to validate incoming data.
152 *
153 * It will call your custom validate method to validate data and will also check any rules
154 * you have specified in definition using addRule
155 *
156 * The name of the form (id attribute of the form) is automatically generated depending on
157 * the name you gave the class extending moodleform. You should call your class something
158 * like
159 *
4f51f48f 160 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
6c1fd304
RT
161 * current url. If a moodle_url object then outputs params as hidden variables.
162 * @param mixed $customdata if your form defintion method needs access to data such as $course
163 * $cm, etc. to construct the form definition then pass it in this array. You can
164 * use globals for somethings.
da1320da 165 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
166 * be merged and used as incoming data to the form.
167 * @param string $target target frame for form submission. You will rarely use this. Don't use
6c1fd304 168 * it if you don't need to as the target attribute is deprecated in xhtml strict.
da1320da 169 * @param mixed $attributes you can pass a string of html attributes here or an array.
f82c9d8d
MG
170 * Special attribute 'data-random-ids' will randomise generated elements ids. This
171 * is necessary when there are several forms on the same page.
225eb7b2 172 * Special attribute 'data-double-submit-protection' set to 'off' will turn off
173 * double-submit protection JavaScript - this may be necessary if your form sends
174 * downloadable files in response to a submit button, and can't call
175 * \core_form\util::form_download_complete();
ba21c9d4 176 * @param bool $editable
84a32f15 177 * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
da1320da 178 */
6853cd5e
DW
179 public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true,
180 $ajaxformdata=null) {
a38a17a1 181 global $CFG, $FULLME;
13725b37
PS
182 // no standard mform in moodle should allow autocomplete with the exception of user signup
183 if (empty($attributes)) {
184 $attributes = array('autocomplete'=>'off');
185 } else if (is_array($attributes)) {
186 $attributes['autocomplete'] = 'off';
187 } else {
188 if (strpos($attributes, 'autocomplete') === false) {
189 $attributes .= ' autocomplete="off" ';
6e9989db
PS
190 }
191 }
192
84a32f15 193
a23f0aaf 194 if (empty($action)){
a38a17a1
PS
195 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
196 $action = strip_querystring($FULLME);
197 if (!empty($CFG->sslproxy)) {
198 // return only https links when using SSL proxy
199 $action = preg_replace('/^http:/', 'https:', $action, 1);
200 }
201 //TODO: use following instead of FULLME - see MDL-33015
202 //$action = strip_querystring(qualified_me());
a23f0aaf 203 }
3a70ccb8 204 // Assign custom data first, so that get_form_identifier can use it.
7f40a229 205 $this->_customdata = $customdata;
3a70ccb8 206 $this->_formname = $this->get_form_identifier();
84a32f15 207 $this->_ajaxformdata = $ajaxformdata;
3a70ccb8 208
8ff19f8c 209 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes, $ajaxformdata);
4f51f48f 210 if (!$editable){
211 $this->_form->hardFreeze();
212 }
7f40a229 213
214 $this->definition();
215
216 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
d18e0fe6 217 $this->_form->setType('sesskey', PARAM_RAW);
7f40a229 218 $this->_form->setDefault('sesskey', sesskey());
5bc97c98 219 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
d18e0fe6 220 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
5bc97c98 221 $this->_form->setDefault('_qf__'.$this->_formname, 1);
222 $this->_form->_setDefaultRuleMessages();
7f40a229 223
547801a4
FM
224 // Hook to inject logic after the definition was provided.
225 $this->after_definition();
226
7f40a229 227 // we have to know all input types before processing submission ;-)
228 $this->_process_submission($method);
7f40a229 229 }
05f5c40c 230
1a0df553
MG
231 /**
232 * Old syntax of class constructor. Deprecated in PHP7.
233 *
234 * @deprecated since Moodle 3.1
235 */
236 public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
237 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
238 self::__construct($action, $customdata, $method, $target, $attributes, $editable);
239 }
240
3a70ccb8
RT
241 /**
242 * It should returns unique identifier for the form.
243 * Currently it will return class name, but in case two same forms have to be
244 * rendered on same page then override function to get unique form identifier.
245 * e.g This is used on multiple self enrollments page.
246 *
247 * @return string form identifier.
248 */
249 protected function get_form_identifier() {
68ef378b
PH
250 $class = get_class($this);
251
252 return preg_replace('/[^a-z0-9_]/i', '_', $class);
3a70ccb8
RT
253 }
254
2c412890 255 /**
da1320da 256 * To autofocus on first form element or first element with error.
2c412890 257 *
8dec2253 258 * @param string $name if this is set then the focus is forced to a field with this name
6c1fd304
RT
259 * @return string javascript to select form element with first error or
260 * first element if no errors. Use this as a parameter
261 * when calling print_header
2c412890 262 */
46f3921e 263 function focus($name=NULL) {
9403060a 264 $form =& $this->_form;
46f3921e 265 $elkeys = array_keys($form->_elementIndex);
266 $error = false;
9403060a 267 if (isset($form->_errors) && 0 != count($form->_errors)){
268 $errorkeys = array_keys($form->_errors);
269 $elkeys = array_intersect($elkeys, $errorkeys);
46f3921e 270 $error = true;
2c412890 271 }
46f3921e 272
273 if ($error or empty($name)) {
274 $names = array();
275 while (empty($names) and !empty($elkeys)) {
276 $el = array_shift($elkeys);
277 $names = $form->_getElNamesRecursive($el);
278 }
279 if (!empty($names)) {
280 $name = array_shift($names);
281 }
8dec2253 282 }
46f3921e 283
284 $focus = '';
285 if (!empty($name)) {
286 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
9403060a 287 }
46f3921e 288
9403060a 289 return $focus;
290 }
7f40a229 291
05f5c40c 292 /**
293 * Internal method. Alters submitted data to be suitable for quickforms processing.
294 * Must be called when the form is fully set up.
ba21c9d4 295 *
6c1fd304 296 * @param string $method name of the method which alters submitted data
05f5c40c 297 */
7f40a229 298 function _process_submission($method) {
299 $submission = array();
bb690849 300 if (!empty($this->_ajaxformdata)) {
84a32f15
DW
301 $submission = $this->_ajaxformdata;
302 } else if ($method == 'post') {
7f40a229 303 if (!empty($_POST)) {
a3777547 304 $submission = $_POST;
7f40a229 305 }
306 } else {
a3777547
PS
307 $submission = $_GET;
308 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
7f40a229 309 }
310
311 // following trick is needed to enable proper sesskey checks when using GET forms
5bc97c98 312 // the _qf__.$this->_formname serves as a marker that form was actually submitted
313 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
7f40a229 314 if (!confirm_sesskey()) {
c3f9ee10 315 print_error('invalidsesskey');
7f40a229 316 }
05f5c40c 317 $files = $_FILES;
7f40a229 318 } else {
319 $submission = array();
05f5c40c 320 $files = array();
7f40a229 321 }
b45ba7f6 322 $this->detectMissingSetType();
7f40a229 323
05f5c40c 324 $this->_form->updateSubmission($submission, $files);
7f40a229 325 }
326
85b82a9c 327 /**
a3777547
PS
328 * Internal method - should not be used anywhere.
329 * @deprecated since 2.6
330 * @return array $_POST.
85b82a9c
PN
331 */
332 protected function _get_post_params() {
a3777547 333 return $_POST;
85b82a9c
PN
334 }
335
05f5c40c 336 /**
f728d49b
PS
337 * Internal method. Validates all old-style deprecated uploaded files.
338 * The new way is to upload files via repository api.
117bd748 339 *
6c1fd304 340 * @param array $files list of files to be validated
ba21c9d4 341 * @return bool|array Success or an array of errors
05f5c40c 342 */
89489cfe 343 function _validate_files(&$files) {
172dd12c 344 global $CFG, $COURSE;
345
89489cfe 346 $files = array();
347
49292f8c 348 if (empty($_FILES)) {
349 // we do not need to do any checks because no files were submitted
89489cfe 350 // note: server side rules do not work for files - use custom verification in validate() instead
49292f8c 351 return true;
352 }
49292f8c 353
172dd12c 354 $errors = array();
355 $filenames = array();
49292f8c 356
357 // now check that we really want each file
358 foreach ($_FILES as $elname=>$file) {
172dd12c 359 $required = $this->_form->isElementRequired($elname);
89489cfe 360
172dd12c 361 if ($file['error'] == 4 and $file['size'] == 0) {
362 if ($required) {
363 $errors[$elname] = get_string('required');
49292f8c 364 }
172dd12c 365 unset($_FILES[$elname]);
366 continue;
367 }
368
a83ad946 369 if (!empty($file['error'])) {
370 $errors[$elname] = file_get_upload_error($file['error']);
172dd12c 371 unset($_FILES[$elname]);
372 continue;
373 }
374
375 if (!is_uploaded_file($file['tmp_name'])) {
376 // TODO: improve error message
377 $errors[$elname] = get_string('error');
378 unset($_FILES[$elname]);
379 continue;
380 }
381
382 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
383 // hmm, this file was not requested
384 unset($_FILES[$elname]);
385 continue;
386 }
387
114e3209
388 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
389
172dd12c 390 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
391 if ($filename === '') {
392 // TODO: improve error message - wrong chars
393 $errors[$elname] = get_string('error');
394 unset($_FILES[$elname]);
395 continue;
49292f8c 396 }
172dd12c 397 if (in_array($filename, $filenames)) {
398 // TODO: improve error message - duplicate name
399 $errors[$elname] = get_string('error');
400 unset($_FILES[$elname]);
401 continue;
402 }
403 $filenames[] = $filename;
404 $_FILES[$elname]['name'] = $filename;
405
406 $files[$elname] = $_FILES[$elname]['tmp_name'];
49292f8c 407 }
408
409 // return errors if found
172dd12c 410 if (count($errors) == 0){
49292f8c 411 return true;
89489cfe 412
49292f8c 413 } else {
89489cfe 414 $files = array();
49292f8c 415 return $errors;
416 }
417 }
418
c6aa3670
RT
419 /**
420 * Internal method. Validates filepicker and filemanager files if they are
421 * set as required fields. Also, sets the error message if encountered one.
422 *
6c1fd304 423 * @return bool|array with errors
c6aa3670
RT
424 */
425 protected function validate_draft_files() {
426 global $USER;
427 $mform =& $this->_form;
428
429 $errors = array();
430 //Go through all the required elements and make sure you hit filepicker or
431 //filemanager element.
432 foreach ($mform->_rules as $elementname => $rules) {
433 $elementtype = $mform->getElementType($elementname);
434 //If element is of type filepicker then do validation
435 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
436 //Check if rule defined is required rule
437 foreach ($rules as $rule) {
438 if ($rule['type'] == 'required') {
439 $draftid = (int)$mform->getSubmitValue($elementname);
440 $fs = get_file_storage();
b0c6dc1c 441 $context = context_user::instance($USER->id);
c6aa3670
RT
442 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
443 $errors[$elementname] = $rule['message'];
444 }
445 }
446 }
447 }
448 }
a32dabc2
DS
449 // Check all the filemanager elements to make sure they do not have too many
450 // files in them.
451 foreach ($mform->_elements as $element) {
452 if ($element->_type == 'filemanager') {
453 $maxfiles = $element->getMaxfiles();
454 if ($maxfiles > 0) {
455 $draftid = (int)$element->getValue();
456 $fs = get_file_storage();
457 $context = context_user::instance($USER->id);
458 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
459 if (count($files) > $maxfiles) {
460 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
461 }
462 }
463 }
464 }
c6aa3670
RT
465 if (empty($errors)) {
466 return true;
467 } else {
468 return $errors;
469 }
470 }
471
05f5c40c 472 /**
da1320da 473 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
474 * form definition (new entry form); this function is used to load in data where values
475 * already exist and data is being edited (edit entry form).
05f5c40c 476 *
294ce987 477 * note: $slashed param removed
478 *
6c1fd304 479 * @param stdClass|array $default_values object or array of default values
05f5c40c 480 */
294ce987 481 function set_data($default_values) {
7f40a229 482 if (is_object($default_values)) {
483 $default_values = (array)$default_values;
484 }
294ce987 485 $this->_form->setDefaults($default_values);
7f40a229 486 }
487
05f5c40c 488 /**
489 * Check that form was submitted. Does not check validity of submitted data.
490 *
491 * @return bool true if form properly submitted
492 */
7f40a229 493 function is_submitted() {
494 return $this->_form->isSubmitted();
495 }
496
ba21c9d4 497 /**
6c1fd304
RT
498 * Checks if button pressed is not for submitting the form
499 *
500 * @staticvar bool $nosubmit keeps track of no submit button
501 * @return bool
ba21c9d4 502 */
a23f0aaf 503 function no_submit_button_pressed(){
504 static $nosubmit = null; // one check is enough
505 if (!is_null($nosubmit)){
506 return $nosubmit;
507 }
508 $mform =& $this->_form;
509 $nosubmit = false;
f07b9627 510 if (!$this->is_submitted()){
511 return false;
512 }
a23f0aaf 513 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
8ff19f8c 514 if ($this->optional_param($nosubmitbutton, 0, PARAM_RAW)) {
a23f0aaf 515 $nosubmit = true;
516 break;
517 }
518 }
519 return $nosubmit;
520 }
521
8ff19f8c
MG
522 /**
523 * Checks if a parameter was passed in the previous form submission
524 *
525 * @param string $name the name of the page parameter we want
526 * @param mixed $default the default value to return if nothing is found
527 * @param string $type expected type of parameter
528 * @return mixed
529 */
530 public function optional_param($name, $default, $type) {
531 if (isset($this->_ajaxformdata[$name])) {
532 return clean_param($this->_ajaxformdata[$name], $type);
533 } else {
534 return optional_param($name, $default, $type);
535 }
536 }
a23f0aaf 537
05f5c40c 538 /**
539 * Check that form data is valid.
58b7d48f 540 * You should almost always use this, rather than {@link validate_defined_fields}
05f5c40c 541 *
542 * @return bool true if form data valid
543 */
7f40a229 544 function is_validated() {
4f51f48f 545 //finalize the form definition before any processing
546 if (!$this->_definition_finalized) {
547 $this->_definition_finalized = true;
548 $this->definition_after_data();
549 }
550
6bba6dbb 551 return $this->validate_defined_fields();
552 }
553
554 /**
555 * Validate the form.
556 *
58b7d48f
SH
557 * You almost always want to call {@link is_validated} instead of this
558 * because it calls {@link definition_after_data} first, before validating the form,
6bba6dbb 559 * which is what you want in 99% of cases.
560 *
561 * This is provided as a separate function for those special cases where
562 * you want the form validated before definition_after_data is called
563 * for example, to selectively add new elements depending on a no_submit_button press,
564 * but only when the form is valid when the no_submit_button is pressed,
565 *
6c1fd304
RT
566 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
567 * is NOT to validate the form when a no submit button has been pressed.
568 * pass true here to override this behaviour
6bba6dbb 569 *
570 * @return bool true if form data valid
571 */
572 function validate_defined_fields($validateonnosubmit=false) {
6bba6dbb 573 $mform =& $this->_form;
574 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
9aa022fe 575 return false;
8b9ca065 576 } elseif ($this->_validated === null) {
3ba2c187 577 $internal_val = $mform->validate();
89489cfe 578
579 $files = array();
580 $file_val = $this->_validate_files($files);
c6aa3670
RT
581 //check draft files for validation and flag them if required files
582 //are not in draft area.
583 $draftfilevalue = $this->validate_draft_files();
584
585 if ($file_val !== true && $draftfilevalue !== true) {
586 $file_val = array_merge($file_val, $draftfilevalue);
587 } else if ($draftfilevalue !== true) {
588 $file_val = $draftfilevalue;
589 } //default is file_val, so no need to assign.
590
89489cfe 591 if ($file_val !== true) {
592 if (!empty($file_val)) {
593 foreach ($file_val as $element=>$msg) {
594 $mform->setElementError($element, $msg);
595 }
596 }
597 $file_val = false;
598 }
599
6c8e25fa
DM
600 // Give the elements a chance to perform an implicit validation.
601 $element_val = true;
602 foreach ($mform->_elements as $element) {
603 if (method_exists($element, 'validateSubmitValue')) {
604 $value = $mform->getSubmitValue($element->getName());
605 $result = $element->validateSubmitValue($value);
606 if (!empty($result) && is_string($result)) {
607 $element_val = false;
608 $mform->setElementError($element->getName(), $result);
609 }
610 }
611 }
612
613 // Let the form instance validate the submitted values.
4287fc0d 614 $data = $mform->exportValues();
89489cfe 615 $moodle_val = $this->validation($data, $files);
a78890d5 616 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
617 // non-empty array means errors
618 foreach ($moodle_val as $element=>$msg) {
619 $mform->setElementError($element, $msg);
7f40a229 620 }
a78890d5 621 $moodle_val = false;
622
623 } else {
624 // anything else means validation ok
625 $moodle_val = true;
7f40a229 626 }
89489cfe 627
6c8e25fa 628 $this->_validated = ($internal_val and $element_val and $moodle_val and $file_val);
7f40a229 629 }
8b9ca065 630 return $this->_validated;
7f40a229 631 }
632
19110c57 633 /**
634 * Return true if a cancel button has been pressed resulting in the form being submitted.
635 *
6c1fd304 636 * @return bool true if a cancel button has been pressed
19110c57 637 */
638 function is_cancelled(){
639 $mform =& $this->_form;
a23f0aaf 640 if ($mform->isSubmitted()){
641 foreach ($mform->_cancelButtons as $cancelbutton){
8ff19f8c 642 if ($this->optional_param($cancelbutton, 0, PARAM_RAW)) {
a23f0aaf 643 return true;
644 }
19110c57 645 }
646 }
647 return false;
648 }
649
05f5c40c 650 /**
da1320da 651 * Return submitted data if properly submitted or returns NULL if validation fails or
652 * if there is no submitted data.
172dd12c 653 *
294ce987 654 * note: $slashed param removed
05f5c40c 655 *
d2b322ae 656 * @return object submitted data; NULL if not valid or not submitted or cancelled
05f5c40c 657 */
294ce987 658 function get_data() {
19110c57 659 $mform =& $this->_form;
3ba2c187 660
d2b322ae 661 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
294ce987 662 $data = $mform->exportValues();
5bc97c98 663 unset($data['sesskey']); // we do not need to return sesskey
664 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
7f40a229 665 if (empty($data)) {
666 return NULL;
667 } else {
668 return (object)$data;
669 }
670 } else {
671 return NULL;
672 }
673 }
674
4f51f48f 675 /**
676 * Return submitted data without validation or NULL if there is no submitted data.
294ce987 677 * note: $slashed param removed
4f51f48f 678 *
4f51f48f 679 * @return object submitted data; NULL if not submitted
680 */
294ce987 681 function get_submitted_data() {
4f51f48f 682 $mform =& $this->_form;
683
684 if ($this->is_submitted()) {
294ce987 685 $data = $mform->exportValues();
4f51f48f 686 unset($data['sesskey']); // we do not need to return sesskey
687 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
688 if (empty($data)) {
689 return NULL;
690 } else {
691 return (object)$data;
692 }
693 } else {
694 return NULL;
695 }
696 }
697
05f5c40c 698 /**
699 * Save verified uploaded files into directory. Upload process can be customised from definition()
ba21c9d4 700 *
6c1fd304
RT
701 * @deprecated since Moodle 2.0
702 * @todo MDL-31294 remove this api
703 * @see moodleform::save_stored_file()
704 * @see moodleform::save_file()
705 * @param string $destination path where file should be stored
ba21c9d4 706 * @return bool Always false
05f5c40c 707 */
49292f8c 708 function save_files($destination) {
172dd12c 709 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
49292f8c 710 return false;
711 }
2b63df96 712
feaf5d06 713 /**
172dd12c 714 * Returns name of uploaded file.
ba21c9d4 715 *
6c1fd304
RT
716 * @param string $elname first element if null
717 * @return string|bool false in case of failure, string if ok
feaf5d06 718 */
172dd12c 719 function get_new_filename($elname=null) {
4287fc0d 720 global $USER;
721
172dd12c 722 if (!$this->is_submitted() or !$this->is_validated()) {
723 return false;
724 }
725
726 if (is_null($elname)) {
727 if (empty($_FILES)) {
728 return false;
729 }
730 reset($_FILES);
731 $elname = key($_FILES);
732 }
4287fc0d 733
734 if (empty($elname)) {
735 return false;
736 }
737
738 $element = $this->_form->getElement($elname);
739
0022e2d7 740 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
4287fc0d 741 $values = $this->_form->exportValues($elname);
742 if (empty($values[$elname])) {
743 return false;
744 }
745 $draftid = $values[$elname];
746 $fs = get_file_storage();
b0c6dc1c 747 $context = context_user::instance($USER->id);
64f93798 748 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
4287fc0d 749 return false;
750 }
751 $file = reset($files);
752 return $file->get_filename();
753 }
754
172dd12c 755 if (!isset($_FILES[$elname])) {
756 return false;
757 }
758
759 return $_FILES[$elname]['name'];
feaf5d06 760 }
761
b6b1d1ca 762 /**
172dd12c 763 * Save file to standard filesystem
ba21c9d4 764 *
172dd12c 765 * @param string $elname name of element
766 * @param string $pathname full path name of file
767 * @param bool $override override file if exists
768 * @return bool success
b6b1d1ca 769 */
172dd12c 770 function save_file($elname, $pathname, $override=false) {
4287fc0d 771 global $USER;
b6b1d1ca 772
4287fc0d 773 if (!$this->is_submitted() or !$this->is_validated()) {
b6b1d1ca 774 return false;
775 }
172dd12c 776 if (file_exists($pathname)) {
777 if ($override) {
778 if (!@unlink($pathname)) {
779 return false;
780 }
781 } else {
782 return false;
783 }
784 }
4287fc0d 785
786 $element = $this->_form->getElement($elname);
787
0022e2d7 788 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
4287fc0d 789 $values = $this->_form->exportValues($elname);
790 if (empty($values[$elname])) {
791 return false;
792 }
793 $draftid = $values[$elname];
794 $fs = get_file_storage();
b0c6dc1c 795 $context = context_user::instance($USER->id);
64f93798 796 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
4287fc0d 797 return false;
798 }
799 $file = reset($files);
800
801 return $file->copy_content_to($pathname);
802
803 } else if (isset($_FILES[$elname])) {
804 return copy($_FILES[$elname]['tmp_name'], $pathname);
172dd12c 805 }
806
4287fc0d 807 return false;
172dd12c 808 }
809
edfd6a5e
PS
810 /**
811 * Returns a temporary file, do not forget to delete after not needed any more.
812 *
6c1fd304
RT
813 * @param string $elname name of the elmenet
814 * @return string|bool either string or false
edfd6a5e
PS
815 */
816 function save_temp_file($elname) {
817 if (!$this->get_new_filename($elname)) {
818 return false;
819 }
af9b1444 820 if (!$dir = make_temp_directory('forms')) {
edfd6a5e
PS
821 return false;
822 }
823 if (!$tempfile = tempnam($dir, 'tempup_')) {
824 return false;
825 }
826 if (!$this->save_file($elname, $tempfile, true)) {
827 // something went wrong
828 @unlink($tempfile);
829 return false;
830 }
831
832 return $tempfile;
833 }
834
0022e2d7 835 /**
d3d98a3a
DC
836 * Get draft files of a form element
837 * This is a protected method which will be used only inside moodleforms
838 *
d3d98a3a 839 * @param string $elname name of element
6c1fd304 840 * @return array|bool|null
d3d98a3a
DC
841 */
842 protected function get_draft_files($elname) {
843 global $USER;
844
845 if (!$this->is_submitted()) {
846 return false;
847 }
848
849 $element = $this->_form->getElement($elname);
850
851 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
852 $values = $this->_form->exportValues($elname);
853 if (empty($values[$elname])) {
854 return false;
855 }
856 $draftid = $values[$elname];
857 $fs = get_file_storage();
b0c6dc1c 858 $context = context_user::instance($USER->id);
64f93798 859 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
d3d98a3a
DC
860 return null;
861 }
862 return $files;
863 }
864 return null;
865 }
866
172dd12c 867 /**
868 * Save file to local filesystem pool
ba21c9d4 869 *
172dd12c 870 * @param string $elname name of element
6c1fd304
RT
871 * @param int $newcontextid id of context
872 * @param string $newcomponent name of the component
873 * @param string $newfilearea name of file area
874 * @param int $newitemid item id
875 * @param string $newfilepath path of file where it get stored
876 * @param string $newfilename use specified filename, if not specified name of uploaded file used
877 * @param bool $overwrite overwrite file if exists
878 * @param int $newuserid new userid if required
172dd12c 879 * @return mixed stored_file object or false if error; may throw exception if duplicate found
880 */
64f93798 881 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
49583e9e 882 $newfilename=null, $overwrite=false, $newuserid=null) {
924ddb15 883 global $USER;
884
172dd12c 885 if (!$this->is_submitted() or !$this->is_validated()) {
89489cfe 886 return false;
172dd12c 887 }
89489cfe 888
924ddb15 889 if (empty($newuserid)) {
890 $newuserid = $USER->id;
89489cfe 891 }
b6b1d1ca 892
4287fc0d 893 $element = $this->_form->getElement($elname);
894 $fs = get_file_storage();
172dd12c 895
4287fc0d 896 if ($element instanceof MoodleQuickForm_filepicker) {
897 $values = $this->_form->exportValues($elname);
898 if (empty($values[$elname])) {
899 return false;
900 }
901 $draftid = $values[$elname];
b0c6dc1c 902 $context = context_user::instance($USER->id);
64f93798 903 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
4287fc0d 904 return false;
905 }
906 $file = reset($files);
907 if (is_null($newfilename)) {
908 $newfilename = $file->get_filename();
909 }
172dd12c 910
4287fc0d 911 if ($overwrite) {
64f93798 912 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
4287fc0d 913 if (!$oldfile->delete()) {
914 return false;
915 }
924ddb15 916 }
917 }
918
64f93798 919 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
4287fc0d 920 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
921 return $fs->create_file_from_storedfile($file_record, $file);
924ddb15 922
4287fc0d 923 } else if (isset($_FILES[$elname])) {
924 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
172dd12c 925
4287fc0d 926 if ($overwrite) {
64f93798 927 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
4287fc0d 928 if (!$oldfile->delete()) {
929 return false;
930 }
931 }
924ddb15 932 }
4287fc0d 933
64f93798 934 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
4287fc0d 935 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
936 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
924ddb15 937 }
938
939 return false;
172dd12c 940 }
941
942 /**
943 * Get content of uploaded file.
ba21c9d4 944 *
6c1fd304
RT
945 * @param string $elname name of file upload element
946 * @return string|bool false in case of failure, string if ok
172dd12c 947 */
948 function get_file_content($elname) {
4287fc0d 949 global $USER;
950
172dd12c 951 if (!$this->is_submitted() or !$this->is_validated()) {
952 return false;
953 }
954
4287fc0d 955 $element = $this->_form->getElement($elname);
956
0022e2d7 957 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
4287fc0d 958 $values = $this->_form->exportValues($elname);
959 if (empty($values[$elname])) {
960 return false;
961 }
962 $draftid = $values[$elname];
963 $fs = get_file_storage();
b0c6dc1c 964 $context = context_user::instance($USER->id);
64f93798 965 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
4287fc0d 966 return false;
967 }
968 $file = reset($files);
969
970 return $file->get_content();
971
972 } else if (isset($_FILES[$elname])) {
973 return file_get_contents($_FILES[$elname]['tmp_name']);
b6b1d1ca 974 }
172dd12c 975
4287fc0d 976 return false;
b6b1d1ca 977 }
978
05f5c40c 979 /**
980 * Print html form.
981 */
7f40a229 982 function display() {
4f51f48f 983 //finalize the form definition if not yet done
984 if (!$this->_definition_finalized) {
985 $this->_definition_finalized = true;
986 $this->definition_after_data();
987 }
b45ba7f6 988
7f40a229 989 $this->_form->display();
990 }
991
d953b184 992 /**
993 * Renders the html form (same as display, but returns the result).
994 *
995 * Note that you can only output this rendered result once per page, as
996 * it contains IDs which must be unique.
997 *
998 * @return string HTML code for the form
999 */
1000 public function render() {
1001 ob_start();
1002 $this->display();
1003 $out = ob_get_contents();
1004 ob_end_clean();
1005 return $out;
1006 }
1007
49292f8c 1008 /**
6c1fd304 1009 * Form definition. Abstract method - always override!
49292f8c 1010 */
afd63fe5 1011 protected abstract function definition();
2c412890 1012
547801a4
FM
1013 /**
1014 * After definition hook.
1015 *
1016 * This is useful for intermediate classes to inject logic after the definition was
1017 * provided without requiring developers to call the parent {{@link self::definition()}}
1018 * as it's not obvious by design. The 'intermediate' class is 'MyClass extends
1019 * IntermediateClass extends moodleform'.
1020 *
1021 * Classes overriding this method should always call the parent. We may not add
1022 * anything specifically in this instance of the method, but intermediate classes
1023 * are likely to do so, and so it is a good practice to always call the parent.
1024 *
1025 * @return void
1026 */
1027 protected function after_definition() {
1028 }
1029
c08ac016 1030 /**
05f5c40c 1031 * Dummy stub method - override if you need to setup the form depending on current
beac4717 1032 * values. This method is called after definition(), data submission and set_data().
05f5c40c 1033 * All form setup that is dependent on form values should go in here.
c08ac016 1034 */
1035 function definition_after_data(){
c08ac016 1036 }
7f40a229 1037
05f5c40c 1038 /**
1039 * Dummy stub method - override if you needed to perform some extra validation.
1040 * If there are errors return array of errors ("fieldname"=>"error message"),
1041 * otherwise true if ok.
38f394b2 1042 *
89489cfe 1043 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
1044 *
05f5c40c 1045 * @param array $data array of ("fieldname"=>value) of submitted data
89489cfe 1046 * @param array $files array of uploaded files "element_name"=>tmp_file_path
a78890d5 1047 * @return array of "element_name"=>"error_description" if there are errors,
6c1fd304 1048 * or an empty array if everything is OK (true allowed for backwards compatibility too).
05f5c40c 1049 */
89489cfe 1050 function validation($data, $files) {
13ccb7bd 1051 return array();
7f40a229 1052 }
ebd3c7ac 1053
fa2fa5c6 1054 /**
58b7d48f 1055 * Helper used by {@link repeat_elements()}.
6c1fd304 1056 *
fa2fa5c6
TH
1057 * @param int $i the index of this element.
1058 * @param HTML_QuickForm_element $elementclone
03848c45 1059 * @param array $namecloned array of names
fa2fa5c6
TH
1060 */
1061 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1062 $name = $elementclone->getName();
1063 $namecloned[] = $name;
1064
1065 if (!empty($name)) {
1066 $elementclone->setName($name."[$i]");
1067 }
1068
1069 if (is_a($elementclone, 'HTML_QuickForm_header')) {
1070 $value = $elementclone->_text;
1071 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1072
ebbc5e7b
TH
1073 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1074 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1075
fa2fa5c6
TH
1076 } else {
1077 $value=$elementclone->getLabel();
1078 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1079 }
1080 }
1081
616b549a 1082 /**
1083 * Method to add a repeating group of elements to a form.
1084 *
1085 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
6c1fd304 1086 * @param int $repeats no of times to repeat elements initially
b2f17171
TH
1087 * @param array $options a nested array. The first array key is the element name.
1088 * the second array key is the type of option to set, and depend on that option,
1089 * the value takes different forms.
1090 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1091 * 'type' - PARAM_* type.
1092 * 'helpbutton' - array containing the helpbutton params.
1093 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1094 * 'rule' - array containing the addRule arguments after the element name.
1095 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1096 * 'advanced' - whether this element is hidden by 'Show more ...'.
616b549a 1097 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1098 * @param string $addfieldsname name for button to add more fields
1099 * @param int $addfieldsno how many fields to add at a time
271ffe3f 1100 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
6c1fd304 1101 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
a23f0aaf 1102 * @return int no of repeats of element in this page
616b549a 1103 */
6f3b54c8 1104 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1105 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
271ffe3f 1106 if ($addstring===null){
1107 $addstring = get_string('addfields', 'form', $addfieldsno);
1108 } else {
1109 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1110 }
8ff19f8c
MG
1111 $repeats = $this->optional_param($repeathiddenname, $repeats, PARAM_INT);
1112 $addfields = $this->optional_param($addfieldsname, '', PARAM_TEXT);
5079271b 1113 $oldrepeats = $repeats;
ebd3c7ac 1114 if (!empty($addfields)){
1115 $repeats += $addfieldsno;
1116 }
ebd3c7ac 1117 $mform =& $this->_form;
a23f0aaf 1118 $mform->registerNoSubmitButton($addfieldsname);
ebd3c7ac 1119 $mform->addElement('hidden', $repeathiddenname, $repeats);
d18e0fe6 1120 $mform->setType($repeathiddenname, PARAM_INT);
ebd3c7ac 1121 //value not to be overridden by submitted value
1122 $mform->setConstants(array($repeathiddenname=>$repeats));
414f7bee 1123 $namecloned = array();
1124 for ($i = 0; $i < $repeats; $i++) {
ebd3c7ac 1125 foreach ($elementobjs as $elementobj){
985f0ddd 1126 $elementclone = fullclone($elementobj);
fa2fa5c6 1127 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
ebd3c7ac 1128
fa2fa5c6
TH
1129 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1130 foreach ($elementclone->getElements() as $el) {
1131 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1132 }
1133 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
ebd3c7ac 1134 }
7b41a4a9 1135
5079271b
DS
1136 // Mark newly created elements, so they know not to look for any submitted data.
1137 if ($i >= $oldrepeats) {
1138 $mform->note_new_repeat($elementclone->getName());
1139 }
1140
ebd3c7ac 1141 $mform->addElement($elementclone);
1142 }
1143 }
1144 for ($i=0; $i<$repeats; $i++) {
1145 foreach ($options as $elementname => $elementoptions){
1146 $pos=strpos($elementname, '[');
1147 if ($pos!==FALSE){
86b600d6
RT
1148 $realelementname = substr($elementname, 0, $pos)."[$i]";
1149 $realelementname .= substr($elementname, $pos);
ebd3c7ac 1150 }else {
1151 $realelementname = $elementname."[$i]";
1152 }
1153 foreach ($elementoptions as $option => $params){
1154
1155 switch ($option){
1156 case 'default' :
1851b00b 1157 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
ebd3c7ac 1158 break;
ebd3c7ac 1159 case 'helpbutton' :
cd188086
DM
1160 $params = array_merge(array($realelementname), $params);
1161 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
ebd3c7ac 1162 break;
1163 case 'disabledif' :
414f7bee 1164 foreach ($namecloned as $num => $name){
1165 if ($params[0] == $name){
1166 $params[0] = $params[0]."[$i]";
1167 break;
1168 }
1169 }
9aa022fe 1170 $params = array_merge(array($realelementname), $params);
1171 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1172 break;
efc34ea5
DS
1173 case 'hideif' :
1174 foreach ($namecloned as $num => $name){
1175 if ($params[0] == $name){
1176 $params[0] = $params[0]."[$i]";
1177 break;
1178 }
1179 }
1180 $params = array_merge(array($realelementname), $params);
1181 call_user_func_array(array(&$mform, 'hideIf'), $params);
1182 break;
9aa022fe 1183 case 'rule' :
1184 if (is_string($params)){
1185 $params = array(null, $params, null, 'client');
1186 }
1187 $params = array_merge(array($realelementname), $params);
1188 call_user_func_array(array(&$mform, 'addRule'), $params);
ebd3c7ac 1189 break;
188c04b0
FM
1190
1191 case 'type':
1192 $mform->setType($realelementname, $params);
51070abc 1193 break;
d23edcf1 1194
f160f97c
FM
1195 case 'expanded':
1196 $mform->setExpanded($realelementname, $params);
d23edcf1
TH
1197 break;
1198
1199 case 'advanced' :
1200 $mform->setAdvanced($realelementname, $params);
a4067bfc 1201 break;
ebd3c7ac 1202 }
1203 }
1204 }
1205 }
271ffe3f 1206 $mform->addElement('submit', $addfieldsname, $addstring);
a23f0aaf 1207
6f3b54c8 1208 if (!$addbuttoninside) {
1209 $mform->closeHeaderBefore($addfieldsname);
1210 }
ebd3c7ac 1211
19194f82 1212 return $repeats;
ebd3c7ac 1213 }
6073a598 1214
1215 /**
1216 * Adds a link/button that controls the checked state of a group of checkboxes.
ba21c9d4 1217 *
6c1fd304 1218 * @param int $groupid The id of the group of advcheckboxes this element controls
d8e7d1a0 1219 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
6c1fd304
RT
1220 * @param array $attributes associative array of HTML attributes
1221 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
6073a598 1222 */
d8e7d1a0 1223 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
c14584f2 1224 global $CFG, $PAGE;
d8e7d1a0 1225
7f850b23
RT
1226 // Name of the controller button
1227 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1228 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1229 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1230
d8e7d1a0 1231 // Set the default text if none was specified
6073a598 1232 if (empty($text)) {
1233 $text = get_string('selectallornone', 'form');
1234 }
1235
1236 $mform = $this->_form;
8ff19f8c
MG
1237 $selectvalue = $this->optional_param($checkboxcontrollerparam, null, PARAM_INT);
1238 $contollerbutton = $this->optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
6073a598 1239
4dd2af12
SH
1240 $newselectvalue = $selectvalue;
1241 if (is_null($selectvalue)) {
1242 $newselectvalue = $originalValue;
7f850b23 1243 } else if (!is_null($contollerbutton)) {
4dd2af12 1244 $newselectvalue = (int) !$selectvalue;
6073a598 1245 }
7f850b23 1246 // set checkbox state depending on orignal/submitted value by controoler button
4dd2af12 1247 if (!is_null($contollerbutton) || is_null($selectvalue)) {
7f850b23
RT
1248 foreach ($mform->_elements as $element) {
1249 if (($element instanceof MoodleQuickForm_advcheckbox) &&
91f7f8c1
RT
1250 $element->getAttribute('class') == $checkboxgroupclass &&
1251 !$element->isFrozen()) {
4dd2af12 1252 $mform->setConstants(array($element->getName() => $newselectvalue));
7f850b23
RT
1253 }
1254 }
1255 }
6073a598 1256
4dd2af12 1257 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
7f850b23 1258 $mform->setType($checkboxcontrollerparam, PARAM_INT);
4dd2af12 1259 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
172dd12c 1260
c14584f2
RT
1261 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1262 array(
1263 array('groupid' => $groupid,
7f850b23
RT
1264 'checkboxclass' => $checkboxgroupclass,
1265 'checkboxcontroller' => $checkboxcontrollerparam,
1266 'controllerbutton' => $checkboxcontrollername)
c14584f2
RT
1267 )
1268 );
1269
1270 require_once("$CFG->libdir/form/submit.php");
7f850b23 1271 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
172dd12c 1272 $mform->addElement($submitlink);
7f850b23
RT
1273 $mform->registerNoSubmitButton($checkboxcontrollername);
1274 $mform->setDefault($checkboxcontrollername, $text);
6073a598 1275 }
1276
a23f0aaf 1277 /**
1d284fbd 1278 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
a23f0aaf 1279 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1280 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
beac4717 1281 * get data with get_data().
a23f0aaf 1282 *
6c1fd304 1283 * @param bool $cancel whether to show cancel button, default true
a23f0aaf 1284 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1285 */
1d284fbd 1286 function add_action_buttons($cancel = true, $submitlabel=null){
a23f0aaf 1287 if (is_null($submitlabel)){
1288 $submitlabel = get_string('savechanges');
1289 }
1290 $mform =& $this->_form;
1d284fbd 1291 if ($cancel){
1292 //when two elements we need a group
a23f0aaf 1293 $buttonarray=array();
1294 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1d284fbd 1295 $buttonarray[] = &$mform->createElement('cancel');
a23f0aaf 1296 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
4f51f48f 1297 $mform->closeHeaderBefore('buttonar');
a23f0aaf 1298 } else {
1299 //no group needed
1300 $mform->addElement('submit', 'submitbutton', $submitlabel);
4f51f48f 1301 $mform->closeHeaderBefore('submitbutton');
a23f0aaf 1302 }
1303 }
572dd8ec
SH
1304
1305 /**
2836e77d 1306 * Adds an initialisation call for a standard JavaScript enhancement.
572dd8ec
SH
1307 *
1308 * This function is designed to add an initialisation call for a JavaScript
2836e77d 1309 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
572dd8ec
SH
1310 *
1311 * Current options:
1312 * - Selectboxes
1313 * - smartselect: Turns a nbsp indented select box into a custom drop down
1314 * control that supports multilevel and category selection.
1315 * $enhancement = 'smartselect';
1316 * $options = array('selectablecategories' => true|false)
1317 *
6c1fd304
RT
1318 * @param string|element $element form element for which Javascript needs to be initalized
1319 * @param string $enhancement which init function should be called
1320 * @param array $options options passed to javascript
1321 * @param array $strings strings for javascript
2fa2ed50 1322 * @deprecated since Moodle 3.3 MDL-57471
572dd8ec
SH
1323 */
1324 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
2fa2ed50
DP
1325 debugging('$mform->init_javascript_enhancement() is deprecated and no longer does anything. '.
1326 'smartselect uses should be converted to the searchableselector form element.', DEBUG_DEVELOPER);
572dd8ec 1327 }
c7e3e61c
SH
1328
1329 /**
1330 * Returns a JS module definition for the mforms JS
6c1fd304 1331 *
c7e3e61c
SH
1332 * @return array
1333 */
1334 public static function get_js_module() {
1335 global $CFG;
1336 return array(
1337 'name' => 'mform',
1338 'fullpath' => '/lib/form/form.js',
ac5e6ca4 1339 'requires' => array('base', 'node')
c7e3e61c
SH
1340 );
1341 }
b45ba7f6
DP
1342
1343 /**
1344 * Detects elements with missing setType() declerations.
1345 *
1346 * Finds elements in the form which should a PARAM_ type set and throws a
1347 * developer debug warning for any elements without it. This is to reduce the
1348 * risk of potential security issues by developers mistakenly forgetting to set
1349 * the type.
1350 *
1351 * @return void
1352 */
1353 private function detectMissingSetType() {
96f81ea3
PS
1354 global $CFG;
1355
1356 if (!$CFG->debugdeveloper) {
b45ba7f6
DP
1357 // Only for devs.
1358 return;
1359 }
1360
1361 $mform = $this->_form;
1362 foreach ($mform->_elements as $element) {
8a9c3f49
FM
1363 $group = false;
1364 $elements = array($element);
1365
1366 if ($element->getType() == 'group') {
1367 $group = $element;
1368 $elements = $element->getElements();
1369 }
1370
1371 foreach ($elements as $index => $element) {
1372 switch ($element->getType()) {
1373 case 'hidden':
1374 case 'text':
1375 case 'url':
1376 if ($group) {
1377 $name = $group->getElementName($index);
1378 } else {
1379 $name = $element->getName();
1380 }
1381 $key = $name;
1382 $found = array_key_exists($key, $mform->_types);
1383 // For repeated elements we need to look for
1384 // the "main" type, not for the one present
1385 // on each repetition. All the stuff in formslib
1386 // (repeat_elements(), updateSubmission()... seems
1387 // to work that way.
1388 while (!$found && strrpos($key, '[') !== false) {
1389 $pos = strrpos($key, '[');
1390 $key = substr($key, 0, $pos);
1391 $found = array_key_exists($key, $mform->_types);
1392 }
1393 if (!$found) {
1394 debugging("Did you remember to call setType() for '$name'? ".
1395 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1396 }
1397 break;
1398 }
b45ba7f6
DP
1399 }
1400 }
1401 }
faaf80fa
JP
1402
1403 /**
1404 * Used by tests to simulate submitted form data submission from the user.
1405 *
1406 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1407 * get_data.
1408 *
1409 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1410 * global arrays after each test.
1411 *
1412 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1413 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1414 * @param string $method 'post' or 'get', defaults to 'post'.
1415 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1416 * a different value here for some forms that are used more than once on the
1417 * same page.
1418 */
1419 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1420 $formidentifier = null) {
1421 $_FILES = $simulatedsubmittedfiles;
1422 if ($formidentifier === null) {
1423 $formidentifier = get_called_class();
518eb193 1424 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
faaf80fa
JP
1425 }
1426 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1427 $simulatedsubmitteddata['sesskey'] = sesskey();
1428 if (strtolower($method) === 'get') {
1429 $_GET = $simulatedsubmitteddata;
1430 } else {
1431 $_POST = $simulatedsubmitteddata;
1432 }
1433 }
7ce44d8e
RW
1434
1435 /**
1436 * Used by tests to generate valid submit keys for moodle forms that are
1437 * submitted with ajax data.
1438 *
1439 * @throws \moodle_exception If called outside unit test environment
1440 * @param array $data Existing form data you wish to add the keys to.
1441 * @return array
1442 */
1443 public static function mock_generate_submit_keys($data = []) {
1444 if (!defined('PHPUNIT_TEST') || !PHPUNIT_TEST) {
1445 throw new \moodle_exception("This function can only be used for unit testing.");
1446 }
1447
1448 $formidentifier = get_called_class();
1449 $formidentifier = str_replace('\\', '_', $formidentifier); // See MDL-56233 for more information.
1450 $data['sesskey'] = sesskey();
1451 $data['_qf__' . $formidentifier] = 1;
1452
1453 return $data;
1454 }
3dee4fae
MG
1455
1456 /**
1457 * Set display mode for the form when labels take full width of the form and above the elements even on big screens
1458 *
1459 * Useful for forms displayed inside modals or in narrow containers
1460 */
1461 public function set_display_vertical() {
1462 $oldclass = $this->_form->getAttribute('class');
1463 $this->_form->updateAttributes(array('class' => $oldclass . ' full-width-labels'));
1464 }
dfd00217
P
1465
1466 /**
1467 * Set the initial 'dirty' state of the form.
1468 *
1469 * @param bool $state
1470 * @since Moodle 3.7.1
1471 */
1472 public function set_initial_dirty_state($state = false) {
1473 $this->_form->set_initial_dirty_state($state);
1474 }
7f40a229 1475}
1476
da1320da 1477/**
6c1fd304
RT
1478 * MoodleQuickForm implementation
1479 *
da1320da 1480 * You never extend this class directly. The class methods of this class are available from
6073a598 1481 * the private $this->_form property on moodleform and its children. You generally only
da1320da 1482 * call methods on this class from within abstract methods that you override on moodleform such
1483 * as definition and definition_after_data
1484 *
6c1fd304
RT
1485 * @package core_form
1486 * @category form
1487 * @copyright 2006 Jamie Pratt <me@jamiep.org>
ba21c9d4 1488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
da1320da 1489 */
7f40a229 1490class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
6c1fd304 1491 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
7f40a229 1492 var $_types = array();
6c1fd304
RT
1493
1494 /** @var array dependent state for the element/'s */
50ef8eb9 1495 var $_dependencies = array();
6c1fd304 1496
d2049862
DS
1497 /**
1498 * @var array elements that will become hidden based on another element
1499 */
1500 protected $_hideifs = array();
1501
6c1fd304 1502 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
19110c57 1503 var $_noSubmitButtons=array();
6c1fd304
RT
1504
1505 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
19110c57 1506 var $_cancelButtons=array();
7f40a229 1507
6c1fd304 1508 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
19194f82 1509 var $_advancedElements = array();
1510
a4067bfc 1511 /**
90a7e556
FM
1512 * Array whose keys are element names and values are the desired collapsible state.
1513 * True for collapsed, False for expanded. If not present, set to default in
1514 * {@link self::accept()}.
a4067bfc
RK
1515 *
1516 * @var array
1517 */
1518 var $_collapsibleElements = array();
1519
1520 /**
1521 * Whether to enable shortforms for this form
1522 *
1523 * @var boolean
1524 */
1525 var $_disableShortforms = false;
1526
6b65e50b
TH
1527 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1528 protected $_use_form_change_checker = true;
1529
dfd00217
P
1530 /**
1531 * The initial state of the dirty state.
1532 *
1533 * @var bool
1534 */
1535 protected $_initial_form_dirty_state = false;
1536
f07b9627 1537 /**
2836e77d 1538 * The form name is derived from the class name of the wrapper minus the trailing form
6c1fd304
RT
1539 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1540 * @var string
f07b9627 1541 */
1542 var $_formName = '';
43914931 1543
4f51f48f 1544 /**
6c1fd304
RT
1545 * String with the html for hidden params passed in as part of a moodle_url
1546 * object for the action. Output in the form.
4f51f48f 1547 * @var string
1548 */
1549 var $_pageparams = '';
1550
5079271b
DS
1551 /** @var array names of new repeating elements that should not expect to find submitted data */
1552 protected $_newrepeats = array();
1553
8ff19f8c
MG
1554 /** @var array $_ajaxformdata submitted form data when using mforms with ajax */
1555 protected $_ajaxformdata;
1556
2edb12ec
DM
1557 /**
1558 * Whether the form contains any client-side validation or not.
1559 * @var bool
1560 */
1561 protected $clientvalidation = false;
1562
d2049862 1563 /**
98887965 1564 * Is this a 'disableIf' dependency ?
d2049862
DS
1565 */
1566 const DEP_DISABLE = 0;
98887965
AA
1567
1568 /**
1569 * Is this a 'hideIf' dependency?
1570 */
d2049862
DS
1571 const DEP_HIDE = 1;
1572
da6f8763 1573 /**
1574 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
ba21c9d4 1575 *
6c1fd304
RT
1576 * @staticvar int $formcounter counts number of forms
1577 * @param string $formName Form's name.
1578 * @param string $method Form's method defaults to 'POST'
1579 * @param string|moodle_url $action Form's action
1580 * @param string $target (optional)Form's target defaults to none
1581 * @param mixed $attributes (optional)Extra attributes for <form> tag
8ff19f8c 1582 * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
da6f8763 1583 */
8ff19f8c 1584 public function __construct($formName, $method, $action, $target = '', $attributes = null, $ajaxformdata = null) {
96705c33 1585 global $CFG, $OUTPUT;
dcf6d93c 1586
271ffe3f 1587 static $formcounter = 1;
7f40a229 1588
32fada5c 1589 // TODO MDL-52313 Replace with the call to parent::__construct().
1a0df553 1590 HTML_Common::__construct($attributes);
da6f8763 1591 $target = empty($target) ? array() : array('target' => $target);
f07b9627 1592 $this->_formName = $formName;
4f51f48f 1593 if (is_a($action, 'moodle_url')){
6ea66ff3 1594 $this->_pageparams = html_writer::input_hidden_params($action);
eb788065 1595 $action = $action->out_omit_querystring();
4f51f48f 1596 } else {
1597 $this->_pageparams = '';
1598 }
28c7749f
FM
1599 // No 'name' atttribute for form in xhtml strict :
1600 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1601 if (is_null($this->getAttribute('id'))) {
4bfcadba
MG
1602 // Append a random id, forms can be loaded in different requests using Fragments API.
1603 $attributes['id'] = 'mform' . $formcounter . '_' . random_string();
28c7749f 1604 }
271ffe3f 1605 $formcounter++;
da6f8763 1606 $this->updateAttributes($attributes);
da6f8763 1607
28c7749f 1608 // This is custom stuff for Moodle :
8ff19f8c 1609 $this->_ajaxformdata = $ajaxformdata;
da6f8763 1610 $oldclass= $this->getAttribute('class');
1611 if (!empty($oldclass)){
1612 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1613 }else {
80f962df 1614 $this->updateAttributes(array('class'=>'mform'));
da6f8763 1615 }
663640f5
DW
1616 $this->_reqHTML = '<span class="req">' . $OUTPUT->pix_icon('req', get_string('requiredelement', 'form')) . '</span>';
1617 $this->_advancedHTML = '<span class="adv">' . $OUTPUT->pix_icon('adv', get_string('advancedelement', 'form')) . '</span>';
a26ce248 1618 $this->setRequiredNote(get_string('somefieldsrequired', 'form', $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'))));
19194f82 1619 }
1620
1a0df553
MG
1621 /**
1622 * Old syntax of class constructor. Deprecated in PHP7.
1623 *
1624 * @deprecated since Moodle 3.1
1625 */
1626 public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1627 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1628 self::__construct($formName, $method, $action, $target, $attributes);
1629 }
1630
a23f0aaf 1631 /**
1632 * Use this method to indicate an element in a form is an advanced field. If items in a form
1633 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1634 * form so the user can decide whether to display advanced form controls.
1635 *
1636 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1637 *
1638 * @param string $elementName group or element name (not the element name of something inside a group).
6c1fd304 1639 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
a23f0aaf 1640 */
90a7e556 1641 function setAdvanced($elementName, $advanced = true) {
a23f0aaf 1642 if ($advanced){
1643 $this->_advancedElements[$elementName]='';
1644 } elseif (isset($this->_advancedElements[$elementName])) {
1645 unset($this->_advancedElements[$elementName]);
1646 }
a23f0aaf 1647 }
a4067bfc 1648
8ff19f8c
MG
1649 /**
1650 * Checks if a parameter was passed in the previous form submission
1651 *
1652 * @param string $name the name of the page parameter we want
1653 * @param mixed $default the default value to return if nothing is found
1654 * @param string $type expected type of parameter
1655 * @return mixed
1656 */
1657 public function optional_param($name, $default, $type) {
1658 if (isset($this->_ajaxformdata[$name])) {
1659 return clean_param($this->_ajaxformdata[$name], $type);
1660 } else {
1661 return optional_param($name, $default, $type);
1662 }
1663 }
1664
a4067bfc
RK
1665 /**
1666 * Use this method to indicate that the fieldset should be shown as expanded.
1667 * The method is applicable to header elements only.
1668 *
f160f97c 1669 * @param string $headername header element name
a4067bfc 1670 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
90a7e556
FM
1671 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1672 * the form was submitted.
f160f97c 1673 * @return void
a4067bfc 1674 */
90a7e556 1675 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
807cf3d0
FM
1676 if (empty($headername)) {
1677 return;
1678 }
f160f97c
FM
1679 $element = $this->getElement($headername);
1680 if ($element->getType() != 'header') {
1681 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1682 return;
1683 }
1684 if (!$headerid = $element->getAttribute('id')) {
1685 $element->_generateId();
1686 $headerid = $element->getAttribute('id');
1687 }
1688 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
90a7e556 1689 // See if the form has been submitted already.
8ff19f8c 1690 $formexpanded = $this->optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
90a7e556 1691 if (!$ignoreuserstate && $formexpanded != -1) {
f160f97c 1692 // Override expanded state with the form variable.
a4067bfc
RK
1693 $expanded = $formexpanded;
1694 }
f160f97c 1695 // Create the form element for storing expanded state.
d23edcf1
TH
1696 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1697 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
f160f97c 1698 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
a4067bfc 1699 }
f160f97c 1700 $this->_collapsibleElements[$headername] = !$expanded;
a4067bfc
RK
1701 }
1702
1703 /**
ac5e6ca4
RK
1704 * Use this method to add show more/less status element required for passing
1705 * over the advanced elements visibility status on the form submission.
a23f0aaf 1706 *
8dcca4aa 1707 * @param string $headerName header element name.
ac5e6ca4 1708 * @param boolean $showmore default false sets the advanced elements to be hidden.
a23f0aaf 1709 */
d23edcf1 1710 function addAdvancedStatusElement($headerid, $showmore=false){
8dcca4aa 1711 // Add extra hidden element to store advanced items state for each section.
d23edcf1 1712 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
8dcca4aa 1713 // See if we the form has been submitted already.
8ff19f8c 1714 $formshowmore = $this->optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
ac5e6ca4 1715 if (!$showmore && $formshowmore != -1) {
8dcca4aa 1716 // Override showmore state with the form variable.
ac5e6ca4 1717 $showmore = $formshowmore;
a23f0aaf 1718 }
8dcca4aa 1719 // Create the form element for storing advanced items state.
d23edcf1
TH
1720 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1721 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1722 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
a23f0aaf 1723 }
19194f82 1724 }
6c1fd304 1725
8dcca4aa
DW
1726 /**
1727 * This function has been deprecated. Show advanced has been replaced by
1728 * "Show more.../Show less..." in the shortforms javascript module.
1729 *
1730 * @deprecated since Moodle 2.5
1731 * @param bool $showadvancedNow if true will show advanced elements.
1732 */
1733 function setShowAdvanced($showadvancedNow = null){
1734 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1735 }
1736
1737 /**
1738 * This function has been deprecated. Show advanced has been replaced by
1739 * "Show more.../Show less..." in the shortforms javascript module.
1740 *
1741 * @deprecated since Moodle 2.5
1742 * @return bool (Always false)
1743 */
1744 function getShowAdvanced(){
1745 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1746 return false;
1747 }
1748
6c1fd304 1749 /**
ac5e6ca4 1750 * Use this method to indicate that the form will not be using shortforms.
6c1fd304 1751 *
ac5e6ca4 1752 * @param boolean $disable default true, controls if the shortforms are disabled.
6c1fd304 1753 */
ac5e6ca4
RK
1754 function setDisableShortforms ($disable = true) {
1755 $this->_disableShortforms = $disable;
19194f82 1756 }
1757
dfd00217
P
1758 /**
1759 * Set the initial 'dirty' state of the form.
1760 *
1761 * @param bool $state
1762 * @since Moodle 3.7.1
1763 */
1764 public function set_initial_dirty_state($state = false) {
1765 $this->_initial_form_dirty_state = $state;
1766 }
1767
1768 /**
1769 * Is the form currently set to dirty?
1770 *
1771 * @return boolean Initial dirty state.
1772 * @since Moodle 3.7.1
1773 */
1774 public function is_dirty() {
1775 return $this->_initial_form_dirty_state;
1776 }
1777
6b65e50b
TH
1778 /**
1779 * Call this method if you don't want the formchangechecker JavaScript to be
1780 * automatically initialised for this form.
1781 */
1782 public function disable_form_change_checker() {
1783 $this->_use_form_change_checker = false;
1784 }
19194f82 1785
6b65e50b
TH
1786 /**
1787 * If you have called {@link disable_form_change_checker()} then you can use
1788 * this method to re-enable it. It is enabled by default, so normally you don't
1789 * need to call this.
1790 */
1791 public function enable_form_change_checker() {
1792 $this->_use_form_change_checker = true;
1793 }
1794
1795 /**
1796 * @return bool whether this form should automatically initialise
1797 * formchangechecker for itself.
1798 */
1799 public function is_form_change_checker_enabled() {
1800 return $this->_use_form_change_checker;
1801 }
1802
1803 /**
19194f82 1804 * Accepts a renderer
1805 *
6c1fd304 1806 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
19194f82 1807 */
46f3921e 1808 function accept(&$renderer) {
19194f82 1809 if (method_exists($renderer, 'setAdvancedElements')){
a4067bfc 1810 //Check for visible fieldsets where all elements are advanced
19194f82 1811 //and mark these headers as advanced as well.
a4067bfc 1812 //Also mark all elements in a advanced header as advanced.
19194f82 1813 $stopFields = $renderer->getStopFieldSetElements();
1814 $lastHeader = null;
1815 $lastHeaderAdvanced = false;
1816 $anyAdvanced = false;
ac5e6ca4 1817 $anyError = false;
19194f82 1818 foreach (array_keys($this->_elements) as $elementIndex){
1819 $element =& $this->_elements[$elementIndex];
46f3921e 1820
1821 // if closing header and any contained element was advanced then mark it as advanced
19194f82 1822 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
d23edcf1
TH
1823 if ($anyAdvanced && !is_null($lastHeader)) {
1824 $lastHeader->_generateId();
19194f82 1825 $this->setAdvanced($lastHeader->getName());
d23edcf1 1826 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
19194f82 1827 }
1828 $lastHeaderAdvanced = false;
46f3921e 1829 unset($lastHeader);
1830 $lastHeader = null;
19194f82 1831 } elseif ($lastHeaderAdvanced) {
1832 $this->setAdvanced($element->getName());
1833 }
46f3921e 1834
19194f82 1835 if ($element->getType()=='header'){
1836 $lastHeader =& $element;
1837 $anyAdvanced = false;
ac5e6ca4 1838 $anyError = false;
19194f82 1839 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1840 } elseif (isset($this->_advancedElements[$element->getName()])){
1841 $anyAdvanced = true;
ac5e6ca4
RK
1842 if (isset($this->_errors[$element->getName()])) {
1843 $anyError = true;
1844 }
19194f82 1845 }
1846 }
46f3921e 1847 // the last header may not be closed yet...
1848 if ($anyAdvanced && !is_null($lastHeader)){
1849 $this->setAdvanced($lastHeader->getName());
d23edcf1
TH
1850 $lastHeader->_generateId();
1851 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
46f3921e 1852 }
19194f82 1853 $renderer->setAdvancedElements($this->_advancedElements);
a4067bfc 1854 }
90a7e556
FM
1855 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1856
1857 // Count the number of sections.
1858 $headerscount = 0;
1859 foreach (array_keys($this->_elements) as $elementIndex){
1860 $element =& $this->_elements[$elementIndex];
1861 if ($element->getType() == 'header') {
1862 $headerscount++;
1863 }
1864 }
1865
1866 $anyrequiredorerror = false;
a4067bfc 1867 $headercounter = 0;
90a7e556 1868 $headername = null;
a4067bfc
RK
1869 foreach (array_keys($this->_elements) as $elementIndex){
1870 $element =& $this->_elements[$elementIndex];
90a7e556 1871
41068d98 1872 if ($element->getType() == 'header') {
a4067bfc 1873 $headercounter++;
90a7e556
FM
1874 $element->_generateId();
1875 $headername = $element->getName();
1876 $anyrequiredorerror = false;
1877 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1878 $anyrequiredorerror = true;
1879 } else {
1880 // Do not reset $anyrequiredorerror to false because we do not want any other element
1881 // in this header (fieldset) to possibly revert the state given.
a4067bfc 1882 }
41068d98 1883
90a7e556
FM
1884 if ($element->getType() == 'header') {
1885 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1886 // By default the first section is always expanded, except if a state has already been set.
1887 $this->setExpanded($headername, true);
1888 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1889 // The second section is always expanded if the form only contains 2 sections),
1890 // except if a state has already been set.
41068d98 1891 $this->setExpanded($headername, true);
a4067bfc 1892 }
90a7e556
FM
1893 } else if ($anyrequiredorerror) {
1894 // If any error or required field are present within the header, we need to expand it.
1895 $this->setExpanded($headername, true, true);
1896 } else if (!isset($this->_collapsibleElements[$headername])) {
1897 // Define element as collapsed by default.
1898 $this->setExpanded($headername, false);
a4067bfc
RK
1899 }
1900 }
90a7e556 1901
a4067bfc 1902 // Pass the array to renderer object.
f160f97c 1903 $renderer->setCollapsibleElements($this->_collapsibleElements);
19194f82 1904 }
1905 parent::accept($renderer);
1906 }
1907
ba21c9d4 1908 /**
6c1fd304
RT
1909 * Adds one or more element names that indicate the end of a fieldset
1910 *
1911 * @param string $elementName name of the element
ba21c9d4 1912 */
19194f82 1913 function closeHeaderBefore($elementName){
1914 $renderer =& $this->defaultRenderer();
1915 $renderer->addStopFieldsetElements($elementName);
da6f8763 1916 }
bb40325e 1917
fc7f69e7
FM
1918 /**
1919 * Set an element to be forced to flow LTR.
1920 *
1921 * The element must exist and support this functionality. Also note that
1922 * when setting the type of a field (@link self::setType} we try to guess the
1923 * whether the field should be force to LTR or not. Make sure you're always
1924 * calling this method last.
1925 *
1926 * @param string $elementname The element name.
1927 * @param bool $value When false, disables force LTR, else enables it.
1928 */
1929 public function setForceLtr($elementname, $value = true) {
1930 $this->getElement($elementname)->set_force_ltr($value);
1931 }
1932
da1320da 1933 /**
1934 * Should be used for all elements of a form except for select, radio and checkboxes which
1935 * clean their own data.
1936 *
1937 * @param string $elementname
6c1fd304 1938 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
58b7d48f 1939 * {@link lib/moodlelib.php} for defined parameter types
da1320da 1940 */
7f40a229 1941 function setType($elementname, $paramtype) {
1942 $this->_types[$elementname] = $paramtype;
fc7f69e7 1943
8a40bc36
FM
1944 // This will not always get it right, but it should be accurate in most cases.
1945 // When inaccurate use setForceLtr().
1946 if (!is_rtl_compatible($paramtype)
fc7f69e7
FM
1947 && $this->elementExists($elementname)
1948 && ($element =& $this->getElement($elementname))
1949 && method_exists($element, 'set_force_ltr')) {
1950
1951 $element->set_force_ltr(true);
1952 }
7f40a229 1953 }
49292f8c 1954
da1320da 1955 /**
6c1fd304 1956 * This can be used to set several types at once.
da1320da 1957 *
6c1fd304
RT
1958 * @param array $paramtypes types of parameters.
1959 * @see MoodleQuickForm::setType
da1320da 1960 */
c56f1826 1961 function setTypes($paramtypes) {
fc7f69e7
FM
1962 foreach ($paramtypes as $elementname => $paramtype) {
1963 $this->setType($elementname, $paramtype);
1964 }
c56f1826 1965 }
49292f8c 1966
3c0ba94e
FM
1967 /**
1968 * Return the type(s) to use to clean an element.
1969 *
1970 * In the case where the element has an array as a value, we will try to obtain a
1971 * type defined for that specific key, and recursively until done.
1972 *
1973 * This method does not work reverse, you cannot pass a nested element and hoping to
1974 * fallback on the clean type of a parent. This method intends to be used with the
1975 * main element, which will generate child types if needed, not the other way around.
1976 *
1977 * Example scenario:
1978 *
1979 * You have defined a new repeated element containing a text field called 'foo'.
1980 * By default there will always be 2 occurence of 'foo' in the form. Even though
1981 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1982 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1983 * $mform->setType('foo[0]', PARAM_FLOAT).
1984 *
1985 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1986 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1987 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
d5909fd1 1988 * get the default clean type returned (param $default).
3c0ba94e
FM
1989 *
1990 * @param string $elementname name of the element.
1991 * @param mixed $value value that should be cleaned.
d5909fd1 1992 * @param int $default default constant value to be returned (PARAM_...)
3c0ba94e
FM
1993 * @return string|array constant value or array of constant values (PARAM_...)
1994 */
1995 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1996 $type = $default;
1997 if (array_key_exists($elementname, $this->_types)) {
1998 $type = $this->_types[$elementname];
1999 }
2000 if (is_array($value)) {
2001 $default = $type;
2002 $type = array();
2003 foreach ($value as $subkey => $subvalue) {
2004 $typekey = "$elementname" . "[$subkey]";
2005 if (array_key_exists($typekey, $this->_types)) {
2006 $subtype = $this->_types[$typekey];
2007 } else {
2008 $subtype = $default;
2009 }
2010 if (is_array($subvalue)) {
2011 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
2012 } else {
2013 $type[$subkey] = $subtype;
2014 }
2015 }
2016 }
2017 return $type;
2018 }
2019
2020 /**
2021 * Return the cleaned value using the passed type(s).
2022 *
2023 * @param mixed $value value that has to be cleaned.
2024 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
2025 * @return mixed cleaned up value.
2026 */
2027 public function getCleanedValue($value, $type) {
2028 if (is_array($type) && is_array($value)) {
2029 foreach ($type as $key => $param) {
2030 $value[$key] = $this->getCleanedValue($value[$key], $param);
2031 }
2032 } else if (!is_array($type) && !is_array($value)) {
2033 $value = clean_param($value, $type);
2034 } else if (!is_array($type) && is_array($value)) {
2035 $value = clean_param_array($value, $type, true);
2036 } else {
d5909fd1 2037 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
3c0ba94e
FM
2038 }
2039 return $value;
2040 }
2041
ba21c9d4 2042 /**
6c1fd304
RT
2043 * Updates submitted values
2044 *
2045 * @param array $submission submitted values
2046 * @param array $files list of files
ba21c9d4 2047 */
49292f8c 2048 function updateSubmission($submission, $files) {
2049 $this->_flagSubmitted = false;
2050
7f40a229 2051 if (empty($submission)) {
2052 $this->_submitValues = array();
7f40a229 2053 } else {
3c0ba94e
FM
2054 foreach ($submission as $key => $s) {
2055 $type = $this->getCleanType($key, $s);
2056 $submission[$key] = $this->getCleanedValue($s, $type);
7f40a229 2057 }
294ce987 2058 $this->_submitValues = $submission;
7f40a229 2059 $this->_flagSubmitted = true;
2060 }
2061
49292f8c 2062 if (empty($files)) {
2063 $this->_submitFiles = array();
2064 } else {
49292f8c 2065 $this->_submitFiles = $files;
2066 $this->_flagSubmitted = true;
2067 }
2068
2c412890 2069 // need to tell all elements that they need to update their value attribute.
2070 foreach (array_keys($this->_elements) as $key) {
2071 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
2072 }
7f40a229 2073 }
2074
ba21c9d4 2075 /**
6c1fd304
RT
2076 * Returns HTML for required elements
2077 *
ba21c9d4 2078 * @return string
2079 */
da6f8763 2080 function getReqHTML(){
2081 return $this->_reqHTML;
2082 }
117bd748 2083
ba21c9d4 2084 /**
6c1fd304
RT
2085 * Returns HTML for advanced elements
2086 *
ba21c9d4 2087 * @return string
2088 */
19194f82 2089 function getAdvancedHTML(){
2090 return $this->_advancedHTML;
2091 }
2092
7f40a229 2093 /**
da1320da 2094 * Initializes a default form value. Used to specify the default for a new entry where
beac4717 2095 * no data is loaded in using moodleform::set_data()
7f40a229 2096 *
294ce987 2097 * note: $slashed param removed
2098 *
6c1fd304
RT
2099 * @param string $elementName element name
2100 * @param mixed $defaultValue values for that element name
7f40a229 2101 */
294ce987 2102 function setDefault($elementName, $defaultValue){
2103 $this->setDefaults(array($elementName=>$defaultValue));
6c1fd304
RT
2104 }
2105
53a78cef 2106 /**
259c165d
PS
2107 * Add a help button to element, only one button per element is allowed.
2108 *
ff95caa8
DM
2109 * This is new, simplified and preferable method of setting a help icon on form elements.
2110 * It uses the new $OUTPUT->help_icon().
2111 *
2112 * Typically, you will provide the same identifier and the component as you have used for the
2113 * label of the element. The string identifier with the _help suffix added is then used
2114 * as the help string.
2115 *
259c165d
PS
2116 * There has to be two strings defined:
2117 * 1/ get_string($identifier, $component) - the title of the help page
5435c9dc 2118 * 2/ get_string($identifier.'_help', $component) - the actual help page text
53a78cef 2119 *
6c1fd304 2120 * @since Moodle 2.0
53a78cef 2121 * @param string $elementname name of the element to add the item to
2836e77d 2122 * @param string $identifier help string identifier without _help suffix
ff95caa8
DM
2123 * @param string $component component name to look the help string in
2124 * @param string $linktext optional text to display next to the icon
6c1fd304 2125 * @param bool $suppresscheck set to true if the element may not exist
53a78cef 2126 */
259c165d
PS
2127 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
2128 global $OUTPUT;
53a78cef 2129 if (array_key_exists($elementname, $this->_elementIndex)) {
af140288
DC
2130 $element = $this->_elements[$this->_elementIndex[$elementname]];
2131 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
53a78cef
PS
2132 } else if (!$suppresscheck) {
2133 debugging(get_string('nonexistentformelements', 'form', $elementname));
2134 }
2135 }
2136
cc444336 2137 /**
2836e77d 2138 * Set constant value not overridden by _POST or _GET
cc444336 2139 * note: this does not work for complex names with [] :-(
ba21c9d4 2140 *
cc444336 2141 * @param string $elname name of element
2142 * @param mixed $value
cc444336 2143 */
2144 function setConstant($elname, $value) {
2145 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
2146 $element =& $this->getElement($elname);
2147 $element->onQuickFormEvent('updateValue', null, $this);
2148 }
2149
ba21c9d4 2150 /**
6c1fd304
RT
2151 * export submitted values
2152 *
2153 * @param string $elementList list of elements in form
2154 * @return array
ba21c9d4 2155 */
294ce987 2156 function exportValues($elementList = null){
0ffb4cc7 2157 $unfiltered = array();
2158 if (null === $elementList) {
2159 // iterate over all elements, calling their exportValue() methods
2160 foreach (array_keys($this->_elements) as $key) {
8e73fbf5
AG
2161 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
2162 $varname = $this->_elements[$key]->_attributes['name'];
2163 $value = '';
2164 // If we have a default value then export it.
2165 if (isset($this->_defaultValues[$varname])) {
5f137dcb 2166 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
8e73fbf5 2167 }
0ffb4cc7 2168 } else {
2169 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
2170 }
2171
2172 if (is_array($value)) {
2173 // This shit throws a bogus warning in PHP 4.3.x
2174 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
2175 }
2176 }
2177 } else {
2178 if (!is_array($elementList)) {
2179 $elementList = array_map('trim', explode(',', $elementList));
2180 }
2181 foreach ($elementList as $elementName) {
2182 $value = $this->exportValue($elementName);
fabbf439 2183 if (@PEAR::isError($value)) {
0ffb4cc7 2184 return $value;
2185 }
4287fc0d 2186 //oh, stock QuickFOrm was returning array of arrays!
2187 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
0ffb4cc7 2188 }
2189 }
7f40a229 2190
f1f70bd4
DC
2191 if (is_array($this->_constantValues)) {
2192 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
2193 }
294ce987 2194 return $unfiltered;
da6f8763 2195 }
6c1fd304 2196
5f137dcb
TH
2197 /**
2198 * This is a bit of a hack, and it duplicates the code in
2199 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
2200 * reliably calling that code. (Think about date selectors, for example.)
2201 * @param string $name the element name.
2202 * @param mixed $value the fixed value to set.
2203 * @return mixed the appropriate array to add to the $unfiltered array.
2204 */
2205 protected function prepare_fixed_value($name, $value) {
2206 if (null === $value) {
2207 return null;
2208 } else {
2209 if (!strpos($name, '[')) {
2210 return array($name => $value);
2211 } else {
2212 $valueAry = array();
2213 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
2214 eval("\$valueAry$myIndex = \$value;");
2215 return $valueAry;
2216 }
2217 }
2218 }
2219
f07b9627 2220 /**
2221 * Adds a validation rule for the given field
2222 *
2223 * If the element is in fact a group, it will be considered as a whole.
2224 * To validate grouped elements as separated entities,
2225 * use addGroupRule instead of addRule.
2226 *
6c1fd304
RT
2227 * @param string $element Form element name
2228 * @param string $message Message to display for invalid data
2229 * @param string $type Rule type, use getRegisteredRules() to get types
2230 * @param string $format (optional)Required for extra rule data
2231 * @param string $validation (optional)Where to perform validation: "server", "client"
2232 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2233 * @param bool $force Force the rule to be applied, even if the target form element does not exist
f07b9627 2234 */
2235 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2236 {
2237 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2238 if ($validation == 'client') {
2edb12ec 2239 $this->clientvalidation = true;
f07b9627 2240 }
2241
6c1fd304
RT
2242 }
2243
f07b9627 2244 /**
2245 * Adds a validation rule for the given group of elements
2246 *
2247 * Only groups with a name can be assigned a validation rule
2248 * Use addGroupRule when you need to validate elements inside the group.
2249 * Use addRule if you need to validate the group as a whole. In this case,
2250 * the same rule will be applied to all elements in the group.
2251 * Use addRule if you need to validate the group against a function.
2252 *
6c1fd304
RT
2253 * @param string $group Form group name
2254 * @param array|string $arg1 Array for multiple elements or error message string for one element
2255 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2256 * @param string $format (optional)Required for extra rule data
2257 * @param int $howmany (optional)How many valid elements should be in the group
2258 * @param string $validation (optional)Where to perform validation: "server", "client"
2259 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
f07b9627 2260 */
2261 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2262 {
2263 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2264 if (is_array($arg1)) {
3a298174 2265 foreach ($arg1 as $rules) {
f07b9627 2266 foreach ($rules as $rule) {
2267 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2edb12ec
DM
2268 if ($validation == 'client') {
2269 $this->clientvalidation = true;
f07b9627 2270 }
2271 }
2272 }
2273 } elseif (is_string($arg1)) {
f07b9627 2274 if ($validation == 'client') {
2edb12ec 2275 $this->clientvalidation = true;
f07b9627 2276 }
2277 }
6c1fd304 2278 }
f07b9627 2279
5bc97c98 2280 /**
2281 * Returns the client side validation script
2282 *
2283 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2284 * and slightly modified to run rules per-element
2285 * Needed to override this because of an error with client side validation of grouped elements.
2286 *
6c1fd304 2287 * @return string Javascript to perform validation, empty string if no 'client' rules were added
5bc97c98 2288 */
2289 function getValidationScript()
2290 {
91bda4cd
DW
2291 global $PAGE;
2292
2edb12ec 2293 if (empty($this->_rules) || $this->clientvalidation === false) {
5bc97c98 2294 return '';
2295 }
2296
2297 include_once('HTML/QuickForm/RuleRegistry.php');
2298 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2299 $test = array();
2300 $js_escape = array(
2301 "\r" => '\r',
2302 "\n" => '\n',
2303 "\t" => '\t',
2304 "'" => "\\'",
2305 '"' => '\"',
2306 '\\' => '\\\\'
2307 );
2308
2309 foreach ($this->_rules as $elementName => $rules) {
2310 foreach ($rules as $rule) {
2311 if ('client' == $rule['validation']) {
da1320da 2312 unset($element); //TODO: find out how to properly initialize it
5bc97c98 2313
2314 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2315 $rule['message'] = strtr($rule['message'], $js_escape);
2316
2317 if (isset($rule['group'])) {
2318 $group =& $this->getElement($rule['group']);
2319 // No JavaScript validation for frozen elements
2320 if ($group->isFrozen()) {
2321 continue 2;
2322 }
2323 $elements =& $group->getElements();
2324 foreach (array_keys($elements) as $key) {
2325 if ($elementName == $group->getElementName($key)) {
2326 $element =& $elements[$key];
2327 break;
2328 }
2329 }
2330 } elseif ($dependent) {
2331 $element = array();
2332 $element[] =& $this->getElement($elementName);
3a298174 2333 foreach ($rule['dependent'] as $elName) {
5bc97c98 2334 $element[] =& $this->getElement($elName);
2335 }
2336 } else {
2337 $element =& $this->getElement($elementName);
2338 }
2339 // No JavaScript validation for frozen elements
2340 if (is_object($element) && $element->isFrozen()) {
2341 continue 2;
2342 } elseif (is_array($element)) {
2343 foreach (array_keys($element) as $key) {
2344 if ($element[$key]->isFrozen()) {
2345 continue 3;
2346 }
2347 }
2348 }
ab978b38 2349 //for editor element, [text] is appended to the name.
d79d0717 2350 $fullelementname = $elementName;
4c4b966a 2351 if (is_object($element) && $element->getType() == 'editor') {
2352 if ($element->getType() == 'editor') {
2353 $fullelementname .= '[text]';
2354 // Add format to rule as moodleform check which format is supported by browser
2355 // it is not set anywhere... So small hack to make sure we pass it down to quickform.
2356 if (is_null($rule['format'])) {
2357 $rule['format'] = $element->getFormat();
2358 }
ab978b38 2359 }
56728202 2360 }
ab978b38 2361 // Fix for bug displaying errors for elements in a group
d79d0717
DS
2362 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2363 $test[$fullelementname][1]=$element;
5bc97c98 2364 //end of fix
2365 }
2366 }
2367 }
7c77033f 2368
2369 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2370 // the form, and then that form field gets corrupted by the code that follows.
2371 unset($element);
2372
5bc97c98 2373 $js = '
1cbb09f1 2374
91bda4cd 2375require(["core/event", "jquery"], function(Event, $) {
fed13a5e 2376
91bda4cd
DW
2377 function qf_errorHandler(element, _qfMsg, escapedName) {
2378 var event = $.Event(Event.Events.FORM_FIELD_VALIDATION);
2379 $(element).trigger(event, _qfMsg);
2380 if (event.isDefaultPrevented()) {
2381 return _qfMsg == \'\';
2382 } else {
2383 // Legacy mforms.
2384 var div = element.parentNode;
2385
2386 if ((div == undefined) || (element.name == undefined)) {
2387 // No checking can be done for undefined elements so let server handle it.
2388 return true;
2389 }
2390
2391 if (_qfMsg != \'\') {
2392 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2393 if (!errorSpan) {
2394 errorSpan = document.createElement("span");
2395 errorSpan.id = \'id_error_\' + escapedName;
2396 errorSpan.className = "error";
2397 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2398 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2399 document.getElementById(errorSpan.id).focus();
2400 }
2c412890 2401
91bda4cd
DW
2402 while (errorSpan.firstChild) {
2403 errorSpan.removeChild(errorSpan.firstChild);
2404 }
5bc97c98 2405
91bda4cd 2406 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
5bc97c98 2407
91bda4cd
DW
2408 if (div.className.substr(div.className.length - 6, 6) != " error"
2409 && div.className != "error") {
2410 div.className += " error";
2411 linebreak = document.createElement("br");
2412 linebreak.className = "error";
2413 linebreak.id = \'id_error_break_\' + escapedName;
2414 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2415 }
5bc97c98 2416
91bda4cd
DW
2417 return false;
2418 } else {
2419 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2420 if (errorSpan) {
2421 errorSpan.parentNode.removeChild(errorSpan);
2422 }
2423 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2424 if (linebreak) {
2425 linebreak.parentNode.removeChild(linebreak);
2426 }
5bc97c98 2427
91bda4cd
DW
2428 if (div.className.substr(div.className.length - 6, 6) == " error") {
2429 div.className = div.className.substr(0, div.className.length - 6);
2430 } else if (div.className == "error") {
2431 div.className = "";
2432 }
2edb12ec 2433
91bda4cd
DW
2434 return true;
2435 } // End if.
2436 } // End if.
2437 } // End function.
2438 ';
5bc97c98 2439 $validateJS = '';
2440 foreach ($test as $elementName => $jsandelement) {
2441 // Fix for bug displaying errors for elements in a group
2442 //unset($element);
2443 list($jsArr,$element)=$jsandelement;
2444 //end of fix
8af229fe 2445 $escapedElementName = preg_replace_callback(
ed608e7a 2446 '/[_\[\]-]/',
484b43f4
MG
2447 function($matches) {
2448 return sprintf("_%2x", ord($matches[0]));
2449 },
8af229fe 2450 $elementName);
2edb12ec
DM
2451 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
2452
4c4b966a 2453 if (!is_array($element)) {
2454 $element = [$element];
2455 }
2456 foreach ($element as $elem) {
2457 if (key_exists('id', $elem->_attributes)) {
2458 $js .= '
2edb12ec
DM
2459 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2460 if (undefined == element) {
2461 //required element was not found, then let form be submitted without client side validation
2462 return true;
b29c9b05 2463 }
2edb12ec
DM
2464 var value = \'\';
2465 var errFlag = new Array();
2466 var _qfGroups = {};
2467 var _qfMsg = \'\';
2468 var frm = element.parentNode;
2469 if ((undefined != element.name) && (frm != undefined)) {
2470 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2471 frm = frm.parentNode;
2472 }
2473 ' . join("\n", $jsArr) . '
2474 return qf_errorHandler(element, _qfMsg, escapedName);
2475 } else {
2476 //element name should be defined else error msg will not be displayed.
2477 return true;
2478 }
2479 }
2480
4c4b966a 2481 document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'blur\', function(ev) {
2edb12ec
DM
2482 ' . $valFunc . '
2483 });
4c4b966a 2484 document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'change\', function(ev) {
2edb12ec
DM
2485 ' . $valFunc . '
2486 });
5bc97c98 2487';
4c4b966a 2488 }
2489 }
51200878
JD
2490 // This handles both randomised (MDL-65217) and non-randomised IDs.
2491 $errorid = preg_replace('/^id_/', 'id_error_', $this->_attributes['id']);
5bc97c98 2492 $validateJS .= '
2edb12ec
DM
2493 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2494 if (!ret && !first_focus) {
2495 first_focus = true;
2496 Y.use(\'moodle-core-event\', function() {
2497 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes['id'] . '\',
51200878
JD
2498 elementid: \'' . $errorid. '\'});
2499 document.getElementById(\'' . $errorid . '\').focus();
2edb12ec
DM
2500 });
2501 }
2ef7c374 2502';
4f51f48f 2503
5bc97c98 2504 // Fix for bug displaying errors for elements in a group
2505 //unset($element);
2506 //$element =& $this->getElement($elementName);
2507 //end of fix
2edb12ec
DM
2508 //$onBlur = $element->getAttribute('onBlur');
2509 //$onChange = $element->getAttribute('onChange');
2510 //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2511 //'onChange' => $onChange . $valFunc));
5bc97c98 2512 }
e7004d05 2513// do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
5bc97c98 2514 $js .= '
2edb12ec
DM
2515
2516 function validate_' . $this->_formName . '() {
2517 if (skipClientValidation) {
2518 return true;
2519 }
2520 var ret = true;
2521
2522 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2523 var first_focus = false;
2524 ' . $validateJS . ';
2525 return ret;
2526 }
2527
260565e3
DW
2528 var form = $(document.getElementById(\'' . $this->_attributes['id'] . '\')).closest(\'form\');
2529 form.on(M.core.event.FORM_SUBMIT_AJAX, function() {
2530 try {
2531 var myValidator = validate_' . $this->_formName . ';
2532 } catch(e) {
2533 return true;
2534 }
2535 if (myValidator) {
2536 myValidator();
2537 }
2538 });
2edb12ec
DM
2539
2540 document.getElementById(\'' . $this->_attributes['id'] . '\').addEventListener(\'submit\', function(ev) {
2541 try {
2542 var myValidator = validate_' . $this->_formName . ';
2543 } catch(e) {
2544 return true;
2545 }
929727e3
DM
2546 if (typeof window.tinyMCE !== \'undefined\') {
2547 window.tinyMCE.triggerSave();
2548 }
2edb12ec
DM
2549 if (!myValidator()) {
2550 ev.preventDefault();
2551 }
2552 });
91bda4cd
DW
2553
2554});
2555';
2556
2557 $PAGE->requires->js_amd_inline($js);
df07fead
FM
2558
2559 // Global variable used to skip the client validation.
3264bf5b 2560 return html_writer::tag('script', 'var skipClientValidation = false;');
5bc97c98 2561 } // end func getValidationScript
6c1fd304
RT
2562
2563 /**
2564 * Sets default error message
2565 */
5bc97c98 2566 function _setDefaultRuleMessages(){
2567 foreach ($this->_rules as $field => $rulesarr){
2568 foreach ($rulesarr as $key => $rule){
2569 if ($rule['message']===null){
365a5941 2570 $a=new stdClass();
5bc97c98 2571 $a->format=$rule['format'];
2572 $str=get_string('err_'.$rule['type'], 'form', $a);
2573 if (strpos($str, '[[')!==0){
2574 $this->_rules[$field][$key]['message']=$str;
2c412890 2575 }
5bc97c98 2576 }
2577 }
2578 }
2579 }
bb40325e 2580
6c1fd304
RT
2581 /**
2582 * Get list of attributes which have dependencies
2583 *
2584 * @return array
2585 */
c7e3e61c
SH
2586 function getLockOptionObject(){
2587 $result = array();
dd07bbac 2588 foreach ($this->_dependencies as $dependentOn => $conditions){
c7e3e61c 2589 $result[$dependentOn] = array();
dd07bbac 2590 foreach ($conditions as $condition=>$values) {
c7e3e61c 2591 $result[$dependentOn][$condition] = array();
dd07bbac 2592 foreach ($values as $value=>$dependents) {
d2049862 2593 $result[$dependentOn][$condition][$value][self::DEP_DISABLE] = array();
dd07bbac 2594 foreach ($dependents as $dependent) {
2595 $elements = $this->_getElNamesRecursive($dependent);
46f3921e 2596 if (empty($elements)) {
2597 // probably element inside of some group
2598 $elements = array($dependent);
2599 }
dd07bbac 2600 foreach($elements as $element) {
2601 if ($element == $dependentOn) {
2602 continue;
2603 }
f3da329d 2604 $result[$dependentOn][$condition][$value][self::DEP_DISABLE][] = $element;
d2049862
DS
2605 }
2606 }
2607 }
2608 }
2609 }
98887965 2610 foreach ($this->_hideifs as $dependenton => $conditions) {
8fc3d411
DS
2611 if (!isset($result[$dependenton])) {
2612 $result[$dependenton] = array();
2613 }
d2049862 2614 foreach ($conditions as $condition => $values) {
8fc3d411
DS
2615 if (!isset($result[$dependenton][$condition])) {
2616 $result[$dependenton][$condition] = array();
2617 }
d2049862
DS
2618 foreach ($values as $value => $dependents) {
2619 $result[$dependenton][$condition][$value][self::DEP_HIDE] = array();
2620 foreach ($dependents as $dependent) {
2621 $elements = $this->_getElNamesRecursive($dependent);
766d6f9a
DS
2622 if (!in_array($dependent, $elements)) {
2623 // Always want to hide the main element, even if it contains sub-elements as well.
2624 $elements[] = $dependent;
d2049862
DS
2625 }
2626 foreach ($elements as $element) {
2627 if ($element == $dependenton) {
2628 continue;
2629 }
f3da329d 2630 $result[$dependenton][$condition][$value][self::DEP_HIDE][] = $element;
dd07bbac 2631 }
11f260f4 2632 }
2633 }
50ef8eb9 2634 }
dd07bbac 2635 }
c7e3e61c 2636 return array($this->getAttribute('id'), $result);
bb40325e 2637 }
d01a38cb 2638
ba21c9d4 2639 /**
6c1fd304
RT
2640 * Get names of element or elements in a group.
2641 *
2642 * @param HTML_QuickForm_group|element $element element group or element object
ba21c9d4 2643 * @return array
2644 */
46f3921e 2645 function _getElNamesRecursive($element) {
2646 if (is_string($element)) {
4f51f48f 2647 if (!$this->elementExists($element)) {
2648 return array();
2649 }
46f3921e 2650 $element = $this->getElement($element);
d01a38cb 2651 }
46f3921e 2652
2653 if (is_a($element, 'HTML_QuickForm_group')) {
2654 $elsInGroup = $element->getElements();
9403060a 2655 $elNames = array();
d01a38cb 2656 foreach ($elsInGroup as $elInGroup){
e850ec48 2657 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
b4eb5f02
MG
2658 // Groups nested in groups: append the group name to the element and then change it back.
2659 // We will be appending group name again in MoodleQuickForm_group::export_for_template().
2660 $oldname = $elInGroup->getName();
2661 if ($element->_appendName) {
2662 $elInGroup->setName($element->getName() . '[' . $oldname . ']');
2663 }
e850ec48 2664 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
b4eb5f02 2665 $elInGroup->setName($oldname);
e850ec48 2666 } else {
2667 $elNames[] = $element->getElementName($elInGroup->getName());
2668 }
d01a38cb 2669 }
46f3921e 2670
2671 } else if (is_a($element, 'HTML_QuickForm_header')) {
2672 return array();
2673
2674 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2675 return array();
2676
8f6384a9
TH
2677 } else if (method_exists($element, 'getPrivateName') &&
2678 !($element instanceof HTML_QuickForm_advcheckbox)) {
2679 // The advcheckbox element implements a method called getPrivateName,
2680 // but in a way that is not compatible with the generic API, so we
2681 // have to explicitly exclude it.
46f3921e 2682 return array($element->getPrivateName());
2683
2684 } else {
2685 $elNames = array($element->getName());
d01a38cb 2686 }
d01a38cb 2687
46f3921e 2688 return $elNames;
50ef8eb9 2689 }
46f3921e 2690
6e372b25 2691 /**
2692 * Adds a dependency for $elementName which will be disabled if $condition is met.
9403060a 2693 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2694 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
31a6c06c 2695 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2696 * of the $dependentOn element is $condition (such as equal) to $value.
6e372b25 2697 *
58f3865f
FM
2698 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2699 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2700 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2701 *
6e372b25 2702 * @param string $elementName the name of the element which will be disabled
6c1fd304 2703 * @param string $dependentOn the name of the element whose state will be checked for condition
6e372b25 2704 * @param string $condition the condition to check
19110c57 2705 * @param mixed $value used in conjunction with condition.
6e372b25 2706 */
58f3865f
FM
2707 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2708 // Multiple selects allow for a multiple selection, we transform the array to string here as
2709 // an array cannot be used as a key in an associative array.
2710 if (is_array($value)) {
2711 $value = implode('|', $value);
2712 }
dd07bbac 2713 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2714 $this->_dependencies[$dependentOn] = array();
2715 }
2716 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2717 $this->_dependencies[$dependentOn][$condition] = array();
2718 }
2719 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2720 $this->_dependencies[$dependentOn][$condition][$value] = array();
2721 }
2722 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
bb40325e 2723 }
dd07bbac 2724
d2049862
DS
2725 /**
2726 * Adds a dependency for $elementName which will be hidden if $condition is met.
2727 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2728 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2729 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2730 * of the $dependentOn element is $condition (such as equal) to $value.
2731 *
2732 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2733 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2734 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2735 *
2736 * @param string $elementname the name of the element which will be hidden
2737 * @param string $dependenton the name of the element whose state will be checked for condition
2738 * @param string $condition the condition to check
2739 * @param mixed $value used in conjunction with condition.
2740 */
2741 public function hideIf($elementname, $dependenton, $condition = 'notchecked', $value = '1') {
2742 // Multiple selects allow for a multiple selection, we transform the array to string here as
2743 // an array cannot be used as a key in an associative array.
2744 if (is_array($value)) {
2745 $value = implode('|', $value);
2746 }
2747 if (!array_key_exists($dependenton, $this->_hideifs)) {
2748 $this->_hideifs[$dependenton] = array();
2749 }
2750 if (!array_key_exists($condition, $this->_hideifs[$dependenton])) {
2751 $this->_hideifs[$dependenton][$condition] = array();
2752 }
2753 if (!array_key_exists($value, $this->_hideifs[$dependenton][$condition])) {
2754 $this->_hideifs[$dependenton][$condition][$value] = array();
2755 }
2756 $this->_hideifs[$dependenton][$condition][$value][] = $elementname;
2757 }
2758
6c1fd304
RT
2759 /**
2760 * Registers button as no submit button
2761 *
2762 * @param string $buttonname name of the button
2763 */
a23f0aaf 2764 function registerNoSubmitButton($buttonname){
2765 $this->_noSubmitButtons[]=$buttonname;
2766 }
dd07bbac 2767
ba21c9d4 2768 /**
6c1fd304
RT
2769 * Checks if button is a no submit button, i.e it doesn't submit form
2770 *
2771 * @param string $buttonname name of the button to check
2772 * @return bool
ba21c9d4 2773 */
a23f0aaf 2774 function isNoSubmitButton($buttonname){
2775 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
19110c57 2776 }
dd07bbac 2777
ba21c9d4 2778 /**
6c1fd304
RT
2779 * Registers a button as cancel button
2780 *
2781 * @param string $addfieldsname name of the button
ba21c9d4 2782 */
19110c57 2783 function _registerCancelButton($addfieldsname){
2784 $this->_cancelButtons[]=$addfieldsname;
2785 }
6c1fd304 2786
acc9c3e0 2787 /**
2788 * Displays elements without HTML input tags.
2789 * This method is different to freeze() in that it makes sure no hidden
cc444336 2790 * elements are included in the form.
2791 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
acc9c3e0 2792 *
4af06dda 2793 * This function also removes all previously defined rules.
2794 *
6c1fd304
RT
2795 * @param string|array $elementList array or string of element(s) to be frozen
2796 * @return object|bool if element list is not empty then return error object, else true
acc9c3e0 2797 */
2798 function hardFreeze($elementList=null)
2799 {
2800 if (!isset($elementList)) {
2801 $this->_freezeAll = true;
2802 $elementList = array();
2803 } else {
2804 if (!is_array($elementList)) {
2805 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2806 }
2807 $elementList = array_flip($elementList);
2808 }
2809
2810 foreach (array_keys($this->_elements) as $key) {
2811 $name = $this->_elements[$key]->getName();
2812 if ($this->_freezeAll || isset($elementList[$name])) {
2813 $this->_elements[$key]->freeze();
2814 $this->_elements[$key]->setPersistantFreeze(false);
2815 unset($elementList[$name]);
4af06dda 2816
2817 // remove all rules
2818 $this->_rules[$name] = array();
2819 // if field is required, remove the rule
2820 $unset = array_search($name, $this->_required);
2821 if ($unset !== false) {
2822 unset($this->_required[$unset]);
2823 }
acc9c3e0 2824 }
2825 }
2826
2827 if (!empty($elementList)) {
66b3302d 2828 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);
acc9c3e0 2829 }
2830 return true;
4f51f48f 2831 }
6c1fd304 2832
4f51f48f 2833 /**
2834 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2835 *
2836 * This function also removes all previously defined rules of elements it freezes.
2837 *
6c1fd304
RT
2838 * @throws HTML_QuickForm_Error
2839 * @param array $elementList array or string of element(s) not to be frozen
2840 * @return bool returns true
4f51f48f 2841 */
2842 function hardFreezeAllVisibleExcept($elementList)
2843 {
2844 $elementList = array_flip($elementList);
2845 foreach (array_keys($this->_elements) as $key) {
2846 $name = $this->_elements[$key]->getName();
2847 $type = $this->_elements[$key]->getType();
56015454 2848
4f51f48f 2849 if ($type == 'hidden'){
2850 // leave hidden types as they are
2851 } elseif (!isset($elementList[$name])) {
2852 $this->_elements[$key]->freeze();
2853 $this->_elements[$key]->setPersistantFreeze(false);
2854
2855 // remove all rules
2856 $this->_rules[$name] = array();
2857 // if field is required, remove the rule
2858 $unset = array_search($name, $this->_required);
2859 if ($unset !== false) {
2860 unset($this->_required[$unset]);
2861 }
2862 }
2863 }
2864 return true;
2865 }
6c1fd304 2866
4f51f48f 2867 /**
2868 * Tells whether the form was already submitted
2869 *
2870 * This is useful since the _submitFiles and _submitValues arrays
2871 * may be completely empty after the trackSubmit value is removed.
2872 *
4f51f48f 2873 * @return bool
2874 */
2875 function isSubmitted()
2876 {
2877 return parent::isSubmitted() && (!$this->isFrozen());
2878 }
5079271b
DS
2879
2880 /**
2881 * Add the element name to the list of newly-created repeat elements
2882 * (So that elements that interpret 'no data submitted' as a valid state
2883 * can tell when they should get the default value instead).
2884 *
2885 * @param string $name the name of the new element
2886 */
2887 public function note_new_repeat($name) {
2888 $this->_newrepeats[] = $name;
2889 }
2890
2891 /**
2892 * Check if the element with the given name has just been added by clicking
2893 * on the 'Add repeating elements' button.
2894 *
2895 * @param string $name the name of the element being checked
2896 * @return bool true if the element is newly added
2897 */
2898 public function is_new_repeat($name) {
2899 return in_array($name, $this->_newrepeats);
2900 }
da6f8763 2901}
2902
2903/**
6c1fd304
RT
2904 * MoodleQuickForm renderer
2905 *
7f40a229 2906 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
da6f8763 2907 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
7f40a229 2908 *
da6f8763 2909 * Stylesheet is part of standard theme and should be automatically included.
2910 *
6c1fd304
RT
2911 * @package core_form
2912 * @copyright 2007 Jamie Pratt <me@jamiep.org>
ba21c9d4 2913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
da6f8763 2914 */
7f40a229 2915class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
da6f8763 2916
6c1fd304 2917 /** @var array Element template array */
da6f8763 2918 var $_elementTemplates;
6c1fd304 2919
49c53687 2920 /**
6c1fd304
RT
2921 * Template used when opening a hidden fieldset
2922 * (i.e. a fieldset that is opened when there is no header element)
2923 * @var string
2924 */
c02345e3 2925 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
6c1fd304
RT
2926
2927 /** @var string Header Template string */
19194f82 2928 var $_headerTemplate =
ac5e6ca4 2929 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
7f40a229 2930
6c1fd304 2931 /** @var string Template used when opening a fieldset */
d4e43871 2932 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
bc9ec4a6 2933
6c1fd304 2934 /** @var string Template used when closing a fieldset */
c02345e3 2935 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
42f248e6 2936
6c1fd304 2937 /** @var string Required Note template string */
7f40a229 2938 var $_requiredNoteTemplate =
6ba2c73d 2939 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
f2c0aba8 2940
a4b076d5
FM
2941 /**
2942 * Collapsible buttons string template.
2943 *
2944 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2945 * until the Javascript has been fully loaded.
2946 *
2947 * @var string
2948 */
f2c0aba8 2949 var $_collapseButtonsTemplate =
a4b076d5 2950 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
f2c0aba8 2951
a4067bfc
RK
2952 /**
2953 * Array whose keys are element names. If the key exists this is a advanced element
2954 *
2955 * @var array
2956 */
19194f82 2957 var $_advancedElements = array();
2958
a4067bfc
RK
2959 /**
2960 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2961 *
2962 * @var array
2963 */
2964 var $_collapsibleElements = array();
2965
f2c0aba8
FM
2966 /**
2967 * @var string Contains the collapsible buttons to add to the form.
2968 */
2969 var $_collapseButtons = '';
2970
6c1fd304
RT
2971 /**
2972 * Constructor
2973 */
1a0df553 2974 public function __construct() {
42f248e6 2975 // switch next two lines for ol li containers for form items.
63e4df60 2976 // $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>');
9aa022fe 2977 $this->_elementTemplates = array(
c62f0a39 2978 'default' => "\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{typeclass} {emptylabel} {class}" {aria-live} {groupname}><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>',
49c7f3a8 2979
c62f0a39 2980 'actionbuttons' => "\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{typeclass} {class}" {groupname}><div class="felement {typeclass}" data-fieldtype="{type}">{element}</div></div>',
95114b18 2981
c62f0a39 2982 'fieldset' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {class}<!-- BEGIN required --> required<!-- END required --> fitem_{typeclass} {emptylabel}" {groupname}><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>',
4f51f48f 2983
c62f0a39 2984 'static' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}" {groupname}><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>',
43914931 2985
e584e6ae 2986 'warning' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}">{element}</div>',
1ae1941e 2987
e584e6ae 2988 'nodisplay' => '');
da6f8763 2989
1a0df553
MG
2990 parent::__construct();
2991 }
2992
2993 /**
2994 * Old syntax of class constructor. Deprecated in PHP7.
2995 *
2996 * @deprecated since Moodle 3.1
2997 */
2998 public function MoodleQuickForm_Renderer() {
2999 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
3000 self::__construct();
da6f8763 3001 }
7f40a229 3002
ba21c9d4 3003 /**
6c1fd304
RT
3004 * Set element's as adavance element
3005 *
3006 * @param array $elements form elements which needs to be grouped as advance elements.
ba21c9d4 3007 */
19194f82 3008 function setAdvancedElements($elements){
3009 $this->_advancedElements = $elements;
3010 }
3011
a4067bfc
RK
3012 /**
3013 * Setting collapsible elements
3014 *
3015 * @param array $elements
3016 */
3017 function setCollapsibleElements($elements) {
3018 $this->_collapsibleElements = $elements;
3019 }
8dcca4aa 3020
19194f82 3021 /**
3022 * What to do when starting the form
3023 *
6c1fd304 3024 * @param MoodleQuickForm $form reference of the form
19194f82 3025 */
da6f8763 3026 function startForm(&$form){
00e8d08d 3027 global $PAGE;
9403060a 3028 $this->_reqHTML = $form->getReqHTML();
3029 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
19194f82 3030 $this->_advancedHTML = $form->getAdvancedHTML();
f2c0aba8 3031 $this->_collapseButtons = '';
a4067bfc 3032 $formid = $form->getAttribute('id');
da6f8763 3033 parent::startForm($form);
4f51f48f 3034 if ($form->isFrozen()){
1872cfcd 3035 $this->_formTemplate = "\n<div id=\"$formid\" class=\"mform frozen\">\n{collapsebtns}\n{content}\n</div>";
4f51f48f 3036 } else {
f2c0aba8 3037 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
4f51f48f 3038 $this->_hiddenHtml .= $form->_pageparams;
3039 }
3040
6b65e50b
TH
3041 if ($form->is_form_change_checker_enabled()) {
3042 $PAGE->requires->yui_module('moodle-core-formchangechecker',
3043 'M.core_formchangechecker.init',
3044 array(array(
dfd00217
P
3045 'formid' => $formid,
3046 'initialdirtystate' => $form->is_dirty(),
6b65e50b
TH
3047 ))
3048 );
3049 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
3050 }
d23edcf1 3051 if (!empty($this->_collapsibleElements)) {
f2c0aba8
FM
3052 if (count($this->_collapsibleElements) > 1) {
3053 $this->_collapseButtons = $this->_collapseButtonsTemplate;
f2c0aba8 3054 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
a4b076d5 3055 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
f2c0aba8 3056 }
a4067bfc
RK
3057 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
3058 }
8dcca4aa 3059 if (!empty($this->_advancedElements)){
37910f5e 3060 $PAGE->requires->js_call_amd('core_form/showadvanced', 'init', [$formid]);
ac5e6ca4 3061 }
da6f8763 3062 }
117bd748 3063
ba21c9d4 3064 /**
6c1fd304
RT
3065 * Create advance group of elements
3066 *
40d56513 3067 * @param MoodleQuickForm_group $group Passed by reference
6c1fd304
RT
3068 * @param bool $required if input is required field
3069 * @param string $error error message to display
ba21c9d4 3070 */
da6f8763 3071 function startGroup(&$group, $required, $error){
91bda4cd
DW
3072 global $OUTPUT;
3073
0f3f6fed
AF
3074 // Make sure the element has an id.
3075 $group->_generateId();
3076
40d56513
MN
3077 // Prepend 'fgroup_' to the ID we generated.
3078 $groupid = 'fgroup_' . $group->getAttribute('id');
3079
3080 // Update the ID.
3081 $group->updateAttributes(array('id' => $groupid));
d6f2ce14 3082 $advanced = isset($this->_advancedElements[$group->getName()]);
40d56513 3083
d6f2ce14 3084 $html = $OUTPUT->mform_element($group, $required, $advanced, $error, false);
91bda4cd
DW
3085 $fromtemplate = !empty($html);
3086 if (!$fromtemplate) {
3087 if (method_exists($group, 'getElementTemplateType')) {
3088 $html = $this->_elementTemplates[$group->getElementTemplateType()];
3089 } else {
3090 $html = $this->_elementTemplates['default'];
3091 }
7f40a229 3092
91bda4cd
DW
3093 if (isset($this->_advancedElements[$group->getName()])) {
3094 $html = str_replace(' {advanced}', ' advanced', $html);
3095 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
3096 } else {
3097 $html = str_replace(' {advanced}', '', $html);
3098 $html = str_replace('{advancedimg}', '', $html);
3099 }
3100 if (method_exists($group, 'getHelpButton')) {
3101 $html = str_replace('{help}', $group->getHelpButton(), $html);
3102 } else {
3103 $html = str_replace('{help}', '', $html);
3104 }
3105 $html = str_replace('{id}', $group->getAttribute('id'), $html);
3106 $html = str_replace('{name}', $group->getName(), $html);
c62f0a39 3107 $html = str_replace('{groupname}', 'data-groupname="'.$group->getName().'"', $html);
63e4df60
DW
3108 $html = str_replace('{typeclass}', 'fgroup', $html);
3109 $html = str_replace('{type}', 'group', $html);
91bda4cd
DW
3110 $html = str_replace('{class}', $group->getAttribute('class'), $html);
3111 $emptylabel = '';
3112 if ($group->getLabel() == '') {
3113 $emptylabel = 'femptylabel';
3114 }
3115 $html = str_replace('{emptylabel}', $emptylabel, $html);
da6f8763 3116 }
91bda4cd 3117 $this->_templates[$group->getName()] = $html;
da6f8763 3118 // Fix for bug in tableless quickforms that didn't allow you to stop a
3119 // fieldset before a group of elements.
3120 // if the element name indicates the end of a fieldset, close the fieldset
91bda4cd 3121 if (in_array($group->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
da6f8763 3122 $this->_html .= $this->_closeFieldsetTemplate;
3123 $this->_fieldsetsOpen--;
3124 }
91bda4cd
DW
3125 if (!$fromtemplate) {
3126 parent::startGroup($group, $required, $error);
3127 } else {
3128 $this->_html .= $html;
3129 }
da6f8763 3130 }
8dcca4aa 3131
ba21c9d4 3132 /**
6c1fd304
RT
3133 * Renders element
3134 *
3135 * @param HTML_QuickForm_element $element element
3136 * @param bool $required if input is required field
3137 * @param string $error error message to display
ba21c9d4 3138 */
da6f8763 3139 function renderElement(&$element, $required, $error){
91bda4cd
DW
3140 global $OUTPUT;
3141
820b41e3
TH
3142 // Make sure the element has an id.
3143 $element->_generateId();
d6f2ce14 3144 $advanced = isset($this->_advancedElements[$element->getName()]);
86aab05c 3145
d6f2ce14 3146 $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
91bda4cd
DW
3147 $fromtemplate = !empty($html);
3148 if (!$fromtemplate) {
3149 // Adding stuff to place holders in template
3150 // check if this is a group element first.
3151 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3152 // So it gets substitutions for *each* element.
3153 $html = $this->_groupElementTemplate;
e584e6ae 3154 } else if (method_exists($element, 'getElementTemplateType')) {
91bda4cd
DW
3155 $html = $this->_elementTemplates[$element->getElementTemplateType()];
3156 } else {
3157 $html = $this->_elementTemplates['default'];
3158 }
e584e6ae 3159 if (isset($this->_advancedElements[$element->getName()])) {
91bda4cd
DW
3160 $html = str_replace(' {advanced}', ' advanced', $html);
3161 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
3162 } else {
3163 $html = str_replace(' {advanced}', '', $html);
3164 $html = str_replace(' {aria-live}', '', $html);
3165 }
e584e6ae 3166 if (isset($this->_advancedElements[$element->getName()]) || $element->getName() == 'mform_showadvanced') {
91bda4cd
DW
3167 $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
3168 } else {
3169 $html = str_replace('{advancedimg}', '', $html);
3170 }
3171 $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
63e4df60
DW
3172 $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
3173 $html = str_replace('{type}', $element->getType(), $html);
91bda4cd 3174 $html = str_replace('{name}', $element->getName(), $html);
c62f0a39 3175 $html = str_replace('{groupname}', '', $html);
91bda4cd
DW
3176 $html = str_replace('{class}', $element->getAttribute('class'), $html);
3177 $emptylabel = '';
3178 if ($element->getLabel() == '') {
3179 $emptylabel = 'femptylabel';
3180 }
3181 $html = str_replace('{emptylabel}', $emptylabel, $html);
3182 if (method_exists($element, 'getHelpButton')) {
3183 $html = str_replace('{help}', $element->getHelpButton(), $html);
3184 } else {
3185 $html = str_replace('{help}', '', $html);
3186 }
19194f82 3187 } else {
91bda4cd
DW
3188 if ($this->_inGroup) {
3189 $this->_groupElementTemplate = $html;
3190 }
da6f8763 3191 }
906ebc4b 3192 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3193 $this->_groupElementTemplate = $html;
91bda4cd 3194 } else if (!isset($this->_templates[$element->getName()])) {
906ebc4b 3195 $this->_templates[$element->getName()] = $html;
172dd12c 3196 }
3197
91bda4cd
DW
3198 if (!$fromtemplate) {
3199 parent::renderElement($element, $required, $error);
63e4df60
DW
3200 } else {
3201 if (in_array($element->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
3202 $this->_html .= $this->_closeFieldsetTemplate;
3203 $this->_fieldsetsOpen--;
3204 }
91bda4cd
DW
3205 $this->_html .= $html;
3206 }
da6f8763 3207 }
19194f82 3208
ba21c9d4 3209 /**
6c1fd304
RT
3210 * Called when visiting a form, after processing all form elements
3211 * Adds required note, form attributes, validation javascript and form content.
3212 *
c7e3e61c 3213 * @global moodle_page $PAGE
6c1fd304 3214 * @param moodleform $form Passed by reference
ba21c9d4 3215 */
bb40325e 3216 function finishForm(&$form){
c7e3e61c 3217 global $PAGE;
4f51f48f 3218 if ($form->isFrozen()){
3219 $this->_hiddenHtml = '';
3220 }
bb40325e 3221 parent::finishForm($form);
f2c0aba8 3222 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
c7e3e61c
SH
3223 if (!$form->isFrozen()) {
3224 $args = $form->getLockOptionObject();
3225 if (count($args[1]) > 0) {
63d5c4ac 3226 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
c7e3e61c 3227 }
bb40325e 3228 }
3229 }
19194f82 3230 /**
3231 * Called when visiting a header element
3232 *
6c1fd304 3233 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
c7e3e61c 3234 * @global moodle_page $PAGE
19194f82 3235 */
c28bf5c9 3236 function renderHeader(&$header) {
3237 global $PAGE;
9262d2d3 3238
d23edcf1 3239 $header->_generateId();
19194f82 3240 $name = $header->getName();
3241
d23edcf1 3242 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
19194f82 3243 if (is_null($header->_text)) {
3244 $header_html = '';
3245