MDL-21695 disabling useless debugging
[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 :
28 * form defintion is used for both printing of form and processing and should be the same
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 *
33 *
ba21c9d4 34 * @copyright Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 * @package moodlecore
da6f8763 37 */
38
ba21c9d4 39/** setup.php icludes our hacked pear libs first */
da6f8763 40require_once 'HTML/QuickForm.php';
41require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
42require_once 'HTML/QuickForm/Renderer/Tableless.php';
43
a83ad946 44require_once $CFG->libdir.'/filelib.php';
f6ac3e0a 45require_once $CFG->libdir.'/uploadlib.php'; // TODO: remove
49292f8c 46
832e13f1 47define('EDITOR_UNLIMITED_FILES', -1);
48
a23f0aaf 49/**
50 * Callback called when PEAR throws an error
51 *
52 * @param PEAR_Error $error
53 */
54function pear_handle_error($error){
55 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
56 echo '<br /> <strong>Backtrace </strong>:';
57 print_object($error->backtrace);
58}
59
66491cf1 60if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
a23f0aaf 61 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
864cc1de 62}
63
ba21c9d4 64/**
117bd748 65 *
ba21c9d4 66 * @staticvar bool $done
ba21c9d4 67 */
8e7cebb0 68function form_init_date_js() {
cf615522 69 global $PAGE;
8e7cebb0 70 static $done = false;
71 if (!$done) {
f44b10ed
PS
72 $PAGE->requires->yui2_lib('calendar');
73 $PAGE->requires->yui2_lib('container');
cf615522 74 $PAGE->requires->js_function_call('init_date_selectors',
0a933ae6 75 array(get_string('firstdayofweek', 'langconfig')));
8e7cebb0 76 $done = true;
77 }
78}
f07b9627 79
05f5c40c 80/**
da1320da 81 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
6073a598 82 * use this class you should write a class definition which extends this class or a more specific
da1320da 83 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
84 *
85 * You will write your own definition() method which performs the form set up.
ba21c9d4 86 *
87 * @package moodlecore
88 * @copyright Jamie Pratt <me@jamiep.org>
89 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
05f5c40c 90 */
afd63fe5 91abstract class moodleform {
ba21c9d4 92 /** @var string */
172dd12c 93 protected $_formname; // form name
3c7656b4 94 /**
95 * quickform object definition
96 *
ba21c9d4 97 * @var object MoodleQuickForm
3c7656b4 98 */
172dd12c 99 protected $_form;
3c7656b4 100 /**
101 * globals workaround
102 *
103 * @var array
104 */
172dd12c 105 protected $_customdata;
4f51f48f 106 /**
107 * definition_after_data executed flag
ba21c9d4 108 * @var object definition_finalized
4f51f48f 109 */
172dd12c 110 protected $_definition_finalized = false;
ebd3c7ac 111
da1320da 112 /**
113 * The constructor function calls the abstract function definition() and it will then
114 * process and clean and attempt to validate incoming data.
115 *
116 * It will call your custom validate method to validate data and will also check any rules
117 * you have specified in definition using addRule
118 *
119 * The name of the form (id attribute of the form) is automatically generated depending on
120 * the name you gave the class extending moodleform. You should call your class something
121 * like
122 *
4f51f48f 123 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
124 * current url. If a moodle_url object then outputs params as hidden variables.
da1320da 125 * @param array $customdata if your form defintion method needs access to data such as $course
126 * $cm, etc. to construct the form definition then pass it in this array. You can
127 * use globals for somethings.
128 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
129 * be merged and used as incoming data to the form.
130 * @param string $target target frame for form submission. You will rarely use this. Don't use
131 * it if you don't need to as the target attribute is deprecated in xhtml
132 * strict.
133 * @param mixed $attributes you can pass a string of html attributes here or an array.
ba21c9d4 134 * @param bool $editable
135 * @return object moodleform
da1320da 136 */
4f51f48f 137 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
a23f0aaf 138 if (empty($action)){
139 $action = strip_querystring(qualified_me());
140 }
f07b9627 141
72f46d11 142 $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
7f40a229 143 $this->_customdata = $customdata;
66491cf1 144 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
4f51f48f 145 if (!$editable){
146 $this->_form->hardFreeze();
147 }
7f40a229 148
149 $this->definition();
150
151 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
d18e0fe6 152 $this->_form->setType('sesskey', PARAM_RAW);
7f40a229 153 $this->_form->setDefault('sesskey', sesskey());
5bc97c98 154 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
d18e0fe6 155 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
5bc97c98 156 $this->_form->setDefault('_qf__'.$this->_formname, 1);
157 $this->_form->_setDefaultRuleMessages();
7f40a229 158
159 // we have to know all input types before processing submission ;-)
160 $this->_process_submission($method);
7f40a229 161 }
05f5c40c 162
2c412890 163 /**
da1320da 164 * To autofocus on first form element or first element with error.
2c412890 165 *
8dec2253 166 * @param string $name if this is set then the focus is forced to a field with this name
167 *
2c412890 168 * @return string javascript to select form element with first error or
da1320da 169 * first element if no errors. Use this as a parameter
170 * when calling print_header
2c412890 171 */
46f3921e 172 function focus($name=NULL) {
9403060a 173 $form =& $this->_form;
46f3921e 174 $elkeys = array_keys($form->_elementIndex);
175 $error = false;
9403060a 176 if (isset($form->_errors) && 0 != count($form->_errors)){
177 $errorkeys = array_keys($form->_errors);
178 $elkeys = array_intersect($elkeys, $errorkeys);
46f3921e 179 $error = true;
2c412890 180 }
46f3921e 181
182 if ($error or empty($name)) {
183 $names = array();
184 while (empty($names) and !empty($elkeys)) {
185 $el = array_shift($elkeys);
186 $names = $form->_getElNamesRecursive($el);
187 }
188 if (!empty($names)) {
189 $name = array_shift($names);
190 }
8dec2253 191 }
46f3921e 192
193 $focus = '';
194 if (!empty($name)) {
195 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
9403060a 196 }
46f3921e 197
9403060a 198 return $focus;
199 }
7f40a229 200
05f5c40c 201 /**
202 * Internal method. Alters submitted data to be suitable for quickforms processing.
203 * Must be called when the form is fully set up.
ba21c9d4 204 *
205 * @param string $method
05f5c40c 206 */
7f40a229 207 function _process_submission($method) {
208 $submission = array();
209 if ($method == 'post') {
210 if (!empty($_POST)) {
211 $submission = $_POST;
212 }
213 } else {
214 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
215 }
216
217 // following trick is needed to enable proper sesskey checks when using GET forms
5bc97c98 218 // the _qf__.$this->_formname serves as a marker that form was actually submitted
219 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
7f40a229 220 if (!confirm_sesskey()) {
c3f9ee10 221 print_error('invalidsesskey');
7f40a229 222 }
05f5c40c 223 $files = $_FILES;
7f40a229 224 } else {
225 $submission = array();
05f5c40c 226 $files = array();
7f40a229 227 }
228
05f5c40c 229 $this->_form->updateSubmission($submission, $files);
7f40a229 230 }
231
05f5c40c 232 /**
4287fc0d 233 * Internal method. Validates all old-style uploaded files.
117bd748 234 *
ba21c9d4 235 * @global object
236 * @global object
237 * @param array $files
238 * @return bool|array Success or an array of errors
05f5c40c 239 */
89489cfe 240 function _validate_files(&$files) {
172dd12c 241 global $CFG, $COURSE;
242
89489cfe 243 $files = array();
244
49292f8c 245 if (empty($_FILES)) {
246 // we do not need to do any checks because no files were submitted
89489cfe 247 // note: server side rules do not work for files - use custom verification in validate() instead
49292f8c 248 return true;
249 }
49292f8c 250
172dd12c 251 $errors = array();
252 $filenames = array();
49292f8c 253
254 // now check that we really want each file
255 foreach ($_FILES as $elname=>$file) {
172dd12c 256 $required = $this->_form->isElementRequired($elname);
89489cfe 257
172dd12c 258 if ($file['error'] == 4 and $file['size'] == 0) {
259 if ($required) {
260 $errors[$elname] = get_string('required');
49292f8c 261 }
172dd12c 262 unset($_FILES[$elname]);
263 continue;
264 }
265
a83ad946 266 if (!empty($file['error'])) {
267 $errors[$elname] = file_get_upload_error($file['error']);
172dd12c 268 unset($_FILES[$elname]);
269 continue;
270 }
271
272 if (!is_uploaded_file($file['tmp_name'])) {
273 // TODO: improve error message
274 $errors[$elname] = get_string('error');
275 unset($_FILES[$elname]);
276 continue;
277 }
278
279 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
280 // hmm, this file was not requested
281 unset($_FILES[$elname]);
282 continue;
283 }
284
285/*
286 // TODO: rethink the file scanning
287 if ($CFG->runclamonupload) {
288 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
289 $errors[$elname] = $_FILES[$elname]['uploadlog'];
290 unset($_FILES[$elname]);
291 continue;
292 }
293 }
294*/
295 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
296 if ($filename === '') {
297 // TODO: improve error message - wrong chars
298 $errors[$elname] = get_string('error');
299 unset($_FILES[$elname]);
300 continue;
49292f8c 301 }
172dd12c 302 if (in_array($filename, $filenames)) {
303 // TODO: improve error message - duplicate name
304 $errors[$elname] = get_string('error');
305 unset($_FILES[$elname]);
306 continue;
307 }
308 $filenames[] = $filename;
309 $_FILES[$elname]['name'] = $filename;
310
311 $files[$elname] = $_FILES[$elname]['tmp_name'];
49292f8c 312 }
313
314 // return errors if found
172dd12c 315 if (count($errors) == 0){
49292f8c 316 return true;
89489cfe 317
49292f8c 318 } else {
89489cfe 319 $files = array();
49292f8c 320 return $errors;
321 }
322 }
323
05f5c40c 324 /**
da1320da 325 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
326 * form definition (new entry form); this function is used to load in data where values
327 * already exist and data is being edited (edit entry form).
05f5c40c 328 *
294ce987 329 * note: $slashed param removed
330 *
05f5c40c 331 * @param mixed $default_values object or array of default values
332 * @param bool $slased true if magic quotes applied to data values
333 */
294ce987 334 function set_data($default_values) {
7f40a229 335 if (is_object($default_values)) {
336 $default_values = (array)$default_values;
337 }
294ce987 338 $this->_form->setDefaults($default_values);
7f40a229 339 }
340
ba21c9d4 341 /**
342 * @param bool $um
343 */
feaf5d06 344 function set_upload_manager($um=false) {
172dd12c 345 debugging('Not used anymore, please fix code!');
c80a13c7 346 }
347
05f5c40c 348 /**
349 * Check that form was submitted. Does not check validity of submitted data.
350 *
351 * @return bool true if form properly submitted
352 */
7f40a229 353 function is_submitted() {
354 return $this->_form->isSubmitted();
355 }
356
ba21c9d4 357 /**
358 * @staticvar bool $nosubmit
359 */
a23f0aaf 360 function no_submit_button_pressed(){
361 static $nosubmit = null; // one check is enough
362 if (!is_null($nosubmit)){
363 return $nosubmit;
364 }
365 $mform =& $this->_form;
366 $nosubmit = false;
f07b9627 367 if (!$this->is_submitted()){
368 return false;
369 }
a23f0aaf 370 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
371 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
372 $nosubmit = true;
373 break;
374 }
375 }
376 return $nosubmit;
377 }
378
379
05f5c40c 380 /**
381 * Check that form data is valid.
6bba6dbb 382 * You should almost always use this, rather than {@see validate_defined_fields}
05f5c40c 383 *
ba21c9d4 384 * @staticvar bool $validated
05f5c40c 385 * @return bool true if form data valid
386 */
7f40a229 387 function is_validated() {
4f51f48f 388 //finalize the form definition before any processing
389 if (!$this->_definition_finalized) {
390 $this->_definition_finalized = true;
391 $this->definition_after_data();
392 }
393
6bba6dbb 394 return $this->validate_defined_fields();
395 }
396
397 /**
398 * Validate the form.
399 *
400 * You almost always want to call {@see is_validated} instead of this
401 * because it calls {@see definition_after_data} first, before validating the form,
402 * which is what you want in 99% of cases.
403 *
404 * This is provided as a separate function for those special cases where
405 * you want the form validated before definition_after_data is called
406 * for example, to selectively add new elements depending on a no_submit_button press,
407 * but only when the form is valid when the no_submit_button is pressed,
408 *
409 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
410 * is NOT to validate the form when a no submit button has been pressed.
411 * pass true here to override this behaviour
412 *
413 * @return bool true if form data valid
414 */
415 function validate_defined_fields($validateonnosubmit=false) {
416 static $validated = null; // one validation is enough
417 $mform =& $this->_form;
418 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
9aa022fe 419 return false;
420 } elseif ($validated === null) {
3ba2c187 421 $internal_val = $mform->validate();
89489cfe 422
423 $files = array();
424 $file_val = $this->_validate_files($files);
425 if ($file_val !== true) {
426 if (!empty($file_val)) {
427 foreach ($file_val as $element=>$msg) {
428 $mform->setElementError($element, $msg);
429 }
430 }
431 $file_val = false;
432 }
433
4287fc0d 434 $data = $mform->exportValues();
89489cfe 435 $moodle_val = $this->validation($data, $files);
a78890d5 436 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
437 // non-empty array means errors
438 foreach ($moodle_val as $element=>$msg) {
439 $mform->setElementError($element, $msg);
7f40a229 440 }
a78890d5 441 $moodle_val = false;
442
443 } else {
444 // anything else means validation ok
445 $moodle_val = true;
7f40a229 446 }
89489cfe 447
49292f8c 448 $validated = ($internal_val and $moodle_val and $file_val);
7f40a229 449 }
9aa022fe 450 return $validated;
7f40a229 451 }
452
19110c57 453 /**
454 * Return true if a cancel button has been pressed resulting in the form being submitted.
455 *
456 * @return boolean true if a cancel button has been pressed
457 */
458 function is_cancelled(){
459 $mform =& $this->_form;
a23f0aaf 460 if ($mform->isSubmitted()){
461 foreach ($mform->_cancelButtons as $cancelbutton){
462 if (optional_param($cancelbutton, 0, PARAM_RAW)){
463 return true;
464 }
19110c57 465 }
466 }
467 return false;
468 }
469
05f5c40c 470 /**
da1320da 471 * Return submitted data if properly submitted or returns NULL if validation fails or
472 * if there is no submitted data.
172dd12c 473 *
294ce987 474 * note: $slashed param removed
05f5c40c 475 *
05f5c40c 476 * @return object submitted data; NULL if not valid or not submitted
477 */
294ce987 478 function get_data() {
19110c57 479 $mform =& $this->_form;
3ba2c187 480
7f40a229 481 if ($this->is_submitted() and $this->is_validated()) {
294ce987 482 $data = $mform->exportValues();
5bc97c98 483 unset($data['sesskey']); // we do not need to return sesskey
484 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
7f40a229 485 if (empty($data)) {
486 return NULL;
487 } else {
488 return (object)$data;
489 }
490 } else {
491 return NULL;
492 }
493 }
494
4f51f48f 495 /**
496 * Return submitted data without validation or NULL if there is no submitted data.
294ce987 497 * note: $slashed param removed
4f51f48f 498 *
4f51f48f 499 * @return object submitted data; NULL if not submitted
500 */
294ce987 501 function get_submitted_data() {
4f51f48f 502 $mform =& $this->_form;
503
504 if ($this->is_submitted()) {
294ce987 505 $data = $mform->exportValues();
4f51f48f 506 unset($data['sesskey']); // we do not need to return sesskey
507 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
508 if (empty($data)) {
509 return NULL;
510 } else {
511 return (object)$data;
512 }
513 } else {
514 return NULL;
515 }
516 }
517
05f5c40c 518 /**
519 * Save verified uploaded files into directory. Upload process can be customised from definition()
172dd12c 520 * NOTE: please use save_stored_file() or save_file()
ba21c9d4 521 *
522 * @return bool Always false
05f5c40c 523 */
49292f8c 524 function save_files($destination) {
172dd12c 525 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
49292f8c 526 return false;
527 }
2b63df96 528
feaf5d06 529 /**
172dd12c 530 * Returns name of uploaded file.
ba21c9d4 531 *
532 * @global object
172dd12c 533 * @param string $elname, first element if null
feaf5d06 534 * @return mixed false in case of failure, string if ok
535 */
172dd12c 536 function get_new_filename($elname=null) {
4287fc0d 537 global $USER;
538
172dd12c 539 if (!$this->is_submitted() or !$this->is_validated()) {
540 return false;
541 }
542
543 if (is_null($elname)) {
544 if (empty($_FILES)) {
545 return false;
546 }
547 reset($_FILES);
548 $elname = key($_FILES);
549 }
4287fc0d 550
551 if (empty($elname)) {
552 return false;
553 }
554
555 $element = $this->_form->getElement($elname);
556
557 if ($element instanceof MoodleQuickForm_filepicker) {
558 $values = $this->_form->exportValues($elname);
559 if (empty($values[$elname])) {
560 return false;
561 }
562 $draftid = $values[$elname];
563 $fs = get_file_storage();
564 $context = get_context_instance(CONTEXT_USER, $USER->id);
565 if (!$files = $fs->get_area_files($context->id, 'user_draft', $draftid, 'id DESC', false)) {
566 return false;
567 }
568 $file = reset($files);
569 return $file->get_filename();
570 }
571
172dd12c 572 if (!isset($_FILES[$elname])) {
573 return false;
574 }
575
576 return $_FILES[$elname]['name'];
feaf5d06 577 }
578
b6b1d1ca 579 /**
172dd12c 580 * Save file to standard filesystem
ba21c9d4 581 *
582 * @global object
172dd12c 583 * @param string $elname name of element
584 * @param string $pathname full path name of file
585 * @param bool $override override file if exists
586 * @return bool success
b6b1d1ca 587 */
172dd12c 588 function save_file($elname, $pathname, $override=false) {
4287fc0d 589 global $USER;
b6b1d1ca 590
4287fc0d 591 if (!$this->is_submitted() or !$this->is_validated()) {
b6b1d1ca 592 return false;
593 }
594
172dd12c 595 if (file_exists($pathname)) {
596 if ($override) {
597 if (!@unlink($pathname)) {
598 return false;
599 }
600 } else {
601 return false;
602 }
603 }
4287fc0d 604
605 $element = $this->_form->getElement($elname);
606
607 if ($element instanceof MoodleQuickForm_filepicker) {
608 $values = $this->_form->exportValues($elname);
609 if (empty($values[$elname])) {
610 return false;
611 }
612 $draftid = $values[$elname];
613 $fs = get_file_storage();
614 $context = get_context_instance(CONTEXT_USER, $USER->id);
615 if (!$files = $fs->get_area_files($context->id, 'user_draft', $draftid, 'id DESC', false)) {
616 return false;
617 }
618 $file = reset($files);
619
620 return $file->copy_content_to($pathname);
621
622 } else if (isset($_FILES[$elname])) {
623 return copy($_FILES[$elname]['tmp_name'], $pathname);
172dd12c 624 }
625
4287fc0d 626 return false;
172dd12c 627 }
628
629 /**
630 * Save file to local filesystem pool
ba21c9d4 631 *
632 * @global object
172dd12c 633 * @param string $elname name of element
924ddb15 634 * @param int $newcontextid
635 * @param string $newfilearea
636 * @param string $newfilepath
637 * @param string $newfilename - use specified filename, if not specified name of uploaded file used
49583e9e 638 * @param bool $overwrite - overwrite file if exists
924ddb15 639 * @param int $newuserid - new userid if required
172dd12c 640 * @return mixed stored_file object or false if error; may throw exception if duplicate found
641 */
f6172562 642 function save_stored_file($elname, $newcontextid, $newfilearea, $newitemid, $newfilepath='/',
49583e9e 643 $newfilename=null, $overwrite=false, $newuserid=null) {
924ddb15 644 global $USER;
645
172dd12c 646 if (!$this->is_submitted() or !$this->is_validated()) {
89489cfe 647 return false;
172dd12c 648 }
89489cfe 649
924ddb15 650 if (empty($newuserid)) {
651 $newuserid = $USER->id;
89489cfe 652 }
b6b1d1ca 653
4287fc0d 654 $element = $this->_form->getElement($elname);
655 $fs = get_file_storage();
172dd12c 656
4287fc0d 657 if ($element instanceof MoodleQuickForm_filepicker) {
658 $values = $this->_form->exportValues($elname);
659 if (empty($values[$elname])) {
660 return false;
661 }
662 $draftid = $values[$elname];
663 $context = get_context_instance(CONTEXT_USER, $USER->id);
664 if (!$files = $fs->get_area_files($context->id, 'user_draft', $draftid, 'id DESC', false)) {
665 return false;
666 }
667 $file = reset($files);
668 if (is_null($newfilename)) {
669 $newfilename = $file->get_filename();
670 }
172dd12c 671
4287fc0d 672 if ($overwrite) {
673 if ($oldfile = $fs->get_file($newcontextid, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
674 if (!$oldfile->delete()) {
675 return false;
676 }
924ddb15 677 }
678 }
679
4287fc0d 680 $file_record = array('contextid'=>$newcontextid, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
681 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
682 return $fs->create_file_from_storedfile($file_record, $file);
924ddb15 683
4287fc0d 684 } else if (isset($_FILES[$elname])) {
685 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
172dd12c 686
4287fc0d 687 if ($overwrite) {
688 if ($oldfile = $fs->get_file($newcontextid, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
689 if (!$oldfile->delete()) {
690 return false;
691 }
692 }
924ddb15 693 }
4287fc0d 694
695 $file_record = array('contextid'=>$newcontextid, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
696 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
697 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
924ddb15 698 }
699
700 return false;
172dd12c 701 }
702
703 /**
704 * Get content of uploaded file.
ba21c9d4 705 *
706 * @global object
172dd12c 707 * @param $element name of file upload element
708 * @return mixed false in case of failure, string if ok
709 */
710 function get_file_content($elname) {
4287fc0d 711 global $USER;
712
172dd12c 713 if (!$this->is_submitted() or !$this->is_validated()) {
714 return false;
715 }
716
4287fc0d 717 $element = $this->_form->getElement($elname);
718
719 if ($element instanceof MoodleQuickForm_filepicker) {
720 $values = $this->_form->exportValues($elname);
721 if (empty($values[$elname])) {
722 return false;
723 }
724 $draftid = $values[$elname];
725 $fs = get_file_storage();
726 $context = get_context_instance(CONTEXT_USER, $USER->id);
727 if (!$files = $fs->get_area_files($context->id, 'user_draft', $draftid, 'id DESC', false)) {
728 return false;
729 }
730 $file = reset($files);
731
732 return $file->get_content();
733
734 } else if (isset($_FILES[$elname])) {
735 return file_get_contents($_FILES[$elname]['tmp_name']);
b6b1d1ca 736 }
172dd12c 737
4287fc0d 738 return false;
b6b1d1ca 739 }
740
05f5c40c 741 /**
742 * Print html form.
743 */
7f40a229 744 function display() {
4f51f48f 745 //finalize the form definition if not yet done
746 if (!$this->_definition_finalized) {
747 $this->_definition_finalized = true;
748 $this->definition_after_data();
749 }
7f40a229 750 $this->_form->display();
751 }
752
49292f8c 753 /**
05f5c40c 754 * Abstract method - always override!
49292f8c 755 *
756 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
757 */
afd63fe5 758 protected abstract function definition();
2c412890 759
c08ac016 760 /**
05f5c40c 761 * Dummy stub method - override if you need to setup the form depending on current
beac4717 762 * values. This method is called after definition(), data submission and set_data().
05f5c40c 763 * All form setup that is dependent on form values should go in here.
c08ac016 764 */
765 function definition_after_data(){
c08ac016 766 }
7f40a229 767
05f5c40c 768 /**
769 * Dummy stub method - override if you needed to perform some extra validation.
770 * If there are errors return array of errors ("fieldname"=>"error message"),
771 * otherwise true if ok.
38f394b2 772 *
89489cfe 773 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
774 *
05f5c40c 775 * @param array $data array of ("fieldname"=>value) of submitted data
89489cfe 776 * @param array $files array of uploaded files "element_name"=>tmp_file_path
a78890d5 777 * @return array of "element_name"=>"error_description" if there are errors,
778 * or an empty array if everything is OK (true allowed for backwards compatibility too).
05f5c40c 779 */
89489cfe 780 function validation($data, $files) {
13ccb7bd 781 return array();
7f40a229 782 }
ebd3c7ac 783
616b549a 784 /**
785 * Method to add a repeating group of elements to a form.
786 *
787 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
788 * @param integer $repeats no of times to repeat elements initially
789 * @param array $options Array of options to apply to elements. Array keys are element names.
790 * This is an array of arrays. The second sets of keys are the option types
791 * for the elements :
792 * 'default' - default value is value
793 * 'type' - PARAM_* constant is value
794 * 'helpbutton' - helpbutton params array is value
795 * 'disabledif' - last three moodleform::disabledIf()
796 * params are value as an array
797 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
798 * @param string $addfieldsname name for button to add more fields
799 * @param int $addfieldsno how many fields to add at a time
271ffe3f 800 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
6f3b54c8 801 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
a23f0aaf 802 * @return int no of repeats of element in this page
616b549a 803 */
6f3b54c8 804 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
805 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
271ffe3f 806 if ($addstring===null){
807 $addstring = get_string('addfields', 'form', $addfieldsno);
808 } else {
809 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
810 }
ebd3c7ac 811 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
812 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
813 if (!empty($addfields)){
814 $repeats += $addfieldsno;
815 }
ebd3c7ac 816 $mform =& $this->_form;
a23f0aaf 817 $mform->registerNoSubmitButton($addfieldsname);
ebd3c7ac 818 $mform->addElement('hidden', $repeathiddenname, $repeats);
d18e0fe6 819 $mform->setType($repeathiddenname, PARAM_INT);
ebd3c7ac 820 //value not to be overridden by submitted value
821 $mform->setConstants(array($repeathiddenname=>$repeats));
414f7bee 822 $namecloned = array();
823 for ($i = 0; $i < $repeats; $i++) {
ebd3c7ac 824 foreach ($elementobjs as $elementobj){
985f0ddd 825 $elementclone = fullclone($elementobj);
7b41a4a9 826 $name = $elementclone->getName();
414f7bee 827 $namecloned[] = $name;
828 if (!empty($name)) {
86aab05c 829 $elementclone->setName($name."[$i]");
830 }
414f7bee 831 if (is_a($elementclone, 'HTML_QuickForm_header')) {
832 $value = $elementclone->_text;
271ffe3f 833 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
834
835 } else {
836 $value=$elementclone->getLabel();
837 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
ebd3c7ac 838
839 }
7b41a4a9 840
ebd3c7ac 841 $mform->addElement($elementclone);
842 }
843 }
844 for ($i=0; $i<$repeats; $i++) {
845 foreach ($options as $elementname => $elementoptions){
846 $pos=strpos($elementname, '[');
847 if ($pos!==FALSE){
848 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
849 $realelementname .= substr($elementname, $pos+1);
850 }else {
851 $realelementname = $elementname."[$i]";
852 }
853 foreach ($elementoptions as $option => $params){
854
855 switch ($option){
856 case 'default' :
857 $mform->setDefault($realelementname, $params);
858 break;
ebd3c7ac 859 case 'helpbutton' :
860 $mform->setHelpButton($realelementname, $params);
861 break;
862 case 'disabledif' :
414f7bee 863 foreach ($namecloned as $num => $name){
864 if ($params[0] == $name){
865 $params[0] = $params[0]."[$i]";
866 break;
867 }
868 }
9aa022fe 869 $params = array_merge(array($realelementname), $params);
870 call_user_func_array(array(&$mform, 'disabledIf'), $params);
871 break;
872 case 'rule' :
873 if (is_string($params)){
874 $params = array(null, $params, null, 'client');
875 }
876 $params = array_merge(array($realelementname), $params);
877 call_user_func_array(array(&$mform, 'addRule'), $params);
ebd3c7ac 878 break;
879
880 }
881 }
882 }
883 }
271ffe3f 884 $mform->addElement('submit', $addfieldsname, $addstring);
a23f0aaf 885
6f3b54c8 886 if (!$addbuttoninside) {
887 $mform->closeHeaderBefore($addfieldsname);
888 }
ebd3c7ac 889
19194f82 890 return $repeats;
ebd3c7ac 891 }
6073a598 892
893 /**
894 * Adds a link/button that controls the checked state of a group of checkboxes.
ba21c9d4 895 *
896 * @global object
6073a598 897 * @param int $groupid The id of the group of advcheckboxes this element controls
ba21c9d4 898 * @param string $buttontext The text of the link. Defaults to "select all/none"
6073a598 899 * @param array $attributes associative array of HTML attributes
900 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
901 */
172dd12c 902 function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
6073a598 903 global $CFG;
904 if (empty($text)) {
905 $text = get_string('selectallornone', 'form');
906 }
907
908 $mform = $this->_form;
909 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
910
911 if ($select_value == 0 || is_null($select_value)) {
912 $new_select_value = 1;
913 } else {
914 $new_select_value = 0;
915 }
916
917 $mform->addElement('hidden', "checkbox_controller$groupid");
d18e0fe6 918 $mform->setType("checkbox_controller$groupid", PARAM_INT);
6073a598 919 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
172dd12c 920
6073a598 921 // Locate all checkboxes for this group and set their value, IF the optional param was given
922 if (!is_null($select_value)) {
923 foreach ($this->_form->_elements as $element) {
924 if ($element->getAttribute('class') == "checkboxgroup$groupid") {
925 $mform->setConstants(array($element->getAttribute('name') => $select_value));
926 }
927 }
928 }
929
930 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
931 $mform->registerNoSubmitButton($checkbox_controller_name);
172dd12c 932
6073a598 933 // Prepare Javascript for submit element
934 $js = "\n//<![CDATA[\n";
935 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
936 $js .= <<<EOS
937function html_quickform_toggle_checkboxes(group) {
938 var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
939 var newvalue = false;
940 var global = eval('html_quickform_checkboxgroup' + group + ';');
941 if (global == 1) {
172dd12c 942 eval('html_quickform_checkboxgroup' + group + ' = 0;');
6073a598 943 newvalue = '';
944 } else {
172dd12c 945 eval('html_quickform_checkboxgroup' + group + ' = 1;');
6073a598 946 newvalue = 'checked';
947 }
948
949 for (i = 0; i < checkboxes.length; i++) {
172dd12c 950 checkboxes[i].checked = newvalue;
6073a598 951 }
952}
953EOS;
954 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
955 }
956 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
172dd12c 957
6073a598 958 $js .= "//]]>\n";
172dd12c 959
6073a598 960 require_once("$CFG->libdir/form/submitlink.php");
961 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
962 $submitlink->_js = $js;
963 $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
172dd12c 964 $mform->addElement($submitlink);
6073a598 965 $mform->setDefault($checkbox_controller_name, $text);
966 }
967
a23f0aaf 968 /**
1d284fbd 969 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
a23f0aaf 970 * if you don't want a cancel button in your form. If you have a cancel button make sure you
971 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
beac4717 972 * get data with get_data().
a23f0aaf 973 *
974 * @param boolean $cancel whether to show cancel button, default true
a23f0aaf 975 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
976 */
1d284fbd 977 function add_action_buttons($cancel = true, $submitlabel=null){
a23f0aaf 978 if (is_null($submitlabel)){
979 $submitlabel = get_string('savechanges');
980 }
981 $mform =& $this->_form;
1d284fbd 982 if ($cancel){
983 //when two elements we need a group
a23f0aaf 984 $buttonarray=array();
985 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1d284fbd 986 $buttonarray[] = &$mform->createElement('cancel');
a23f0aaf 987 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
4f51f48f 988 $mform->closeHeaderBefore('buttonar');
a23f0aaf 989 } else {
990 //no group needed
991 $mform->addElement('submit', 'submitbutton', $submitlabel);
4f51f48f 992 $mform->closeHeaderBefore('submitbutton');
a23f0aaf 993 }
994 }
7f40a229 995}
996
da1320da 997/**
998 * You never extend this class directly. The class methods of this class are available from
6073a598 999 * the private $this->_form property on moodleform and its children. You generally only
da1320da 1000 * call methods on this class from within abstract methods that you override on moodleform such
1001 * as definition and definition_after_data
1002 *
ba21c9d4 1003 * @package moodlecore
1004 * @copyright Jamie Pratt <me@jamiep.org>
1005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
da1320da 1006 */
7f40a229 1007class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
ba21c9d4 1008 /** @var array */
7f40a229 1009 var $_types = array();
50ef8eb9 1010 var $_dependencies = array();
19110c57 1011 /**
1012 * Array of buttons that if pressed do not result in the processing of the form.
1013 *
1014 * @var array
1015 */
1016 var $_noSubmitButtons=array();
1017 /**
1018 * Array of buttons that if pressed do not result in the processing of the form.
1019 *
1020 * @var array
1021 */
1022 var $_cancelButtons=array();
7f40a229 1023
19194f82 1024 /**
1025 * Array whose keys are element names. If the key exists this is a advanced element
1026 *
1027 * @var array
1028 */
1029 var $_advancedElements = array();
1030
1031 /**
1032 * Whether to display advanced elements (on page load)
1033 *
1034 * @var boolean
1035 */
1036 var $_showAdvanced = null;
1037
f07b9627 1038 /**
1039 * The form name is derrived from the class name of the wrapper minus the trailing form
1040 * It is a name with words joined by underscores whereas the id attribute is words joined by
1041 * underscores.
1042 *
1043 * @var unknown_type
1044 */
1045 var $_formName = '';
43914931 1046
4f51f48f 1047 /**
1048 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
1049 *
1050 * @var string
1051 */
1052 var $_pageparams = '';
1053
da6f8763 1054 /**
1055 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
ba21c9d4 1056 *
1057 * @global object
1058 * @staticvar int $formcounter
da6f8763 1059 * @param string $formName Form's name.
1060 * @param string $method (optional)Form's method defaults to 'POST'
4f51f48f 1061 * @param mixed $action (optional)Form's action - string or moodle_url
da6f8763 1062 * @param string $target (optional)Form's target defaults to none
1063 * @param mixed $attributes (optional)Extra attributes for <form> tag
da6f8763 1064 * @access public
1065 */
7f40a229 1066 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
96705c33 1067 global $CFG, $OUTPUT;
dcf6d93c 1068
271ffe3f 1069 static $formcounter = 1;
7f40a229 1070
da6f8763 1071 HTML_Common::HTML_Common($attributes);
da6f8763 1072 $target = empty($target) ? array() : array('target' => $target);
f07b9627 1073 $this->_formName = $formName;
4f51f48f 1074 if (is_a($action, 'moodle_url')){
6ea66ff3 1075 $this->_pageparams = html_writer::input_hidden_params($action);
eb788065 1076 $action = $action->out_omit_querystring();
4f51f48f 1077 } else {
1078 $this->_pageparams = '';
1079 }
da6f8763 1080 //no 'name' atttribute for form in xhtml strict :
1327f08e 1081 $attributes = array('action'=>$action, 'method'=>$method,
1082 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
271ffe3f 1083 $formcounter++;
da6f8763 1084 $this->updateAttributes($attributes);
da6f8763 1085
7f40a229 1086 //this is custom stuff for Moodle :
da6f8763 1087 $oldclass= $this->getAttribute('class');
1088 if (!empty($oldclass)){
1089 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1090 }else {
80f962df 1091 $this->updateAttributes(array('class'=>'mform'));
da6f8763 1092 }
b5d0cafc
PS
1093 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1094 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1095 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
5bff0855 1096 //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
19194f82 1097 }
1098
a23f0aaf 1099 /**
1100 * Use this method to indicate an element in a form is an advanced field. If items in a form
1101 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1102 * form so the user can decide whether to display advanced form controls.
1103 *
1104 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1105 *
1106 * @param string $elementName group or element name (not the element name of something inside a group).
1107 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
1108 */
1109 function setAdvanced($elementName, $advanced=true){
1110 if ($advanced){
1111 $this->_advancedElements[$elementName]='';
1112 } elseif (isset($this->_advancedElements[$elementName])) {
1113 unset($this->_advancedElements[$elementName]);
1114 }
1115 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1116 $this->setShowAdvanced();
1117 $this->registerNoSubmitButton('mform_showadvanced');
1118
1119 $this->addElement('hidden', 'mform_showadvanced_last');
d18e0fe6 1120 $this->setType('mform_showadvanced_last', PARAM_INT);
a23f0aaf 1121 }
1122 }
1123 /**
1124 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1125 * display advanced elements in the form until 'Show Advanced' is pressed.
1126 *
1127 * You can get the last state of the form and possibly save it for this user by using
1128 * value 'mform_showadvanced_last' in submitted data.
1129 *
1130 * @param boolean $showadvancedNow
1131 */
1132 function setShowAdvanced($showadvancedNow = null){
1133 if ($showadvancedNow === null){
1134 if ($this->_showAdvanced !== null){
1135 return;
1136 } else { //if setShowAdvanced is called without any preference
1137 //make the default to not show advanced elements.
f07b9627 1138 $showadvancedNow = get_user_preferences(
1139 moodle_strtolower($this->_formName.'_showadvanced', 0));
a23f0aaf 1140 }
a23f0aaf 1141 }
1142 //value of hidden element
1143 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1144 //value of button
1145 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1146 //toggle if button pressed or else stay the same
1147 if ($hiddenLast == -1) {
1148 $next = $showadvancedNow;
1149 } elseif ($buttonPressed) { //toggle on button press
1150 $next = !$hiddenLast;
1151 } else {
1152 $next = $hiddenLast;
1153 }
1154 $this->_showAdvanced = $next;
f07b9627 1155 if ($showadvancedNow != $next){
1156 set_user_preference($this->_formName.'_showadvanced', $next);
1157 }
a23f0aaf 1158 $this->setConstants(array('mform_showadvanced_last'=>$next));
19194f82 1159 }
1160 function getShowAdvanced(){
1161 return $this->_showAdvanced;
1162 }
1163
19194f82 1164
1165 /**
1166 * Accepts a renderer
1167 *
ba21c9d4 1168 * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
19194f82 1169 * @access public
1170 * @return void
1171 */
46f3921e 1172 function accept(&$renderer) {
19194f82 1173 if (method_exists($renderer, 'setAdvancedElements')){
1174 //check for visible fieldsets where all elements are advanced
1175 //and mark these headers as advanced as well.
1176 //And mark all elements in a advanced header as advanced
1177 $stopFields = $renderer->getStopFieldSetElements();
1178 $lastHeader = null;
1179 $lastHeaderAdvanced = false;
1180 $anyAdvanced = false;
1181 foreach (array_keys($this->_elements) as $elementIndex){
1182 $element =& $this->_elements[$elementIndex];
46f3921e 1183
1184 // if closing header and any contained element was advanced then mark it as advanced
19194f82 1185 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
46f3921e 1186 if ($anyAdvanced && !is_null($lastHeader)){
19194f82 1187 $this->setAdvanced($lastHeader->getName());
1188 }
1189 $lastHeaderAdvanced = false;
46f3921e 1190 unset($lastHeader);
1191 $lastHeader = null;
19194f82 1192 } elseif ($lastHeaderAdvanced) {
1193 $this->setAdvanced($element->getName());
1194 }
46f3921e 1195
19194f82 1196 if ($element->getType()=='header'){
1197 $lastHeader =& $element;
1198 $anyAdvanced = false;
1199 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1200 } elseif (isset($this->_advancedElements[$element->getName()])){
1201 $anyAdvanced = true;
1202 }
1203 }
46f3921e 1204 // the last header may not be closed yet...
1205 if ($anyAdvanced && !is_null($lastHeader)){
1206 $this->setAdvanced($lastHeader->getName());
1207 }
19194f82 1208 $renderer->setAdvancedElements($this->_advancedElements);
19194f82 1209
19194f82 1210 }
1211 parent::accept($renderer);
1212 }
1213
ba21c9d4 1214 /**
1215 * @param string $elementName
1216 */
19194f82 1217 function closeHeaderBefore($elementName){
1218 $renderer =& $this->defaultRenderer();
1219 $renderer->addStopFieldsetElements($elementName);
da6f8763 1220 }
bb40325e 1221
da1320da 1222 /**
1223 * Should be used for all elements of a form except for select, radio and checkboxes which
1224 * clean their own data.
1225 *
1226 * @param string $elementname
1227 * @param integer $paramtype use the constants PARAM_*.
1228 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
1229 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
1230 * It will strip all html tags. But will still let tags for multilang support
1231 * through.
1232 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
1233 * html editor. Data from the editor is later cleaned before display using
1234 * format_text() function. PARAM_RAW can also be used for data that is validated
1235 * by some other way or printed by p() or s().
1236 * * PARAM_INT should be used for integers.
1237 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
1238 * form actions.
1239 */
7f40a229 1240 function setType($elementname, $paramtype) {
1241 $this->_types[$elementname] = $paramtype;
1242 }
49292f8c 1243
da1320da 1244 /**
1245 * See description of setType above. This can be used to set several types at once.
1246 *
1247 * @param array $paramtypes
1248 */
c56f1826 1249 function setTypes($paramtypes) {
1250 $this->_types = $paramtypes + $this->_types;
1251 }
49292f8c 1252
ba21c9d4 1253 /**
1254 * @param array $submission
1255 * @param array $files
1256 */
49292f8c 1257 function updateSubmission($submission, $files) {
1258 $this->_flagSubmitted = false;
1259
7f40a229 1260 if (empty($submission)) {
1261 $this->_submitValues = array();
7f40a229 1262 } else {
1263 foreach ($submission as $key=>$s) {
1264 if (array_key_exists($key, $this->_types)) {
1265 $submission[$key] = clean_param($s, $this->_types[$key]);
1266 }
1267 }
294ce987 1268 $this->_submitValues = $submission;
7f40a229 1269 $this->_flagSubmitted = true;
1270 }
1271
49292f8c 1272 if (empty($files)) {
1273 $this->_submitFiles = array();
1274 } else {
49292f8c 1275 $this->_submitFiles = $files;
1276 $this->_flagSubmitted = true;
1277 }
1278
2c412890 1279 // need to tell all elements that they need to update their value attribute.
1280 foreach (array_keys($this->_elements) as $key) {
1281 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1282 }
7f40a229 1283 }
1284
ba21c9d4 1285 /**
1286 * @return string
1287 */
da6f8763 1288 function getReqHTML(){
1289 return $this->_reqHTML;
1290 }
117bd748 1291
ba21c9d4 1292 /**
1293 * @return string
1294 */
19194f82 1295 function getAdvancedHTML(){
1296 return $this->_advancedHTML;
1297 }
1298
7f40a229 1299 /**
da1320da 1300 * Initializes a default form value. Used to specify the default for a new entry where
beac4717 1301 * no data is loaded in using moodleform::set_data()
7f40a229 1302 *
294ce987 1303 * note: $slashed param removed
1304 *
7f40a229 1305 * @param string $elementname element name
1306 * @param mixed $values values for that element name
7f40a229 1307 * @access public
1308 * @return void
1309 */
294ce987 1310 function setDefault($elementName, $defaultValue){
1311 $this->setDefaults(array($elementName=>$defaultValue));
7f40a229 1312 } // end func setDefault
da6f8763 1313 /**
c56f1826 1314 * Add an array of buttons to the form
7f40a229 1315 * @param array $buttons An associative array representing help button to attach to
da6f8763 1316 * to the form. keys of array correspond to names of elements in form.
ba21c9d4 1317 * @param bool $suppresscheck
1318 * @param string $function
da6f8763 1319 * @access public
1320 */
d4fe14d3 1321 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
7f40a229 1322
c56f1826 1323 foreach ($buttons as $elementname => $button){
d4fe14d3 1324 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
da6f8763 1325 }
1326 }
c56f1826 1327 /**
da1320da 1328 * Add a single button.
c56f1826 1329 *
1330 * @param string $elementname name of the element to add the item to
ba21c9d4 1331 * @param array $button arguments to pass to function $function
1332 * @param boolean $suppresscheck whether to throw an error if the element
c56f1826 1333 * doesn't exist.
d4fe14d3 1334 * @param string $function - function to generate html from the arguments in $button
ba21c9d4 1335 * @param string $function
c56f1826 1336 */
4bcc5118 1337 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
642816a6 1338 global $OUTPUT;
b65d2720 1339 //TODO: obsolete this function completely
4bcc5118 1340 if ($function !== 'helpbutton') {
b65d2720 1341 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
4bcc5118
PS
1342 }
1343
1344 $buttonargs = (array)$buttonargs;
1345
1346 if (array_key_exists($elementname, $this->_elementIndex)) {
c56f1826 1347 //_elements has a numeric index, this code accesses the elements by name
4bcc5118 1348 $element = $this->_elements[$this->_elementIndex[$elementname]];
642816a6 1349
4bcc5118
PS
1350 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1351 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1352 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1353 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1354
1355 $element->_helpbutton = $OUTPUT->help_icon($page, $text, $module, $linktext);
642816a6 1356
4bcc5118 1357 } else if (!$suppresscheck) {
c56f1826 1358 print_error('nonexistentformelements', 'form', '', $elementname);
2c412890 1359 }
c56f1826 1360 }
7f40a229 1361
53a78cef
PS
1362 /**
1363 * Add a help button to element,
1364 * only one button per element is allowed.
1365 *
1366 * @param string $elementname name of the element to add the item to
1367 * @param string $identifier
1368 * @param string $title
1369 * @param string $component
1370 * @param string $linktext
1371 * @return void
1372 */
1373 function addHelpButton($elementname, $identifier, $title, $component = 'moodle', $linktext = '') {
1374 if (array_key_exists($elementname, $this->_elementIndex)) {
1375 $element->_helpbutton = $OUTPUT->help_icon($identifier, $title, $component, $linktext);
1376 } else if (!$suppresscheck) {
1377 debugging(get_string('nonexistentformelements', 'form', $elementname));
1378 }
1379 }
1380
cc444336 1381 /**
1382 * Set constant value not overriden by _POST or _GET
1383 * note: this does not work for complex names with [] :-(
ba21c9d4 1384 *
cc444336 1385 * @param string $elname name of element
1386 * @param mixed $value
1387 * @return void
1388 */
1389 function setConstant($elname, $value) {
1390 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1391 $element =& $this->getElement($elname);
1392 $element->onQuickFormEvent('updateValue', null, $this);
1393 }
1394
ba21c9d4 1395 /**
1396 * @param string $elementList
1397 */
294ce987 1398 function exportValues($elementList = null){
0ffb4cc7 1399 $unfiltered = array();
1400 if (null === $elementList) {
1401 // iterate over all elements, calling their exportValue() methods
98af2d1d 1402 $emptyarray = array();
0ffb4cc7 1403 foreach (array_keys($this->_elements) as $key) {
1404 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
98af2d1d 1405 $value = $this->_elements[$key]->exportValue($emptyarray, true);
0ffb4cc7 1406 } else {
1407 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1408 }
1409
1410 if (is_array($value)) {
1411 // This shit throws a bogus warning in PHP 4.3.x
1412 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1413 }
1414 }
1415 } else {
1416 if (!is_array($elementList)) {
1417 $elementList = array_map('trim', explode(',', $elementList));
1418 }
1419 foreach ($elementList as $elementName) {
1420 $value = $this->exportValue($elementName);
1421 if (PEAR::isError($value)) {
1422 return $value;
1423 }
4287fc0d 1424 //oh, stock QuickFOrm was returning array of arrays!
1425 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
0ffb4cc7 1426 }
1427 }
7f40a229 1428
294ce987 1429 return $unfiltered;
da6f8763 1430 }
f07b9627 1431 /**
1432 * Adds a validation rule for the given field
1433 *
1434 * If the element is in fact a group, it will be considered as a whole.
1435 * To validate grouped elements as separated entities,
1436 * use addGroupRule instead of addRule.
1437 *
1438 * @param string $element Form element name
1439 * @param string $message Message to display for invalid data
1440 * @param string $type Rule type, use getRegisteredRules() to get types
1441 * @param string $format (optional)Required for extra rule data
1442 * @param string $validation (optional)Where to perform validation: "server", "client"
1443 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1444 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
f07b9627 1445 * @access public
f07b9627 1446 */
1447 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1448 {
1449 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1450 if ($validation == 'client') {
1451 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1452 }
1453
1454 } // end func addRule
1455 /**
1456 * Adds a validation rule for the given group of elements
1457 *
1458 * Only groups with a name can be assigned a validation rule
1459 * Use addGroupRule when you need to validate elements inside the group.
1460 * Use addRule if you need to validate the group as a whole. In this case,
1461 * the same rule will be applied to all elements in the group.
1462 * Use addRule if you need to validate the group against a function.
1463 *
1464 * @param string $group Form group name
1465 * @param mixed $arg1 Array for multiple elements or error message string for one element
1466 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1467 * @param string $format (optional)Required for extra rule data
1468 * @param int $howmany (optional)How many valid elements should be in the group
1469 * @param string $validation (optional)Where to perform validation: "server", "client"
1470 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
f07b9627 1471 * @access public
f07b9627 1472 */
1473 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1474 {
1475 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1476 if (is_array($arg1)) {
3a298174 1477 foreach ($arg1 as $rules) {
f07b9627 1478 foreach ($rules as $rule) {
1479 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1480
1481 if ('client' == $validation) {
1482 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1483 }
1484 }
1485 }
1486 } elseif (is_string($arg1)) {
1487
1488 if ($validation == 'client') {
3a298174 1489 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
f07b9627 1490 }
1491 }
1492 } // end func addGroupRule
1493
1494 // }}}
5bc97c98 1495 /**
1496 * Returns the client side validation script
1497 *
1498 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1499 * and slightly modified to run rules per-element
1500 * Needed to override this because of an error with client side validation of grouped elements.
1501 *
1502 * @access public
1503 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1504 */
1505 function getValidationScript()
1506 {
1507 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1508 return '';
1509 }
1510
1511 include_once('HTML/QuickForm/RuleRegistry.php');
1512 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1513 $test = array();
1514 $js_escape = array(
1515 "\r" => '\r',
1516 "\n" => '\n',
1517 "\t" => '\t',
1518 "'" => "\\'",
1519 '"' => '\"',
1520 '\\' => '\\\\'
1521 );
1522
1523 foreach ($this->_rules as $elementName => $rules) {
1524 foreach ($rules as $rule) {
1525 if ('client' == $rule['validation']) {
da1320da 1526 unset($element); //TODO: find out how to properly initialize it
5bc97c98 1527
1528 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1529 $rule['message'] = strtr($rule['message'], $js_escape);
1530
1531 if (isset($rule['group'])) {
1532 $group =& $this->getElement($rule['group']);
1533 // No JavaScript validation for frozen elements
1534 if ($group->isFrozen()) {
1535 continue 2;
1536 }
1537 $elements =& $group->getElements();
1538 foreach (array_keys($elements) as $key) {
1539 if ($elementName == $group->getElementName($key)) {
1540 $element =& $elements[$key];
1541 break;
1542 }
1543 }
1544 } elseif ($dependent) {
1545 $element = array();
1546 $element[] =& $this->getElement($elementName);
3a298174 1547 foreach ($rule['dependent'] as $elName) {
5bc97c98 1548 $element[] =& $this->getElement($elName);
1549 }
1550 } else {
1551 $element =& $this->getElement($elementName);
1552 }
1553 // No JavaScript validation for frozen elements
1554 if (is_object($element) && $element->isFrozen()) {
1555 continue 2;
1556 } elseif (is_array($element)) {
1557 foreach (array_keys($element) as $key) {
1558 if ($element[$key]->isFrozen()) {
1559 continue 3;
1560 }
1561 }
1562 }
1563 // Fix for bug displaying errors for elements in a group
1564 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1565 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1566 $test[$elementName][1]=$element;
1567 //end of fix
1568 }
1569 }
1570 }
7c77033f 1571
1572 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1573 // the form, and then that form field gets corrupted by the code that follows.
1574 unset($element);
1575
5bc97c98 1576 $js = '
1577<script type="text/javascript">
1578//<![CDATA[
1cbb09f1 1579
1580var skipClientValidation = false;
1581
5bc97c98 1582function qf_errorHandler(element, _qfMsg) {
1583 div = element.parentNode;
1584 if (_qfMsg != \'\') {
e35c9eeb 1585 var errorSpan = document.getElementById(\'id_error_\'+element.name);
e7004d05 1586 if (!errorSpan) {
1587 errorSpan = document.createElement("span");
e35c9eeb 1588 errorSpan.id = \'id_error_\'+element.name;
1589 errorSpan.className = "error";
fed13a5e 1590 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
5bc97c98 1591 }
fed13a5e 1592
e7004d05 1593 while (errorSpan.firstChild) {
1594 errorSpan.removeChild(errorSpan.firstChild);
5bc97c98 1595 }
2c412890 1596
e7004d05 1597 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
e35c9eeb 1598 errorSpan.appendChild(document.createElement("br"));
5bc97c98 1599
1600 if (div.className.substr(div.className.length - 6, 6) != " error"
1601 && div.className != "error") {
1602 div.className += " error";
1603 }
1604
1605 return false;
1606 } else {
e35c9eeb 1607 var errorSpan = document.getElementById(\'id_error_\'+element.name);
e7004d05 1608 if (errorSpan) {
1609 errorSpan.parentNode.removeChild(errorSpan);
5bc97c98 1610 }
1611
1612 if (div.className.substr(div.className.length - 6, 6) == " error") {
1613 div.className = div.className.substr(0, div.className.length - 6);
1614 } else if (div.className == "error") {
1615 div.className = "";
1616 }
1617
1618 return true;
1619 }
1620}';
1621 $validateJS = '';
1622 foreach ($test as $elementName => $jsandelement) {
1623 // Fix for bug displaying errors for elements in a group
1624 //unset($element);
1625 list($jsArr,$element)=$jsandelement;
1626 //end of fix
1627 $js .= '
f07b9627 1628function validate_' . $this->_formName . '_' . $elementName . '(element) {
5bc97c98 1629 var value = \'\';
1630 var errFlag = new Array();
1631 var _qfGroups = {};
1632 var _qfMsg = \'\';
1633 var frm = element.parentNode;
cd350b53 1634 while (frm && frm.nodeName.toUpperCase() != "FORM") {
5bc97c98 1635 frm = frm.parentNode;
1636 }
1637' . join("\n", $jsArr) . '
1638 return qf_errorHandler(element, _qfMsg);
1639}
1640';
1641 $validateJS .= '
2ef7c374 1642 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;
1643 if (!ret && !first_focus) {
1644 first_focus = true;
1645 frm.elements[\''.$elementName.'\'].focus();
1646 }
1647';
4f51f48f 1648
5bc97c98 1649 // Fix for bug displaying errors for elements in a group
1650 //unset($element);
1651 //$element =& $this->getElement($elementName);
1652 //end of fix
f07b9627 1653 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
5bc97c98 1654 $onBlur = $element->getAttribute('onBlur');
1655 $onChange = $element->getAttribute('onChange');
1656 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1657 'onChange' => $onChange . $valFunc));
1658 }
e7004d05 1659// do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
5bc97c98 1660 $js .= '
f07b9627 1661function validate_' . $this->_formName . '(frm) {
1cbb09f1 1662 if (skipClientValidation) {
1663 return true;
1664 }
5bc97c98 1665 var ret = true;
4f51f48f 1666
0befbdfd 1667 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2ef7c374 1668 var first_focus = false;
5bc97c98 1669' . $validateJS . ';
1670 return ret;
1671}
1672//]]>
1673</script>';
1674 return $js;
1675 } // end func getValidationScript
1676 function _setDefaultRuleMessages(){
1677 foreach ($this->_rules as $field => $rulesarr){
1678 foreach ($rulesarr as $key => $rule){
1679 if ($rule['message']===null){
1680 $a=new object();
1681 $a->format=$rule['format'];
1682 $str=get_string('err_'.$rule['type'], 'form', $a);
1683 if (strpos($str, '[[')!==0){
1684 $this->_rules[$field][$key]['message']=$str;
2c412890 1685 }
5bc97c98 1686 }
1687 }
1688 }
1689 }
bb40325e 1690
ba21c9d4 1691 /**
1692 * @return string
1693 */
d01a38cb 1694 function getLockOptionEndScript(){
dd07bbac 1695
1696 $iname = $this->getAttribute('id').'items';
f4ba7e1a 1697 $js = '<script type="text/javascript">'."\n";
5e87b920 1698 $js .= '//<![CDATA['."\n";
dd07bbac 1699 $js .= "var $iname = Array();\n";
1700
1701 foreach ($this->_dependencies as $dependentOn => $conditions){
1702 $js .= "{$iname}['$dependentOn'] = Array();\n";
1703 foreach ($conditions as $condition=>$values) {
1704 $js .= "{$iname}['$dependentOn']['$condition'] = Array();\n";
1705 foreach ($values as $value=>$dependents) {
1706 $js .= "{$iname}['$dependentOn']['$condition']['$value'] = Array();\n";
1707 $i = 0;
1708 foreach ($dependents as $dependent) {
1709 $elements = $this->_getElNamesRecursive($dependent);
46f3921e 1710 if (empty($elements)) {
1711 // probably element inside of some group
1712 $elements = array($dependent);
1713 }
dd07bbac 1714 foreach($elements as $element) {
1715 if ($element == $dependentOn) {
1716 continue;
1717 }
1718 $js .= "{$iname}['$dependentOn']['$condition']['$value'][$i]='$element';\n";
1719 $i++;
1720 }
11f260f4 1721 }
1722 }
50ef8eb9 1723 }
dd07bbac 1724 }
d01a38cb 1725 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
5e87b920 1726 $js .='//]]>'."\n";
50ef8eb9 1727 $js .='</script>'."\n";
1728 return $js;
bb40325e 1729 }
d01a38cb 1730
ba21c9d4 1731 /**
1732 * @param mixed $element
1733 * @return array
1734 */
46f3921e 1735 function _getElNamesRecursive($element) {
1736 if (is_string($element)) {
4f51f48f 1737 if (!$this->elementExists($element)) {
1738 return array();
1739 }
46f3921e 1740 $element = $this->getElement($element);
d01a38cb 1741 }
46f3921e 1742
1743 if (is_a($element, 'HTML_QuickForm_group')) {
1744 $elsInGroup = $element->getElements();
9403060a 1745 $elNames = array();
d01a38cb 1746 foreach ($elsInGroup as $elInGroup){
e850ec48 1747 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1748 // not sure if this would work - groups nested in groups
1749 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1750 } else {
1751 $elNames[] = $element->getElementName($elInGroup->getName());
1752 }
d01a38cb 1753 }
46f3921e 1754
1755 } else if (is_a($element, 'HTML_QuickForm_header')) {
1756 return array();
1757
1758 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1759 return array();
1760
1761 } else if (method_exists($element, 'getPrivateName')) {
1762 return array($element->getPrivateName());
1763
1764 } else {
1765 $elNames = array($element->getName());
d01a38cb 1766 }
d01a38cb 1767
46f3921e 1768 return $elNames;
50ef8eb9 1769 }
46f3921e 1770
6e372b25 1771 /**
1772 * Adds a dependency for $elementName which will be disabled if $condition is met.
9403060a 1773 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1774 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
31a6c06c 1775 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1776 * of the $dependentOn element is $condition (such as equal) to $value.
6e372b25 1777 *
1778 * @param string $elementName the name of the element which will be disabled
1779 * @param string $dependentOn the name of the element whose state will be checked for
1780 * condition
1781 * @param string $condition the condition to check
19110c57 1782 * @param mixed $value used in conjunction with condition.
6e372b25 1783 */
dd07bbac 1784 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1785 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1786 $this->_dependencies[$dependentOn] = array();
1787 }
1788 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1789 $this->_dependencies[$dependentOn][$condition] = array();
1790 }
1791 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1792 $this->_dependencies[$dependentOn][$condition][$value] = array();
1793 }
1794 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
bb40325e 1795 }
dd07bbac 1796
a23f0aaf 1797 function registerNoSubmitButton($buttonname){
1798 $this->_noSubmitButtons[]=$buttonname;
1799 }
dd07bbac 1800
ba21c9d4 1801 /**
1802 * @param string $buttonname
1803 * @return mixed
1804 */
a23f0aaf 1805 function isNoSubmitButton($buttonname){
1806 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
19110c57 1807 }
dd07bbac 1808
ba21c9d4 1809 /**
1810 * @param string $buttonname
1811 */
19110c57 1812 function _registerCancelButton($addfieldsname){
1813 $this->_cancelButtons[]=$addfieldsname;
1814 }
acc9c3e0 1815 /**
1816 * Displays elements without HTML input tags.
1817 * This method is different to freeze() in that it makes sure no hidden
cc444336 1818 * elements are included in the form.
1819 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
acc9c3e0 1820 *
4af06dda 1821 * This function also removes all previously defined rules.
1822 *
acc9c3e0 1823 * @param mixed $elementList array or string of element(s) to be frozen
acc9c3e0 1824 * @access public
acc9c3e0 1825 */
1826 function hardFreeze($elementList=null)
1827 {
1828 if (!isset($elementList)) {
1829 $this->_freezeAll = true;
1830 $elementList = array();
1831 } else {
1832 if (!is_array($elementList)) {
1833 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1834 }
1835 $elementList = array_flip($elementList);
1836 }
1837
1838 foreach (array_keys($this->_elements) as $key) {
1839 $name = $this->_elements[$key]->getName();
1840 if ($this->_freezeAll || isset($elementList[$name])) {
1841 $this->_elements[$key]->freeze();
1842 $this->_elements[$key]->setPersistantFreeze(false);
1843 unset($elementList[$name]);
4af06dda 1844
1845 // remove all rules
1846 $this->_rules[$name] = array();
1847 // if field is required, remove the rule
1848 $unset = array_search($name, $this->_required);
1849 if ($unset !== false) {
1850 unset($this->_required[$unset]);
1851 }
acc9c3e0 1852 }
1853 }
1854
1855 if (!empty($elementList)) {
1856 return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
1857 }
1858 return true;
4f51f48f 1859 }
1860 /**
1861 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
1862 *
1863 * This function also removes all previously defined rules of elements it freezes.
1864 *
ba21c9d4 1865 * throws HTML_QuickForm_Error
1866 *
4f51f48f 1867 * @param array $elementList array or string of element(s) not to be frozen
4f51f48f 1868 * @access public
4f51f48f 1869 */
1870 function hardFreezeAllVisibleExcept($elementList)
1871 {
1872 $elementList = array_flip($elementList);
1873 foreach (array_keys($this->_elements) as $key) {
1874 $name = $this->_elements[$key]->getName();
1875 $type = $this->_elements[$key]->getType();
56015454 1876
4f51f48f 1877 if ($type == 'hidden'){
1878 // leave hidden types as they are
1879 } elseif (!isset($elementList[$name])) {
1880 $this->_elements[$key]->freeze();
1881 $this->_elements[$key]->setPersistantFreeze(false);
1882
1883 // remove all rules
1884 $this->_rules[$name] = array();
1885 // if field is required, remove the rule
1886 $unset = array_search($name, $this->_required);
1887 if ($unset !== false) {
1888 unset($this->_required[$unset]);
1889 }
1890 }
1891 }
1892 return true;
1893 }
1894 /**
1895 * Tells whether the form was already submitted
1896 *
1897 * This is useful since the _submitFiles and _submitValues arrays
1898 * may be completely empty after the trackSubmit value is removed.
1899 *
1900 * @access public
1901 * @return bool
1902 */
1903 function isSubmitted()
1904 {
1905 return parent::isSubmitted() && (!$this->isFrozen());
1906 }
da6f8763 1907}
1908
e24b7f85 1909
da6f8763 1910/**
7f40a229 1911 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
da6f8763 1912 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
7f40a229 1913 *
da6f8763 1914 * Stylesheet is part of standard theme and should be automatically included.
1915 *
ba21c9d4 1916 * @package moodlecore
1917 * @copyright Jamie Pratt <me@jamiep.org>
1918 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
da6f8763 1919 */
7f40a229 1920class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
da6f8763 1921
1922 /**
1923 * Element template array
1924 * @var array
1925 * @access private
1926 */
1927 var $_elementTemplates;
49c53687 1928 /**
1929 * Template used when opening a hidden fieldset
1930 * (i.e. a fieldset that is opened when there is no header element)
1931 * @var string
1932 * @access private
1933 */
c02345e3 1934 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
19194f82 1935 /**
1936 * Header Template string
1937 * @var string
1938 * @access private
1939 */
1940 var $_headerTemplate =
c02345e3 1941 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
7f40a229 1942
49c53687 1943 /**
bc9ec4a6 1944 * Template used when opening a fieldset
1945 * @var string
1946 * @access private
1947 */
1948 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
1949
1950 /**
49c53687 1951 * Template used when closing a fieldset
1952 * @var string
1953 * @access private
1954 */
c02345e3 1955 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
42f248e6 1956
49c53687 1957 /**
1958 * Required Note template string
1959 * @var string
1960 * @access private
1961 */
7f40a229 1962 var $_requiredNoteTemplate =
6ba2c73d 1963 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
7f40a229 1964
19194f82 1965 var $_advancedElements = array();
1966
1967 /**
1968 * Whether to display advanced elements (on page load)
1969 *
1970 * @var integer 1 means show 0 means hide
1971 */
1972 var $_showAdvanced;
1973
7f40a229 1974 function MoodleQuickForm_Renderer(){
42f248e6 1975 // switch next two lines for ol li containers for form items.
49c7f3a8 1976 // $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 1977 $this->_elementTemplates = array(
f8b9ac74 1978 'default'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
49c7f3a8 1979
f9f9be73 1980 'fieldset'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></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 1981
f9f9be73 1982 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></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 1983
1ae1941e 1984'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
1985
4f51f48f 1986 'nodisplay'=>'');
da6f8763 1987
1988 parent::HTML_QuickForm_Renderer_Tableless();
1989 }
7f40a229 1990
ba21c9d4 1991 /**
1992 * @param array $elements
1993 */
19194f82 1994 function setAdvancedElements($elements){
1995 $this->_advancedElements = $elements;
1996 }
1997
1998 /**
1999 * What to do when starting the form
2000 *
ba21c9d4 2001 * @param object $form MoodleQuickForm
19194f82 2002 */
da6f8763 2003 function startForm(&$form){
9403060a 2004 $this->_reqHTML = $form->getReqHTML();
2005 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
19194f82 2006 $this->_advancedHTML = $form->getAdvancedHTML();
2007 $this->_showAdvanced = $form->getShowAdvanced();
da6f8763 2008 parent::startForm($form);
4f51f48f 2009 if ($form->isFrozen()){
2010 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2011 } else {
0524b1d9 2012 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
4f51f48f 2013 $this->_hiddenHtml .= $form->_pageparams;
2014 }
2015
2016
da6f8763 2017 }
117bd748 2018
ba21c9d4 2019 /**
2020 * @param object $group Passed by reference
2021 * @param mixed $required
2022 * @param mixed $error
2023 */
da6f8763 2024 function startGroup(&$group, $required, $error){
2025 if (method_exists($group, 'getElementTemplateType')){
e249661f 2026 $html = $this->_elementTemplates[$group->getElementTemplateType()];
da6f8763 2027 }else{
2028 $html = $this->_elementTemplates['default'];
7f40a229 2029
da6f8763 2030 }
19194f82 2031 if ($this->_showAdvanced){
2032 $advclass = ' advanced';
2033 } else {
2034 $advclass = ' advanced hide';
2035 }
2036 if (isset($this->_advancedElements[$group->getName()])){
2037 $html =str_replace(' {advanced}', $advclass, $html);
2038 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2039 } else {
2040 $html =str_replace(' {advanced}', '', $html);
2041 $html =str_replace('{advancedimg}', '', $html);
2042 }
da6f8763 2043 if (method_exists($group, 'getHelpButton')){
2044 $html =str_replace('{help}', $group->getHelpButton(), $html);
2045 }else{
2046 $html =str_replace('{help}', '', $html);
da6f8763 2047 }
e7004d05 2048 $html =str_replace('{name}', $group->getName(), $html);
49c53687 2049 $html =str_replace('{type}', 'fgroup', $html);
7f40a229 2050
da6f8763 2051 $this->_templates[$group->getName()]=$html;
2052 // Fix for bug in tableless quickforms that didn't allow you to stop a
2053 // fieldset before a group of elements.
2054 // if the element name indicates the end of a fieldset, close the fieldset
2055 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2056 && $this->_fieldsetsOpen > 0
2057 ) {
2058 $this->_html .= $this->_closeFieldsetTemplate;
2059 $this->_fieldsetsOpen--;
2060 }
2061 parent::startGroup($group, $required, $error);
2062 }
ba21c9d4 2063 /**
2064 * @param object $element
2065 * @param mixed $required
2066 * @param mixed $error
2067 */
da6f8763 2068 function renderElement(&$element, $required, $error){
172dd12c 2069 //manipulate id of all elements before rendering
86aab05c 2070 if (!is_null($element->getAttribute('id'))) {
2071 $id = $element->getAttribute('id');
2072 } else {
2073 $id = $element->getName();
2074 }
2075 //strip qf_ prefix and replace '[' with '_' and strip ']'
2076 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
2077 if (strpos($id, 'id_') !== 0){
2078 $element->updateAttributes(array('id'=>'id_'.$id));
2079 }
2080
2081 //adding stuff to place holders in template
172dd12c 2082 //check if this is a group element first
906ebc4b 2083 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
3493eb15 2084 // so it gets substitutions for *each* element
c07b5ad4 2085 $html = $this->_groupElementTemplate;
906ebc4b 2086 }
2087 elseif (method_exists($element, 'getElementTemplateType')){
da6f8763 2088 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2089 }else{
2090 $html = $this->_elementTemplates['default'];
19194f82 2091 }
2092 if ($this->_showAdvanced){
2093 $advclass = ' advanced';
2094 } else {
2095 $advclass = ' advanced hide';
2096 }
2097 if (isset($this->_advancedElements[$element->getName()])){
2098 $html =str_replace(' {advanced}', $advclass, $html);
2099 } else {
2100 $html =str_replace(' {advanced}', '', $html);
2101 }
2102 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2103 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2104 } else {
2105 $html =str_replace('{advancedimg}', '', $html);
da6f8763 2106 }
49c53687 2107 $html =str_replace('{type}', 'f'.$element->getType(), $html);
e7004d05 2108 $html =str_replace('{name}', $element->getName(), $html);
da6f8763 2109 if (method_exists($element, 'getHelpButton')){
9403060a 2110 $html = str_replace('{help}', $element->getHelpButton(), $html);
da6f8763 2111 }else{
9403060a 2112 $html = str_replace('{help}', '', $html);
7f40a229 2113
da6f8763 2114 }
906ebc4b 2115 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2116 $this->_groupElementTemplate = $html;
41b6d001 2117 }
906ebc4b 2118 elseif (!isset($this->_templates[$element->getName()])) {
2119 $this->_templates[$element->getName()] = $html;
172dd12c 2120 }
2121
da6f8763 2122 parent::renderElement($element, $required, $error);
2123 }
19194f82 2124
ba21c9d4 2125 /**
2126 * @param object $form Passed by reference
2127 */
bb40325e 2128 function finishForm(&$form){
4f51f48f 2129 if ($form->isFrozen()){
2130 $this->_hiddenHtml = '';
2131 }
bb40325e 2132 parent::finishForm($form);
4f51f48f 2133 if ((!$form->isFrozen()) && ('' != ($script = $form->getLockOptionEndScript()))) {
2134 // add a lockoptions script
bb40325e 2135 $this->_html = $this->_html . "\n" . $script;
2136 }
2137 }
19194f82 2138 /**
2139 * Called when visiting a header element
2140 *
ba21c9d4 2141 * @param object $header An HTML_QuickForm_header element being visited
19194f82 2142 * @access public
2143 * @return void
2144 */
c28bf5c9 2145 function renderHeader(&$header) {
2146 global $PAGE;
9262d2d3 2147 static $advformcount;
2148
2149 // This ensures that if 2(+) advanced buttons are used
2150 // that all show/hide buttons appear in the correct place
2151 // Because of now using $PAGE->requires->js_function_call
2152 if ($advformcount==null) {
2153 $advformcount = 1;
2154 }
2155
19194f82 2156 $name = $header->getName();
2157
2158 $id = empty($name) ? '' : ' id="' . $name . '"';
78354cec 2159 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
19194f82 2160 if (is_null($header->_text)) {
2161 $header_html = '';
2162 } elseif (!empty($name) && isset($this->_templates[$name])) {
2163 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2164 } else {
2165 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2166 }
2167
2168 if (isset($this->_advancedElements[$name])){
2169 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2170 } else {
2171 $header_html =str_replace('{advancedimg}', '', $header_html);
2172 }
2173 $elementName='mform_showadvanced';
2174 if ($this->_showAdvanced==0){
2175 $buttonlabel = get_string('showadvanced', 'form');
2176 } else {
2177 $buttonlabel = get_string('hideadvanced', 'form');
2178 }
2179
2180 if (isset($this->_advancedElements[$name])){
f44b10ed 2181 $PAGE->requires->yui2_lib('event');
7c9b1d31 2182 // this is tricky - the first submit button on form is "clicked" if user presses enter
2183 // we do not want to "submit" using advanced button if javascript active
9262d2d3 2184 $button_nojs = '<input name="'.$elementName.'" id="'.$elementName.(string)$advformcount.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
cd350b53 2185
2186 $buttonlabel = addslashes_js($buttonlabel);
fc4f5796 2187 $PAGE->requires->string_for_js('showadvanced', 'form');
2188 $PAGE->requires->string_for_js('hideadvanced', 'form');
2189 $PAGE->requires->js_function_call('showAdvancedInit', Array($elementName.(string)$advformcount, $elementName, $buttonlabel));
117bd748 2190
9262d2d3 2191 $advformcount++;
2192 $header_html = str_replace('{button}', $button_nojs, $header_html);
19194f82 2193 } else {
7c9b1d31 2194 $header_html = str_replace('{button}', '', $header_html);
19194f82 2195 }
2196
2197 if ($this->_fieldsetsOpen > 0) {
2198 $this->_html .= $this->_closeFieldsetTemplate;
2199 $this->_fieldsetsOpen--;
2200 }
2201
2202 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2203 if ($this->_showAdvanced){
2204 $advclass = ' class="advanced"';
2205 } else {
2206 $advclass = ' class="advanced hide"';
2207 }
2208 if (isset($this->_advancedElements[$name])){
2209 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2210 } else {
2211 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2212 }
2213 $this->_html .= $openFieldsetTemplate . $header_html;
2214 $this->_fieldsetsOpen++;
2215 } // end func renderHeader
2216
2217 function getStopFieldsetElements(){
2218 return $this->_stopFieldsetElements;
2219 }
da6f8763 2220}
2221
ba21c9d4 2222/**
2223 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2224 * @name $_HTML_QuickForm_default_renderer
2225 */
66491cf1 2226$GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
da6f8763 2227
ba21c9d4 2228/** Please keep this list in alphabetical order. */
c583482c 2229MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2230MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2231MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
09179b78 2232MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
7f40a229 2233MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
c583482c 2234MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
2235MoodleQuickForm::registerElementType('choosecoursefileorimsrepo', "$CFG->libdir/form/choosecoursefileorimsrepo.php", 'MoodleQuickForm_choosecoursefileorimsrepo');
2236MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2237MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
32fa2272 2238MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
c583482c 2239MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
7f40a229 2240MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
241431cd 2241MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
c5704ec6 2242MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
c583482c 2243MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
7f40a229 2244MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
c583482c 2245MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2246MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2247MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2248MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2249MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
7f40a229 2250MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
4f51f48f 2251MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
c583482c 2252MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
7f40a229 2253MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
c583482c 2254MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
7f40a229 2255MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
4f51f48f 2256MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
c583482c 2257MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2258MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2259MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2260MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
6073a598 2261MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
9f1c9dfc 2262MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
7f40a229 2263MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2264MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1a03384f 2265MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
1ae1941e 2266MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');