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