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