Language string changes
[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
24//point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else.
25if (FALSE===strstr(ini_get('include_path'), $CFG->libdir.'/pear' )){
26 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
27}
28require_once 'HTML/QuickForm.php';
29require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
30require_once 'HTML/QuickForm/Renderer/Tableless.php';
31
49292f8c 32require_once $CFG->libdir.'/uploadlib.php';
33
19194f82 34define('FORM_ADVANCEDIMAGEURL', $CFG->wwwroot.'/lib/form/adv.gif');
35define('FORM_REQIMAGEURL', $CFG->wwwroot.'/lib/form/req.gif');
36
a23f0aaf 37/**
38 * Callback called when PEAR throws an error
39 *
40 * @param PEAR_Error $error
41 */
42function pear_handle_error($error){
43 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
44 echo '<br /> <strong>Backtrace </strong>:';
45 print_object($error->backtrace);
46}
47
864cc1de 48if ($CFG->debug >= DEBUG_ALL){
a23f0aaf 49 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
864cc1de 50}
51
f07b9627 52
05f5c40c 53/**
da1320da 54 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
55 * use this class you should write a class defintion which extends this class or a more specific
56 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
57 *
58 * You will write your own definition() method which performs the form set up.
05f5c40c 59 */
7f40a229 60class moodleform {
49292f8c 61 var $_formname; // form name
3c7656b4 62 /**
63 * quickform object definition
64 *
65 * @var MoodleQuickForm
66 */
67 var $_form;
68 /**
69 * globals workaround
70 *
71 * @var array
72 */
73 var $_customdata;
74 /**
75 * file upload manager
76 *
77 * @var upload_manager
78 */
79 var $_upload_manager; //
7f40a229 80
19110c57 81
ebd3c7ac 82
da1320da 83 /**
84 * The constructor function calls the abstract function definition() and it will then
85 * process and clean and attempt to validate incoming data.
86 *
87 * It will call your custom validate method to validate data and will also check any rules
88 * you have specified in definition using addRule
89 *
90 * The name of the form (id attribute of the form) is automatically generated depending on
91 * the name you gave the class extending moodleform. You should call your class something
92 * like
93 *
a23f0aaf 94 * @param string $action the action attribute for the form. If empty defaults to auto detect the
95 * current url.
da1320da 96 * @param array $customdata if your form defintion method needs access to data such as $course
97 * $cm, etc. to construct the form definition then pass it in this array. You can
98 * use globals for somethings.
99 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
100 * be merged and used as incoming data to the form.
101 * @param string $target target frame for form submission. You will rarely use this. Don't use
102 * it if you don't need to as the target attribute is deprecated in xhtml
103 * strict.
104 * @param mixed $attributes you can pass a string of html attributes here or an array.
105 * @return moodleform
106 */
a23f0aaf 107 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null) {
108 if (empty($action)){
109 $action = strip_querystring(qualified_me());
110 }
f07b9627 111
72f46d11 112 $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
7f40a229 113 $this->_customdata = $customdata;
5bc97c98 114 $this->_form =& new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
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);
127
05f5c40c 128 // update form definition based on final data
129 $this->definition_after_data();
7f40a229 130 }
05f5c40c 131
2c412890 132 /**
da1320da 133 * To autofocus on first form element or first element with error.
2c412890 134 *
135 * @return string javascript to select form element with first error or
da1320da 136 * first element if no errors. Use this as a parameter
137 * when calling print_header
2c412890 138 */
139 function focus(){
9403060a 140 $form =& $this->_form;
5c52df67 141 $elkeys=array_keys($form->_elementIndex);
9403060a 142 if (isset($form->_errors) && 0 != count($form->_errors)){
143 $errorkeys = array_keys($form->_errors);
144 $elkeys = array_intersect($elkeys, $errorkeys);
2c412890 145 }
9403060a 146 $names=null;
147 while (!$names){
148 $el = array_shift($elkeys);
149 $names=$form->_getElNamesRecursive($el);
150 }
151 $name=array_shift($names);
152 $focus='forms[\''.$this->_form->getAttribute('id').'\'].elements[\''.$name.'\']';
153 return $focus;
154 }
7f40a229 155
05f5c40c 156 /**
157 * Internal method. Alters submitted data to be suitable for quickforms processing.
158 * Must be called when the form is fully set up.
159 */
7f40a229 160 function _process_submission($method) {
161 $submission = array();
162 if ($method == 'post') {
163 if (!empty($_POST)) {
164 $submission = $_POST;
165 }
166 } else {
167 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
168 }
169
170 // following trick is needed to enable proper sesskey checks when using GET forms
5bc97c98 171 // the _qf__.$this->_formname serves as a marker that form was actually submitted
172 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
7f40a229 173 if (!confirm_sesskey()) {
174 error('Incorrect sesskey submitted, form not accepted!');
175 }
05f5c40c 176 $files = $_FILES;
7f40a229 177 } else {
178 $submission = array();
05f5c40c 179 $files = array();
7f40a229 180 }
181
05f5c40c 182 $this->_form->updateSubmission($submission, $files);
7f40a229 183 }
184
05f5c40c 185 /**
186 * Internal method. Validates all uploaded files.
187 */
49292f8c 188 function _validate_files() {
189 if (empty($_FILES)) {
190 // we do not need to do any checks because no files were submitted
191 // TODO: find out why server side required rule does not work for uploaded files;
192 // testing is easily done by always returning true from this function and adding
193 // $mform->addRule('soubor', get_string('required'), 'required', null, 'server');
194 // and submitting form without selected file
195 return true;
196 }
197 $errors = array();
198 $mform =& $this->_form;
199
49292f8c 200 // check the files
201 $status = $this->_upload_manager->preprocess_files();
202
203 // now check that we really want each file
204 foreach ($_FILES as $elname=>$file) {
205 if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
206 $required = $mform->isElementRequired($elname);
207 if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
208 if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
209 // file not uploaded and not required - ignore it
210 continue;
211 }
212 $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
213 }
214 } else {
feaf5d06 215 error('Incorrect upload attempt!');
49292f8c 216 }
217 }
218
219 // return errors if found
220 if ($status and 0 == count($errors)){
221 return true;
222 } else {
223 return $errors;
224 }
225 }
226
05f5c40c 227 /**
da1320da 228 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
229 * form definition (new entry form); this function is used to load in data where values
230 * already exist and data is being edited (edit entry form).
05f5c40c 231 *
232 * @param mixed $default_values object or array of default values
233 * @param bool $slased true if magic quotes applied to data values
234 */
7f40a229 235 function set_defaults($default_values, $slashed=false) {
236 if (is_object($default_values)) {
237 $default_values = (array)$default_values;
238 }
239 $filter = $slashed ? 'stripslashes' : NULL;
240 $this->_form->setDefaults($default_values, $filter);
38f394b2 241 //update form definition when data changed
05f5c40c 242 $this->definition_after_data();
7f40a229 243 }
244
c80a13c7 245 /**
feaf5d06 246 * Set custom upload manager.
c80a13c7 247 * Must be used BEFORE creating of file element!
248 *
feaf5d06 249 * @param object $um - custom upload manager
c80a13c7 250 */
feaf5d06 251 function set_upload_manager($um=false) {
252 if ($um === false) {
253 $um = new upload_manager();
c80a13c7 254 }
feaf5d06 255 $this->_upload_manager = $um;
c80a13c7 256
feaf5d06 257 $this->_form->setMaxFileSize($um->config->maxbytes);
c80a13c7 258 }
259
05f5c40c 260 /**
261 * Check that form was submitted. Does not check validity of submitted data.
262 *
263 * @return bool true if form properly submitted
264 */
7f40a229 265 function is_submitted() {
266 return $this->_form->isSubmitted();
267 }
268
a23f0aaf 269 function no_submit_button_pressed(){
270 static $nosubmit = null; // one check is enough
271 if (!is_null($nosubmit)){
272 return $nosubmit;
273 }
274 $mform =& $this->_form;
275 $nosubmit = false;
f07b9627 276 if (!$this->is_submitted()){
277 return false;
278 }
a23f0aaf 279 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
280 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
281 $nosubmit = true;
282 break;
283 }
284 }
285 return $nosubmit;
286 }
287
288
05f5c40c 289 /**
290 * Check that form data is valid.
291 *
292 * @return bool true if form data valid
293 */
7f40a229 294 function is_validated() {
49292f8c 295 static $validated = null; // one validation is enough
3ba2c187 296 $mform =& $this->_form;
f07b9627 297
9aa022fe 298 if ($this->no_submit_button_pressed()){
299 return false;
300 } elseif ($validated === null) {
3ba2c187 301 $internal_val = $mform->validate();
302 $moodle_val = $this->validation($mform->exportValues(null, true));
7f40a229 303 if ($moodle_val !== true) {
a23f0aaf 304 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
7f40a229 305 foreach ($moodle_val as $element=>$msg) {
3ba2c187 306 $mform->setElementError($element, $msg);
7f40a229 307 }
a23f0aaf 308 $moodle_val = false;
309 } else {
310 $moodle_val = true;
7f40a229 311 }
7f40a229 312 }
49292f8c 313 $file_val = $this->_validate_files();
314 if ($file_val !== true) {
315 if (!empty($file_val)) {
316 foreach ($file_val as $element=>$msg) {
3ba2c187 317 $mform->setElementError($element, $msg);
49292f8c 318 }
319 }
320 $file_val = false;
321 }
322 $validated = ($internal_val and $moodle_val and $file_val);
7f40a229 323 }
9aa022fe 324 return $validated;
7f40a229 325 }
326
19110c57 327 /**
328 * Return true if a cancel button has been pressed resulting in the form being submitted.
329 *
330 * @return boolean true if a cancel button has been pressed
331 */
332 function is_cancelled(){
333 $mform =& $this->_form;
a23f0aaf 334 if ($mform->isSubmitted()){
335 foreach ($mform->_cancelButtons as $cancelbutton){
336 if (optional_param($cancelbutton, 0, PARAM_RAW)){
337 return true;
338 }
19110c57 339 }
340 }
341 return false;
342 }
343
05f5c40c 344 /**
da1320da 345 * Return submitted data if properly submitted or returns NULL if validation fails or
346 * if there is no submitted data.
05f5c40c 347 *
348 * @param bool $slashed true means return data with addslashes applied
349 * @return object submitted data; NULL if not valid or not submitted
350 */
7f40a229 351 function data_submitted($slashed=true) {
19110c57 352 $mform =& $this->_form;
3ba2c187 353
7f40a229 354 if ($this->is_submitted() and $this->is_validated()) {
19110c57 355 $data = $mform->exportValues(null, $slashed);
5bc97c98 356 unset($data['sesskey']); // we do not need to return sesskey
357 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
7f40a229 358 if (empty($data)) {
359 return NULL;
360 } else {
361 return (object)$data;
362 }
363 } else {
364 return NULL;
365 }
366 }
367
05f5c40c 368 /**
369 * Save verified uploaded files into directory. Upload process can be customised from definition()
38f394b2 370 * method by creating instance of upload manager and storing it in $this->_upload_form
05f5c40c 371 *
372 * @param string $destination where to store uploaded files
373 * @return bool success
374 */
49292f8c 375 function save_files($destination) {
49292f8c 376 if ($this->is_submitted() and $this->is_validated()) {
377 return $this->_upload_manager->save_files($destination);
378 }
379 return false;
380 }
2b63df96 381
feaf5d06 382 /**
383 * If we're only handling one file (if inputname was given in the constructor)
384 * this will return the (possibly changed) filename of the file.
385 * @return mixed false in case of failure, string if ok
386 */
387 function get_new_filename() {
388 return $this->_upload_manager->get_new_filename();
389 }
390
05f5c40c 391 /**
392 * Print html form.
393 */
7f40a229 394 function display() {
395 $this->_form->display();
396 }
397
49292f8c 398 /**
05f5c40c 399 * Abstract method - always override!
49292f8c 400 *
401 * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
402 */
7f40a229 403 function definition() {
404 error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
405 }
2c412890 406
c08ac016 407 /**
05f5c40c 408 * Dummy stub method - override if you need to setup the form depending on current
409 * values. This method is called after definition(), data submission and set_defaults().
410 * All form setup that is dependent on form values should go in here.
c08ac016 411 */
412 function definition_after_data(){
c08ac016 413 }
7f40a229 414
05f5c40c 415 /**
416 * Dummy stub method - override if you needed to perform some extra validation.
417 * If there are errors return array of errors ("fieldname"=>"error message"),
418 * otherwise true if ok.
38f394b2 419 *
05f5c40c 420 * @param array $data array of ("fieldname"=>value) of submitted data
38f394b2 421 * @return bool array of errors or true if ok
05f5c40c 422 */
7f40a229 423 function validation($data) {
7f40a229 424 return true;
425 }
ebd3c7ac 426
19110c57 427
ebd3c7ac 428
19194f82 429
a23f0aaf 430
616b549a 431 /**
432 * Method to add a repeating group of elements to a form.
433 *
434 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
435 * @param integer $repeats no of times to repeat elements initially
436 * @param array $options Array of options to apply to elements. Array keys are element names.
437 * This is an array of arrays. The second sets of keys are the option types
438 * for the elements :
439 * 'default' - default value is value
440 * 'type' - PARAM_* constant is value
441 * 'helpbutton' - helpbutton params array is value
442 * 'disabledif' - last three moodleform::disabledIf()
443 * params are value as an array
444 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
445 * @param string $addfieldsname name for button to add more fields
446 * @param int $addfieldsno how many fields to add at a time
271ffe3f 447 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
a23f0aaf 448 * @return int no of repeats of element in this page
616b549a 449 */
271ffe3f 450 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, $addfieldsname, $addfieldsno=5, $addstring=null){
451 if ($addstring===null){
452 $addstring = get_string('addfields', 'form', $addfieldsno);
453 } else {
454 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
455 }
ebd3c7ac 456 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
457 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
458 if (!empty($addfields)){
459 $repeats += $addfieldsno;
460 }
ebd3c7ac 461 $mform =& $this->_form;
a23f0aaf 462 $mform->registerNoSubmitButton($addfieldsname);
ebd3c7ac 463 $mform->addElement('hidden', $repeathiddenname, $repeats);
464 //value not to be overridden by submitted value
465 $mform->setConstants(array($repeathiddenname=>$repeats));
466 for ($i=0; $i<$repeats; $i++) {
467 foreach ($elementobjs as $elementobj){
271ffe3f 468 $elementclone = clone($elementobj);
ebd3c7ac 469 $name=$elementclone->getName();
86aab05c 470 if (!empty($name)){
471 $elementclone->setName($name."[$i]");
472 }
ebd3c7ac 473 if (is_a($elementclone, 'HTML_QuickForm_header')){
474 $value=$elementclone->_text;
271ffe3f 475 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
476
477 } else {
478 $value=$elementclone->getLabel();
479 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
ebd3c7ac 480
481 }
482 $mform->addElement($elementclone);
483 }
484 }
485 for ($i=0; $i<$repeats; $i++) {
486 foreach ($options as $elementname => $elementoptions){
487 $pos=strpos($elementname, '[');
488 if ($pos!==FALSE){
489 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
490 $realelementname .= substr($elementname, $pos+1);
491 }else {
492 $realelementname = $elementname."[$i]";
493 }
494 foreach ($elementoptions as $option => $params){
495
496 switch ($option){
497 case 'default' :
498 $mform->setDefault($realelementname, $params);
499 break;
500 case 'type' :
501 $mform->setType($realelementname, $params);
502 break;
503 case 'helpbutton' :
504 $mform->setHelpButton($realelementname, $params);
505 break;
506 case 'disabledif' :
9aa022fe 507 $params = array_merge(array($realelementname), $params);
508 call_user_func_array(array(&$mform, 'disabledIf'), $params);
509 break;
510 case 'rule' :
511 if (is_string($params)){
512 $params = array(null, $params, null, 'client');
513 }
514 $params = array_merge(array($realelementname), $params);
515 call_user_func_array(array(&$mform, 'addRule'), $params);
ebd3c7ac 516 break;
517
518 }
519 }
520 }
521 }
271ffe3f 522 $mform->addElement('submit', $addfieldsname, $addstring);
a23f0aaf 523
524 $mform->closeHeaderBefore($addfieldsname);
ebd3c7ac 525
19194f82 526 return $repeats;
ebd3c7ac 527 }
a23f0aaf 528 /**
1d284fbd 529 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
a23f0aaf 530 * if you don't want a cancel button in your form. If you have a cancel button make sure you
531 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
532 * get data with data_submitted().
533 *
534 * @param boolean $cancel whether to show cancel button, default true
535 * @param boolean $revert whether to show revert button, default true
536 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
537 */
1d284fbd 538 function add_action_buttons($cancel = true, $submitlabel=null){
a23f0aaf 539 if (is_null($submitlabel)){
540 $submitlabel = get_string('savechanges');
541 }
542 $mform =& $this->_form;
1d284fbd 543 if ($cancel){
544 //when two elements we need a group
a23f0aaf 545 $buttonarray=array();
546 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1d284fbd 547 $buttonarray[] = &$mform->createElement('cancel');
a23f0aaf 548 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
549 $mform->closeHeaderBefore('buttonar');
550 } else {
551 //no group needed
552 $mform->addElement('submit', 'submitbutton', $submitlabel);
553 $mform->closeHeaderBefore('submitbutton');
554 }
555 }
7f40a229 556}
557
da1320da 558/**
559 * You never extend this class directly. The class methods of this class are available from
560 * the private $this->_form property on moodleform and it's children. You generally only
561 * call methods on this class from within abstract methods that you override on moodleform such
562 * as definition and definition_after_data
563 *
564 */
7f40a229 565class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
566 var $_types = array();
50ef8eb9 567 var $_dependencies = array();
19110c57 568 /**
569 * Array of buttons that if pressed do not result in the processing of the form.
570 *
571 * @var array
572 */
573 var $_noSubmitButtons=array();
574 /**
575 * Array of buttons that if pressed do not result in the processing of the form.
576 *
577 * @var array
578 */
579 var $_cancelButtons=array();
7f40a229 580
19194f82 581 /**
582 * Array whose keys are element names. If the key exists this is a advanced element
583 *
584 * @var array
585 */
586 var $_advancedElements = array();
587
588 /**
589 * Whether to display advanced elements (on page load)
590 *
591 * @var boolean
592 */
593 var $_showAdvanced = null;
594
f07b9627 595 /**
596 * The form name is derrived from the class name of the wrapper minus the trailing form
597 * It is a name with words joined by underscores whereas the id attribute is words joined by
598 * underscores.
599 *
600 * @var unknown_type
601 */
602 var $_formName = '';
603
da6f8763 604 /**
605 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
606 * @param string $formName Form's name.
607 * @param string $method (optional)Form's method defaults to 'POST'
608 * @param string $action (optional)Form's action
609 * @param string $target (optional)Form's target defaults to none
610 * @param mixed $attributes (optional)Extra attributes for <form> tag
611 * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
612 * @access public
613 */
7f40a229 614 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
da6f8763 615 global $CFG;
271ffe3f 616 static $formcounter = 1;
7f40a229 617
da6f8763 618 HTML_Common::HTML_Common($attributes);
da6f8763 619 $target = empty($target) ? array() : array('target' => $target);
f07b9627 620 $this->_formName = $formName;
da6f8763 621 //no 'name' atttribute for form in xhtml strict :
271ffe3f 622 $attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target;
623 $formcounter++;
da6f8763 624 $this->updateAttributes($attributes);
da6f8763 625
7f40a229 626 //this is custom stuff for Moodle :
da6f8763 627 $oldclass= $this->getAttribute('class');
628 if (!empty($oldclass)){
629 $this->updateAttributes(array('class'=>$oldclass.' mform'));
630 }else {
80f962df 631 $this->updateAttributes(array('class'=>'mform'));
da6f8763 632 }
19194f82 633 $this->_reqHTML = '<img alt="'.get_string('requiredelement', 'form').'" src="'.FORM_REQIMAGEURL.'" />';
634 $this->_advancedHTML = '<img alt="'.get_string('advancedelement', 'form').'" src="'.FORM_ADVANCEDIMAGEURL.'" />';
3d685169 635 $this->setRequiredNote(get_string('denotesreq', 'form',
da6f8763 636 helpbutton('requiredelement', get_string('requiredelement', 'form'),'moodle',
3ba2c187 637 true, false, '', true, '<img alt="'.get_string('requiredelement', 'form').'" src="'.
19194f82 638 FORM_REQIMAGEURL.'" />')));
639 }
640
a23f0aaf 641 /**
642 * Use this method to indicate an element in a form is an advanced field. If items in a form
643 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
644 * form so the user can decide whether to display advanced form controls.
645 *
646 * If you set a header element to advanced then all elements it contains will also be set as advanced.
647 *
648 * @param string $elementName group or element name (not the element name of something inside a group).
649 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
650 */
651 function setAdvanced($elementName, $advanced=true){
652 if ($advanced){
653 $this->_advancedElements[$elementName]='';
654 } elseif (isset($this->_advancedElements[$elementName])) {
655 unset($this->_advancedElements[$elementName]);
656 }
657 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
658 $this->setShowAdvanced();
659 $this->registerNoSubmitButton('mform_showadvanced');
660
661 $this->addElement('hidden', 'mform_showadvanced_last');
662 }
663 }
664 /**
665 * Set whether to show advanced elements in the form on first displaying form. Default is not to
666 * display advanced elements in the form until 'Show Advanced' is pressed.
667 *
668 * You can get the last state of the form and possibly save it for this user by using
669 * value 'mform_showadvanced_last' in submitted data.
670 *
671 * @param boolean $showadvancedNow
672 */
673 function setShowAdvanced($showadvancedNow = null){
674 if ($showadvancedNow === null){
675 if ($this->_showAdvanced !== null){
676 return;
677 } else { //if setShowAdvanced is called without any preference
678 //make the default to not show advanced elements.
f07b9627 679 $showadvancedNow = get_user_preferences(
680 moodle_strtolower($this->_formName.'_showadvanced', 0));
a23f0aaf 681 }
a23f0aaf 682 }
683 //value of hidden element
684 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
685 //value of button
686 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
687 //toggle if button pressed or else stay the same
688 if ($hiddenLast == -1) {
689 $next = $showadvancedNow;
690 } elseif ($buttonPressed) { //toggle on button press
691 $next = !$hiddenLast;
692 } else {
693 $next = $hiddenLast;
694 }
695 $this->_showAdvanced = $next;
f07b9627 696 if ($showadvancedNow != $next){
697 set_user_preference($this->_formName.'_showadvanced', $next);
698 }
a23f0aaf 699 $this->setConstants(array('mform_showadvanced_last'=>$next));
19194f82 700 }
701 function getShowAdvanced(){
702 return $this->_showAdvanced;
703 }
704
19194f82 705
706 /**
707 * Accepts a renderer
708 *
709 * @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
710 * @since 3.0
711 * @access public
712 * @return void
713 */
714 function accept(&$renderer)
715 {
716 if (method_exists($renderer, 'setAdvancedElements')){
717 //check for visible fieldsets where all elements are advanced
718 //and mark these headers as advanced as well.
719 //And mark all elements in a advanced header as advanced
720 $stopFields = $renderer->getStopFieldSetElements();
721 $lastHeader = null;
722 $lastHeaderAdvanced = false;
723 $anyAdvanced = false;
724 foreach (array_keys($this->_elements) as $elementIndex){
725 $element =& $this->_elements[$elementIndex];
726 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
727 if ($anyAdvanced && ($lastHeader!==null)){
728 $this->setAdvanced($lastHeader->getName());
729 }
730 $lastHeaderAdvanced = false;
731 } elseif ($lastHeaderAdvanced) {
732 $this->setAdvanced($element->getName());
733 }
734 if ($element->getType()=='header'){
735 $lastHeader =& $element;
736 $anyAdvanced = false;
737 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
738 } elseif (isset($this->_advancedElements[$element->getName()])){
739 $anyAdvanced = true;
740 }
741 }
742 $renderer->setAdvancedElements($this->_advancedElements);
743 if (count($this->_advancedElements)){
744
745 }
746 }
747 parent::accept($renderer);
748 }
749
19194f82 750
19194f82 751
752 function closeHeaderBefore($elementName){
753 $renderer =& $this->defaultRenderer();
754 $renderer->addStopFieldsetElements($elementName);
da6f8763 755 }
bb40325e 756
da1320da 757 /**
758 * Should be used for all elements of a form except for select, radio and checkboxes which
759 * clean their own data.
760 *
761 * @param string $elementname
762 * @param integer $paramtype use the constants PARAM_*.
763 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
764 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
765 * It will strip all html tags. But will still let tags for multilang support
766 * through.
767 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
768 * html editor. Data from the editor is later cleaned before display using
769 * format_text() function. PARAM_RAW can also be used for data that is validated
770 * by some other way or printed by p() or s().
771 * * PARAM_INT should be used for integers.
772 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
773 * form actions.
774 */
7f40a229 775 function setType($elementname, $paramtype) {
776 $this->_types[$elementname] = $paramtype;
777 }
49292f8c 778
da1320da 779 /**
780 * See description of setType above. This can be used to set several types at once.
781 *
782 * @param array $paramtypes
783 */
c56f1826 784 function setTypes($paramtypes) {
785 $this->_types = $paramtypes + $this->_types;
786 }
49292f8c 787
788 function updateSubmission($submission, $files) {
789 $this->_flagSubmitted = false;
790
7f40a229 791 if (empty($submission)) {
792 $this->_submitValues = array();
7f40a229 793 } else {
794 foreach ($submission as $key=>$s) {
795 if (array_key_exists($key, $this->_types)) {
796 $submission[$key] = clean_param($s, $this->_types[$key]);
797 }
798 }
799 $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
800 $this->_flagSubmitted = true;
801 }
802
49292f8c 803 if (empty($files)) {
804 $this->_submitFiles = array();
805 } else {
806 if (1 == get_magic_quotes_gpc()) {
807 foreach ($files as $elname=>$file) {
808 // dangerous characters in filenames are cleaned later in upload_manager
809 $files[$elname]['name'] = stripslashes($files[$elname]['name']);
810 }
811 }
812 $this->_submitFiles = $files;
813 $this->_flagSubmitted = true;
814 }
815
2c412890 816 // need to tell all elements that they need to update their value attribute.
817 foreach (array_keys($this->_elements) as $key) {
818 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
819 }
7f40a229 820 }
821
da6f8763 822 function getReqHTML(){
823 return $this->_reqHTML;
824 }
7f40a229 825
19194f82 826 function getAdvancedHTML(){
827 return $this->_advancedHTML;
828 }
829
7f40a229 830 /**
da1320da 831 * Initializes a default form value. Used to specify the default for a new entry where
832 * no data is loaded in using moodleform::set_defaults()
7f40a229 833 *
834 * @param string $elementname element name
835 * @param mixed $values values for that element name
836 * @param bool $slashed the default value is slashed
837 * @access public
838 * @return void
839 */
840 function setDefault($elementName, $defaultValue, $slashed=false){
841 $filter = $slashed ? 'stripslashes' : NULL;
842 $this->setDefaults(array($elementName=>$defaultValue), $filter);
843 } // end func setDefault
da6f8763 844 /**
c56f1826 845 * Add an array of buttons to the form
7f40a229 846 * @param array $buttons An associative array representing help button to attach to
da6f8763 847 * to the form. keys of array correspond to names of elements in form.
7f40a229 848 *
da6f8763 849 * @access public
850 */
d4fe14d3 851 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
7f40a229 852
c56f1826 853 foreach ($buttons as $elementname => $button){
d4fe14d3 854 $this->setHelpButton($elementname, $button, $suppresscheck, $function);
da6f8763 855 }
856 }
c56f1826 857 /**
da1320da 858 * Add a single button.
c56f1826 859 *
860 * @param string $elementname name of the element to add the item to
d4fe14d3 861 * @param array $button - arguments to pass to function $function
c56f1826 862 * @param boolean $suppresscheck - whether to throw an error if the element
863 * doesn't exist.
d4fe14d3 864 * @param string $function - function to generate html from the arguments in $button
c56f1826 865 */
d4fe14d3 866 function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
c56f1826 867 if (array_key_exists($elementname, $this->_elementIndex)){
868 //_elements has a numeric index, this code accesses the elements by name
869 $element=&$this->_elements[$this->_elementIndex[$elementname]];
870 if (method_exists($element, 'setHelpButton')){
d4fe14d3 871 $element->setHelpButton($button, $function);
c56f1826 872 }else{
873 $a=new object();
874 $a->name=$element->getName();
875 $a->classname=get_class($element);
876 print_error('nomethodforaddinghelpbutton', 'form', '', $a);
877 }
878 }elseif (!$suppresscheck){
879 print_error('nonexistentformelements', 'form', '', $elementname);
2c412890 880 }
c56f1826 881 }
7f40a229 882
42f248e6 883 function exportValues($elementList= null, $addslashes=true){
0ffb4cc7 884 $unfiltered = array();
885 if (null === $elementList) {
886 // iterate over all elements, calling their exportValue() methods
887 foreach (array_keys($this->_elements) as $key) {
888 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
889 $value = $this->_elements[$key]->exportValue(array(), true);
890 } else {
891 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
892 }
893
894 if (is_array($value)) {
895 // This shit throws a bogus warning in PHP 4.3.x
896 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
897 }
898 }
899 } else {
900 if (!is_array($elementList)) {
901 $elementList = array_map('trim', explode(',', $elementList));
902 }
903 foreach ($elementList as $elementName) {
904 $value = $this->exportValue($elementName);
905 if (PEAR::isError($value)) {
906 return $value;
907 }
908 $unfiltered[$elementName] = $value;
909 }
910 }
7f40a229 911
da6f8763 912 if ($addslashes){
0ffb4cc7 913 return $this->_recursiveFilter('addslashes', $unfiltered);
da6f8763 914 } else {
915 return $unfiltered;
916 }
917 }
f07b9627 918 /**
919 * Adds a validation rule for the given field
920 *
921 * If the element is in fact a group, it will be considered as a whole.
922 * To validate grouped elements as separated entities,
923 * use addGroupRule instead of addRule.
924 *
925 * @param string $element Form element name
926 * @param string $message Message to display for invalid data
927 * @param string $type Rule type, use getRegisteredRules() to get types
928 * @param string $format (optional)Required for extra rule data
929 * @param string $validation (optional)Where to perform validation: "server", "client"
930 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
931 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
932 * @since 1.0
933 * @access public
934 * @throws HTML_QuickForm_Error
935 */
936 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
937 {
938 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
939 if ($validation == 'client') {
940 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
941 }
942
943 } // end func addRule
944 /**
945 * Adds a validation rule for the given group of elements
946 *
947 * Only groups with a name can be assigned a validation rule
948 * Use addGroupRule when you need to validate elements inside the group.
949 * Use addRule if you need to validate the group as a whole. In this case,
950 * the same rule will be applied to all elements in the group.
951 * Use addRule if you need to validate the group against a function.
952 *
953 * @param string $group Form group name
954 * @param mixed $arg1 Array for multiple elements or error message string for one element
955 * @param string $type (optional)Rule type use getRegisteredRules() to get types
956 * @param string $format (optional)Required for extra rule data
957 * @param int $howmany (optional)How many valid elements should be in the group
958 * @param string $validation (optional)Where to perform validation: "server", "client"
959 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
960 * @since 2.5
961 * @access public
962 * @throws HTML_QuickForm_Error
963 */
964 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
965 {
966 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
967 if (is_array($arg1)) {
968 foreach ($arg1 as $elementIndex => $rules) {
969 foreach ($rules as $rule) {
970 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
971
972 if ('client' == $validation) {
973 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
974 }
975 }
976 }
977 } elseif (is_string($arg1)) {
978
979 if ($validation == 'client') {
980 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $formname . '; } catch(e) { return true; } return myValidator(this);'));
981 }
982 }
983 } // end func addGroupRule
984
985 // }}}
5bc97c98 986 /**
987 * Returns the client side validation script
988 *
989 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
990 * and slightly modified to run rules per-element
991 * Needed to override this because of an error with client side validation of grouped elements.
992 *
993 * @access public
994 * @return string Javascript to perform validation, empty string if no 'client' rules were added
995 */
996 function getValidationScript()
997 {
998 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
999 return '';
1000 }
1001
1002 include_once('HTML/QuickForm/RuleRegistry.php');
1003 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1004 $test = array();
1005 $js_escape = array(
1006 "\r" => '\r',
1007 "\n" => '\n',
1008 "\t" => '\t',
1009 "'" => "\\'",
1010 '"' => '\"',
1011 '\\' => '\\\\'
1012 );
1013
1014 foreach ($this->_rules as $elementName => $rules) {
1015 foreach ($rules as $rule) {
1016 if ('client' == $rule['validation']) {
da1320da 1017 unset($element); //TODO: find out how to properly initialize it
5bc97c98 1018
1019 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1020 $rule['message'] = strtr($rule['message'], $js_escape);
1021
1022 if (isset($rule['group'])) {
1023 $group =& $this->getElement($rule['group']);
1024 // No JavaScript validation for frozen elements
1025 if ($group->isFrozen()) {
1026 continue 2;
1027 }
1028 $elements =& $group->getElements();
1029 foreach (array_keys($elements) as $key) {
1030 if ($elementName == $group->getElementName($key)) {
1031 $element =& $elements[$key];
1032 break;
1033 }
1034 }
1035 } elseif ($dependent) {
1036 $element = array();
1037 $element[] =& $this->getElement($elementName);
1038 foreach ($rule['dependent'] as $idx => $elName) {
1039 $element[] =& $this->getElement($elName);
1040 }
1041 } else {
1042 $element =& $this->getElement($elementName);
1043 }
1044 // No JavaScript validation for frozen elements
1045 if (is_object($element) && $element->isFrozen()) {
1046 continue 2;
1047 } elseif (is_array($element)) {
1048 foreach (array_keys($element) as $key) {
1049 if ($element[$key]->isFrozen()) {
1050 continue 3;
1051 }
1052 }
1053 }
1054 // Fix for bug displaying errors for elements in a group
1055 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1056 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1057 $test[$elementName][1]=$element;
1058 //end of fix
1059 }
1060 }
1061 }
1062 $js = '
1063<script type="text/javascript">
1064//<![CDATA[
1cbb09f1 1065
1066var skipClientValidation = false;
1067
5bc97c98 1068function qf_errorHandler(element, _qfMsg) {
1069 div = element.parentNode;
1070 if (_qfMsg != \'\') {
e35c9eeb 1071 var errorSpan = document.getElementById(\'id_error_\'+element.name);
e7004d05 1072 if (!errorSpan) {
1073 errorSpan = document.createElement("span");
e35c9eeb 1074 errorSpan.id = \'id_error_\'+element.name;
1075 errorSpan.className = "error";
fed13a5e 1076 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
5bc97c98 1077 }
fed13a5e 1078
e7004d05 1079 while (errorSpan.firstChild) {
1080 errorSpan.removeChild(errorSpan.firstChild);
5bc97c98 1081 }
2c412890 1082
e7004d05 1083 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
e35c9eeb 1084 errorSpan.appendChild(document.createElement("br"));
5bc97c98 1085
1086 if (div.className.substr(div.className.length - 6, 6) != " error"
1087 && div.className != "error") {
1088 div.className += " error";
1089 }
1090
1091 return false;
1092 } else {
e35c9eeb 1093 var errorSpan = document.getElementById(\'id_error_\'+element.name);
e7004d05 1094 if (errorSpan) {
1095 errorSpan.parentNode.removeChild(errorSpan);
5bc97c98 1096 }
1097
1098 if (div.className.substr(div.className.length - 6, 6) == " error") {
1099 div.className = div.className.substr(0, div.className.length - 6);
1100 } else if (div.className == "error") {
1101 div.className = "";
1102 }
1103
1104 return true;
1105 }
1106}';
1107 $validateJS = '';
1108 foreach ($test as $elementName => $jsandelement) {
1109 // Fix for bug displaying errors for elements in a group
1110 //unset($element);
1111 list($jsArr,$element)=$jsandelement;
1112 //end of fix
1113 $js .= '
f07b9627 1114function validate_' . $this->_formName . '_' . $elementName . '(element) {
5bc97c98 1115 var value = \'\';
1116 var errFlag = new Array();
1117 var _qfGroups = {};
1118 var _qfMsg = \'\';
1119 var frm = element.parentNode;
1120 while (frm && frm.nodeName != "FORM") {
1121 frm = frm.parentNode;
1122 }
1123' . join("\n", $jsArr) . '
1124 return qf_errorHandler(element, _qfMsg);
1125}
1126';
1127 $validateJS .= '
f07b9627 1128 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;';
5bc97c98 1129 // Fix for bug displaying errors for elements in a group
1130 //unset($element);
1131 //$element =& $this->getElement($elementName);
1132 //end of fix
f07b9627 1133 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
5bc97c98 1134 $onBlur = $element->getAttribute('onBlur');
1135 $onChange = $element->getAttribute('onChange');
1136 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1137 'onChange' => $onChange . $valFunc));
1138 }
e7004d05 1139// do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
5bc97c98 1140 $js .= '
f07b9627 1141function validate_' . $this->_formName . '(frm) {
1cbb09f1 1142 if (skipClientValidation) {
1143 return true;
1144 }
5bc97c98 1145 var ret = true;
0befbdfd 1146
1147 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1148
5bc97c98 1149' . $validateJS . ';
1150 return ret;
1151}
1152//]]>
1153</script>';
1154 return $js;
1155 } // end func getValidationScript
1156 function _setDefaultRuleMessages(){
1157 foreach ($this->_rules as $field => $rulesarr){
1158 foreach ($rulesarr as $key => $rule){
1159 if ($rule['message']===null){
1160 $a=new object();
1161 $a->format=$rule['format'];
1162 $str=get_string('err_'.$rule['type'], 'form', $a);
1163 if (strpos($str, '[[')!==0){
1164 $this->_rules[$field][$key]['message']=$str;
2c412890 1165 }
5bc97c98 1166 }
1167 }
1168 }
1169 }
bb40325e 1170
d01a38cb 1171 function getLockOptionEndScript(){
f4ba7e1a 1172 $js = '<script type="text/javascript">'."\n";
5e87b920 1173 $js .= '//<![CDATA['."\n";
271ffe3f 1174 $js .= "var ".$this->getAttribute('id')."items= {";
50ef8eb9 1175 foreach ($this->_dependencies as $dependentOn => $elements){
46e648b6 1176 $js .= "'$dependentOn'".' : {dependents :[';
50ef8eb9 1177 foreach ($elements as $element){
11f260f4 1178 $elementNames = $this->_getElNamesRecursive($element['dependent']);
1179 foreach ($elementNames as $dependent){
1180 if ($dependent != $dependentOn) {
1181 $js.="'".$dependent."', ";
1182 }
1183 }
50ef8eb9 1184 }
1185 $js=rtrim($js, ', ');
1186 $js .= "],\n";
e24b7f85 1187 $js .= "condition : '{$element['condition']}',\n";
1188 $js .= "value : '{$element['value']}'},\n";
50ef8eb9 1189
1190 };
1191 $js=rtrim($js, ",\n");
1192 $js .= '};'."\n";
d01a38cb 1193 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
5e87b920 1194 $js .='//]]>'."\n";
50ef8eb9 1195 $js .='</script>'."\n";
1196 return $js;
bb40325e 1197 }
d01a38cb 1198
1199 function _getElNamesRecursive(&$element, $group=null){
1200 if ($group==null){
9403060a 1201 $el = $this->getElement($element);
d01a38cb 1202 } else {
9403060a 1203 $el = &$element;
d01a38cb 1204 }
1205 if (is_a($el, 'HTML_QuickForm_group')){
9403060a 1206 $group = $el;
1207 $elsInGroup = $group->getElements();
1208 $elNames = array();
d01a38cb 1209 foreach ($elsInGroup as $elInGroup){
1210 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup, $group));
1211 }
1212 }else{
9403060a 1213 if ($group != null){
1214 $elNames = array($group->getElementName($el->getName()));
1215 } elseif (is_a($el, 'HTML_QuickForm_header')) {
1216 return null;
2dbd6409 1217 } elseif (method_exists($el, 'getPrivateName')) {
1218 return array($el->getPrivateName());
d01a38cb 1219 } else {
9403060a 1220 $elNames = array($el->getName());
d01a38cb 1221 }
1222 }
1223 return $elNames;
1224
50ef8eb9 1225 }
6e372b25 1226 /**
1227 * Adds a dependency for $elementName which will be disabled if $condition is met.
9403060a 1228 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1229 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
6e372b25 1230 * is checked. If $condition is something else then it is checked to see if the value
1231 * of the $dependentOn element is equal to $condition.
1232 *
1233 * @param string $elementName the name of the element which will be disabled
1234 * @param string $dependentOn the name of the element whose state will be checked for
1235 * condition
1236 * @param string $condition the condition to check
19110c57 1237 * @param mixed $value used in conjunction with condition.
6e372b25 1238 */
e24b7f85 1239 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value=null){
11f260f4 1240 $this->_dependencies[$dependentOn][] = array('dependent'=>$elementName,
e24b7f85 1241 'condition'=>$condition, 'value'=>$value);
bb40325e 1242 }
a23f0aaf 1243 function registerNoSubmitButton($buttonname){
1244 $this->_noSubmitButtons[]=$buttonname;
1245 }
1246 function isNoSubmitButton($buttonname){
1247 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
19110c57 1248 }
1249 function _registerCancelButton($addfieldsname){
1250 $this->_cancelButtons[]=$addfieldsname;
1251 }
da6f8763 1252}
1253
e24b7f85 1254
da6f8763 1255/**
7f40a229 1256 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
da6f8763 1257 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
7f40a229 1258 *
da6f8763 1259 * Stylesheet is part of standard theme and should be automatically included.
1260 *
1261 * @author Jamie Pratt <me@jamiep.org>
1262 * @license gpl license
1263 */
7f40a229 1264class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
da6f8763 1265
1266 /**
1267 * Element template array
1268 * @var array
1269 * @access private
1270 */
1271 var $_elementTemplates;
49c53687 1272 /**
1273 * Template used when opening a hidden fieldset
1274 * (i.e. a fieldset that is opened when there is no header element)
1275 * @var string
1276 * @access private
1277 */
1278 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\">";
19194f82 1279 /**
1280 * Header Template string
1281 * @var string
1282 * @access private
1283 */
1284 var $_headerTemplate =
a23f0aaf 1285 "\n\t\t<legend>{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div>\n\t\t";
7f40a229 1286
49c53687 1287 /**
1288 * Template used when closing a fieldset
1289 * @var string
1290 * @access private
1291 */
1292 var $_closeFieldsetTemplate = "\n\t\t</fieldset>";
42f248e6 1293
49c53687 1294 /**
1295 * Required Note template string
1296 * @var string
1297 * @access private
1298 */
7f40a229 1299 var $_requiredNoteTemplate =
49c53687 1300 "\n\t\t<div class=\"fdescription\">{requiredNote}</div>";
7f40a229 1301
19194f82 1302 var $_advancedElements = array();
1303
1304 /**
1305 * Whether to display advanced elements (on page load)
1306 *
1307 * @var integer 1 means show 0 means hide
1308 */
1309 var $_showAdvanced;
1310
7f40a229 1311 function MoodleQuickForm_Renderer(){
42f248e6 1312 // switch next two lines for ol li containers for form items.
49c53687 1313 // $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 1314 $this->_elementTemplates = array(
10a31031 1315 'default'=>"\n\t\t<div class=\"fitem {advanced}<!-- BEGIN required --> required<!-- END required -->\"><div class=\"fitemtitle\"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg}</label>{help}</div><div class=\"felement {type}<!-- BEGIN error --> error<!-- END error -->\"><!-- BEGIN error --><span class=\"error\">{error}</span><br /><!-- END error -->{element}</div></div>",
1316 'fieldset'=>"\n\t\t<div class=\"fitem {advanced}<!-- BEGIN required --> required<!-- END required -->\"><div class=\"fitemtitle\"><div class=\"fgrouplabel\">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg}</div>{help}</div><fieldset class=\"felement {type}<!-- BEGIN error --> error<!-- END error -->\"><!-- BEGIN error --><span class=\"error\">{error}</span><br /><!-- END error -->{element}</fieldset></div>",
1317 'static'=>"\n\t\t<div class=\"fitem {advanced}<!-- BEGIN required --> required<!-- END required -->\"><div class=\"fitemtitle\"><div class=\"fstaticlabel\">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg}</div>{help}</div><div class=\"felement {type}<!-- BEGIN error --> error<!-- END error -->\"><!-- BEGIN error --><span class=\"error\">{error}</span><br /><!-- END error -->{element}</div></div>");
da6f8763 1318
1319 parent::HTML_QuickForm_Renderer_Tableless();
1320 }
7f40a229 1321
19194f82 1322 function setAdvancedElements($elements){
1323 $this->_advancedElements = $elements;
1324 }
1325
1326 /**
1327 * What to do when starting the form
1328 *
1329 * @param MoodleQuickForm $form
1330 */
da6f8763 1331 function startForm(&$form){
9403060a 1332 $this->_reqHTML = $form->getReqHTML();
1333 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
19194f82 1334 $this->_advancedHTML = $form->getAdvancedHTML();
1335 $this->_showAdvanced = $form->getShowAdvanced();
da6f8763 1336 parent::startForm($form);
1337 }
7f40a229 1338
da6f8763 1339 function startGroup(&$group, $required, $error){
1340 if (method_exists($group, 'getElementTemplateType')){
e249661f 1341 $html = $this->_elementTemplates[$group->getElementTemplateType()];
da6f8763 1342 }else{
1343 $html = $this->_elementTemplates['default'];
7f40a229 1344
da6f8763 1345 }
19194f82 1346 if ($this->_showAdvanced){
1347 $advclass = ' advanced';
1348 } else {
1349 $advclass = ' advanced hide';
1350 }
1351 if (isset($this->_advancedElements[$group->getName()])){
1352 $html =str_replace(' {advanced}', $advclass, $html);
1353 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1354 } else {
1355 $html =str_replace(' {advanced}', '', $html);
1356 $html =str_replace('{advancedimg}', '', $html);
1357 }
da6f8763 1358 if (method_exists($group, 'getHelpButton')){
1359 $html =str_replace('{help}', $group->getHelpButton(), $html);
1360 }else{
1361 $html =str_replace('{help}', '', $html);
da6f8763 1362 }
e7004d05 1363 $html =str_replace('{name}', $group->getName(), $html);
49c53687 1364 $html =str_replace('{type}', 'fgroup', $html);
7f40a229 1365
da6f8763 1366 $this->_templates[$group->getName()]=$html;
1367 // Fix for bug in tableless quickforms that didn't allow you to stop a
1368 // fieldset before a group of elements.
1369 // if the element name indicates the end of a fieldset, close the fieldset
1370 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1371 && $this->_fieldsetsOpen > 0
1372 ) {
1373 $this->_html .= $this->_closeFieldsetTemplate;
1374 $this->_fieldsetsOpen--;
1375 }
1376 parent::startGroup($group, $required, $error);
1377 }
7f40a229 1378
da6f8763 1379 function renderElement(&$element, $required, $error){
86aab05c 1380 //manipulate id of all elements before rendering
1381 if (!is_null($element->getAttribute('id'))) {
1382 $id = $element->getAttribute('id');
1383 } else {
1384 $id = $element->getName();
1385 }
1386 //strip qf_ prefix and replace '[' with '_' and strip ']'
1387 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1388 if (strpos($id, 'id_') !== 0){
1389 $element->updateAttributes(array('id'=>'id_'.$id));
1390 }
1391
1392 //adding stuff to place holders in template
da6f8763 1393 if (method_exists($element, 'getElementTemplateType')){
1394 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1395 }else{
1396 $html = $this->_elementTemplates['default'];
19194f82 1397 }
1398 if ($this->_showAdvanced){
1399 $advclass = ' advanced';
1400 } else {
1401 $advclass = ' advanced hide';
1402 }
1403 if (isset($this->_advancedElements[$element->getName()])){
1404 $html =str_replace(' {advanced}', $advclass, $html);
1405 } else {
1406 $html =str_replace(' {advanced}', '', $html);
1407 }
1408 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1409 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1410 } else {
1411 $html =str_replace('{advancedimg}', '', $html);
da6f8763 1412 }
49c53687 1413 $html =str_replace('{type}', 'f'.$element->getType(), $html);
e7004d05 1414 $html =str_replace('{name}', $element->getName(), $html);
da6f8763 1415 if (method_exists($element, 'getHelpButton')){
9403060a 1416 $html = str_replace('{help}', $element->getHelpButton(), $html);
da6f8763 1417 }else{
9403060a 1418 $html = str_replace('{help}', '', $html);
7f40a229 1419
da6f8763 1420 }
86aab05c 1421
9403060a 1422 $this->_templates[$element->getName()] = $html;
86aab05c 1423
da6f8763 1424 parent::renderElement($element, $required, $error);
1425 }
19194f82 1426
bb40325e 1427 function finishForm(&$form){
1428 parent::finishForm($form);
d01a38cb 1429 // add a lockoptions script
bb40325e 1430 if ('' != ($script = $form->getLockOptionEndScript())) {
1431 $this->_html = $this->_html . "\n" . $script;
1432 }
1433 }
19194f82 1434 /**
1435 * Called when visiting a header element
1436 *
1437 * @param object An HTML_QuickForm_header element being visited
1438 * @access public
1439 * @return void
1440 */
1441 function renderHeader(&$header) {
1442 $name = $header->getName();
1443
1444 $id = empty($name) ? '' : ' id="' . $name . '"';
78354cec 1445 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
19194f82 1446 if (is_null($header->_text)) {
1447 $header_html = '';
1448 } elseif (!empty($name) && isset($this->_templates[$name])) {
1449 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
1450 } else {
1451 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
1452 }
1453
1454 if (isset($this->_advancedElements[$name])){
1455 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
1456 } else {
1457 $header_html =str_replace('{advancedimg}', '', $header_html);
1458 }
1459 $elementName='mform_showadvanced';
1460 if ($this->_showAdvanced==0){
1461 $buttonlabel = get_string('showadvanced', 'form');
1462 } else {
1463 $buttonlabel = get_string('hideadvanced', 'form');
1464 }
1465
1466 if (isset($this->_advancedElements[$name])){
1467 $showtext="'".get_string('showadvanced', 'form')."'";
1468 $hidetext="'".get_string('hideadvanced', 'form')."'";
1469 //onclick returns false so if js is on then page is not submitted.
1470 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1471 $button = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" onclick="'.$onclick.'" />';
1472 $header_html =str_replace('{button}', $button, $header_html);
1473 } else {
1474 $header_html =str_replace('{button}', '', $header_html);
1475 }
1476
1477 if ($this->_fieldsetsOpen > 0) {
1478 $this->_html .= $this->_closeFieldsetTemplate;
1479 $this->_fieldsetsOpen--;
1480 }
1481
1482 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
1483 if ($this->_showAdvanced){
1484 $advclass = ' class="advanced"';
1485 } else {
1486 $advclass = ' class="advanced hide"';
1487 }
1488 if (isset($this->_advancedElements[$name])){
1489 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1490 } else {
1491 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1492 }
1493 $this->_html .= $openFieldsetTemplate . $header_html;
1494 $this->_fieldsetsOpen++;
1495 } // end func renderHeader
1496
1497 function getStopFieldsetElements(){
1498 return $this->_stopFieldsetElements;
1499 }
da6f8763 1500}
1501
da6f8763 1502
9403060a 1503$GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
da6f8763 1504
7f40a229 1505MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1506MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1507MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1508MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1509MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1510MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1511MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1512MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1513MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1514MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1515MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
effa85f4 1516MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
7f40a229 1517MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1518MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
e2294b98 1519MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1520MoodleQuickForm::registerElementType('modgroupmode', "$CFG->libdir/form/modgroupmode.php", 'MoodleQuickForm_modgroupmode');
e0f40684 1521MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
d4fe14d3 1522MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
19110c57 1523MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3c7656b4 1524MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1525MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
a23f0aaf 1526MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1527MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
9e93222d 1528MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
111be766 1529MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
9aa022fe 1530?>