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