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