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