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