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