Changes to the redirects.
[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
98af2d1d 887 $emptyarray = array();
0ffb4cc7 888 foreach (array_keys($this->_elements) as $key) {
889 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
98af2d1d 890 $value = $this->_elements[$key]->exportValue($emptyarray, true);
0ffb4cc7 891 } else {
892 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
893 }
894
895 if (is_array($value)) {
896 // This shit throws a bogus warning in PHP 4.3.x
897 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
898 }
899 }
900 } else {
901 if (!is_array($elementList)) {
902 $elementList = array_map('trim', explode(',', $elementList));
903 }
904 foreach ($elementList as $elementName) {
905 $value = $this->exportValue($elementName);
906 if (PEAR::isError($value)) {
907 return $value;
908 }
909 $unfiltered[$elementName] = $value;
910 }
911 }
7f40a229 912
da6f8763 913 if ($addslashes){
0ffb4cc7 914 return $this->_recursiveFilter('addslashes', $unfiltered);
da6f8763 915 } else {
916 return $unfiltered;
917 }
918 }
f07b9627 919 /**
920 * Adds a validation rule for the given field
921 *
922 * If the element is in fact a group, it will be considered as a whole.
923 * To validate grouped elements as separated entities,
924 * use addGroupRule instead of addRule.
925 *
926 * @param string $element Form element name
927 * @param string $message Message to display for invalid data
928 * @param string $type Rule type, use getRegisteredRules() to get types
929 * @param string $format (optional)Required for extra rule data
930 * @param string $validation (optional)Where to perform validation: "server", "client"
931 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
932 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
933 * @since 1.0
934 * @access public
935 * @throws HTML_QuickForm_Error
936 */
937 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
938 {
939 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
940 if ($validation == 'client') {
941 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
942 }
943
944 } // end func addRule
945 /**
946 * Adds a validation rule for the given group of elements
947 *
948 * Only groups with a name can be assigned a validation rule
949 * Use addGroupRule when you need to validate elements inside the group.
950 * Use addRule if you need to validate the group as a whole. In this case,
951 * the same rule will be applied to all elements in the group.
952 * Use addRule if you need to validate the group against a function.
953 *
954 * @param string $group Form group name
955 * @param mixed $arg1 Array for multiple elements or error message string for one element
956 * @param string $type (optional)Rule type use getRegisteredRules() to get types
957 * @param string $format (optional)Required for extra rule data
958 * @param int $howmany (optional)How many valid elements should be in the group
959 * @param string $validation (optional)Where to perform validation: "server", "client"
960 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
961 * @since 2.5
962 * @access public
963 * @throws HTML_QuickForm_Error
964 */
965 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
966 {
967 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
968 if (is_array($arg1)) {
969 foreach ($arg1 as $elementIndex => $rules) {
970 foreach ($rules as $rule) {
971 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
972
973 if ('client' == $validation) {
974 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
975 }
976 }
977 }
978 } elseif (is_string($arg1)) {
979
980 if ($validation == 'client') {
981 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $formname . '; } catch(e) { return true; } return myValidator(this);'));
982 }
983 }
984 } // end func addGroupRule
985
986 // }}}
5bc97c98 987 /**
988 * Returns the client side validation script
989 *
990 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
991 * and slightly modified to run rules per-element
992 * Needed to override this because of an error with client side validation of grouped elements.
993 *
994 * @access public
995 * @return string Javascript to perform validation, empty string if no 'client' rules were added
996 */
997 function getValidationScript()
998 {
999 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1000 return '';
1001 }
1002
1003 include_once('HTML/QuickForm/RuleRegistry.php');
1004 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1005 $test = array();
1006 $js_escape = array(
1007 "\r" => '\r',
1008 "\n" => '\n',
1009 "\t" => '\t',
1010 "'" => "\\'",
1011 '"' => '\"',
1012 '\\' => '\\\\'
1013 );
1014
1015 foreach ($this->_rules as $elementName => $rules) {
1016 foreach ($rules as $rule) {
1017 if ('client' == $rule['validation']) {
da1320da 1018 unset($element); //TODO: find out how to properly initialize it
5bc97c98 1019
1020 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1021 $rule['message'] = strtr($rule['message'], $js_escape);
1022
1023 if (isset($rule['group'])) {
1024 $group =& $this->getElement($rule['group']);
1025 // No JavaScript validation for frozen elements
1026 if ($group->isFrozen()) {
1027 continue 2;
1028 }
1029 $elements =& $group->getElements();
1030 foreach (array_keys($elements) as $key) {
1031 if ($elementName == $group->getElementName($key)) {
1032 $element =& $elements[$key];
1033 break;
1034 }
1035 }
1036 } elseif ($dependent) {
1037 $element = array();
1038 $element[] =& $this->getElement($elementName);
1039 foreach ($rule['dependent'] as $idx => $elName) {
1040 $element[] =& $this->getElement($elName);
1041 }
1042 } else {
1043 $element =& $this->getElement($elementName);
1044 }
1045 // No JavaScript validation for frozen elements
1046 if (is_object($element) && $element->isFrozen()) {
1047 continue 2;
1048 } elseif (is_array($element)) {
1049 foreach (array_keys($element) as $key) {
1050 if ($element[$key]->isFrozen()) {
1051 continue 3;
1052 }
1053 }
1054 }
1055 // Fix for bug displaying errors for elements in a group
1056 //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
1057 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1058 $test[$elementName][1]=$element;
1059 //end of fix
1060 }
1061 }
1062 }
1063 $js = '
1064<script type="text/javascript">
1065//<![CDATA[
1cbb09f1 1066
1067var skipClientValidation = false;
1068
5bc97c98 1069function qf_errorHandler(element, _qfMsg) {
1070 div = element.parentNode;
1071 if (_qfMsg != \'\') {
e35c9eeb 1072 var errorSpan = document.getElementById(\'id_error_\'+element.name);
e7004d05 1073 if (!errorSpan) {
1074 errorSpan = document.createElement("span");
e35c9eeb 1075 errorSpan.id = \'id_error_\'+element.name;
1076 errorSpan.className = "error";
fed13a5e 1077 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
5bc97c98 1078 }
fed13a5e 1079
e7004d05 1080 while (errorSpan.firstChild) {
1081 errorSpan.removeChild(errorSpan.firstChild);
5bc97c98 1082 }
2c412890 1083
e7004d05 1084 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
e35c9eeb 1085 errorSpan.appendChild(document.createElement("br"));
5bc97c98 1086
1087 if (div.className.substr(div.className.length - 6, 6) != " error"
1088 && div.className != "error") {
1089 div.className += " error";
1090 }
1091
1092 return false;
1093 } else {
e35c9eeb 1094 var errorSpan = document.getElementById(\'id_error_\'+element.name);
e7004d05 1095 if (errorSpan) {
1096 errorSpan.parentNode.removeChild(errorSpan);
5bc97c98 1097 }
1098
1099 if (div.className.substr(div.className.length - 6, 6) == " error") {
1100 div.className = div.className.substr(0, div.className.length - 6);
1101 } else if (div.className == "error") {
1102 div.className = "";
1103 }
1104
1105 return true;
1106 }
1107}';
1108 $validateJS = '';
1109 foreach ($test as $elementName => $jsandelement) {
1110 // Fix for bug displaying errors for elements in a group
1111 //unset($element);
1112 list($jsArr,$element)=$jsandelement;
1113 //end of fix
1114 $js .= '
f07b9627 1115function validate_' . $this->_formName . '_' . $elementName . '(element) {
5bc97c98 1116 var value = \'\';
1117 var errFlag = new Array();
1118 var _qfGroups = {};
1119 var _qfMsg = \'\';
1120 var frm = element.parentNode;
1121 while (frm && frm.nodeName != "FORM") {
1122 frm = frm.parentNode;
1123 }
1124' . join("\n", $jsArr) . '
1125 return qf_errorHandler(element, _qfMsg);
1126}
1127';
1128 $validateJS .= '
f07b9627 1129 ret = validate_' . $this->_formName . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;';
5bc97c98 1130 // Fix for bug displaying errors for elements in a group
1131 //unset($element);
1132 //$element =& $this->getElement($elementName);
1133 //end of fix
f07b9627 1134 $valFunc = 'validate_' . $this->_formName . '_' . $elementName . '(this)';
5bc97c98 1135 $onBlur = $element->getAttribute('onBlur');
1136 $onChange = $element->getAttribute('onChange');
1137 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1138 'onChange' => $onChange . $valFunc));
1139 }
e7004d05 1140// do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
5bc97c98 1141 $js .= '
f07b9627 1142function validate_' . $this->_formName . '(frm) {
1cbb09f1 1143 if (skipClientValidation) {
1144 return true;
1145 }
5bc97c98 1146 var ret = true;
0befbdfd 1147
1148 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1149
5bc97c98 1150' . $validateJS . ';
1151 return ret;
1152}
1153//]]>
1154</script>';
1155 return $js;
1156 } // end func getValidationScript
1157 function _setDefaultRuleMessages(){
1158 foreach ($this->_rules as $field => $rulesarr){
1159 foreach ($rulesarr as $key => $rule){
1160 if ($rule['message']===null){
1161 $a=new object();
1162 $a->format=$rule['format'];
1163 $str=get_string('err_'.$rule['type'], 'form', $a);
1164 if (strpos($str, '[[')!==0){
1165 $this->_rules[$field][$key]['message']=$str;
2c412890 1166 }
5bc97c98 1167 }
1168 }
1169 }
1170 }
bb40325e 1171
d01a38cb 1172 function getLockOptionEndScript(){
f4ba7e1a 1173 $js = '<script type="text/javascript">'."\n";
5e87b920 1174 $js .= '//<![CDATA['."\n";
271ffe3f 1175 $js .= "var ".$this->getAttribute('id')."items= {";
50ef8eb9 1176 foreach ($this->_dependencies as $dependentOn => $elements){
46e648b6 1177 $js .= "'$dependentOn'".' : {dependents :[';
50ef8eb9 1178 foreach ($elements as $element){
11f260f4 1179 $elementNames = $this->_getElNamesRecursive($element['dependent']);
1180 foreach ($elementNames as $dependent){
1181 if ($dependent != $dependentOn) {
1182 $js.="'".$dependent."', ";
1183 }
1184 }
50ef8eb9 1185 }
1186 $js=rtrim($js, ', ');
1187 $js .= "],\n";
e24b7f85 1188 $js .= "condition : '{$element['condition']}',\n";
1189 $js .= "value : '{$element['value']}'},\n";
50ef8eb9 1190
1191 };
1192 $js=rtrim($js, ",\n");
1193 $js .= '};'."\n";
d01a38cb 1194 $js .="lockoptionsallsetup('".$this->getAttribute('id')."');\n";
5e87b920 1195 $js .='//]]>'."\n";
50ef8eb9 1196 $js .='</script>'."\n";
1197 return $js;
bb40325e 1198 }
d01a38cb 1199
1200 function _getElNamesRecursive(&$element, $group=null){
1201 if ($group==null){
9403060a 1202 $el = $this->getElement($element);
d01a38cb 1203 } else {
9403060a 1204 $el = &$element;
d01a38cb 1205 }
1206 if (is_a($el, 'HTML_QuickForm_group')){
9403060a 1207 $group = $el;
1208 $elsInGroup = $group->getElements();
1209 $elNames = array();
d01a38cb 1210 foreach ($elsInGroup as $elInGroup){
1211 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup, $group));
1212 }
1213 }else{
9403060a 1214 if ($group != null){
1215 $elNames = array($group->getElementName($el->getName()));
1216 } elseif (is_a($el, 'HTML_QuickForm_header')) {
1217 return null;
2dbd6409 1218 } elseif (method_exists($el, 'getPrivateName')) {
1219 return array($el->getPrivateName());
d01a38cb 1220 } else {
9403060a 1221 $elNames = array($el->getName());
d01a38cb 1222 }
1223 }
1224 return $elNames;
1225
50ef8eb9 1226 }
6e372b25 1227 /**
1228 * Adds a dependency for $elementName which will be disabled if $condition is met.
9403060a 1229 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1230 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
6e372b25 1231 * is checked. If $condition is something else then it is checked to see if the value
1232 * of the $dependentOn element is equal to $condition.
1233 *
1234 * @param string $elementName the name of the element which will be disabled
1235 * @param string $dependentOn the name of the element whose state will be checked for
1236 * condition
1237 * @param string $condition the condition to check
19110c57 1238 * @param mixed $value used in conjunction with condition.
6e372b25 1239 */
e24b7f85 1240 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value=null){
11f260f4 1241 $this->_dependencies[$dependentOn][] = array('dependent'=>$elementName,
e24b7f85 1242 'condition'=>$condition, 'value'=>$value);
bb40325e 1243 }
a23f0aaf 1244 function registerNoSubmitButton($buttonname){
1245 $this->_noSubmitButtons[]=$buttonname;
1246 }
1247 function isNoSubmitButton($buttonname){
1248 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
19110c57 1249 }
1250 function _registerCancelButton($addfieldsname){
1251 $this->_cancelButtons[]=$addfieldsname;
1252 }
acc9c3e0 1253 /**
1254 * Displays elements without HTML input tags.
1255 * This method is different to freeze() in that it makes sure no hidden
1256 * elements are included in the form. And a 'hardFrozen' element's submitted value is
1257 * ignored.
1258 *
1259 * @param mixed $elementList array or string of element(s) to be frozen
1260 * @since 1.0
1261 * @access public
1262 * @throws HTML_QuickForm_Error
1263 */
1264 function hardFreeze($elementList=null)
1265 {
1266 if (!isset($elementList)) {
1267 $this->_freezeAll = true;
1268 $elementList = array();
1269 } else {
1270 if (!is_array($elementList)) {
1271 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
1272 }
1273 $elementList = array_flip($elementList);
1274 }
1275
1276 foreach (array_keys($this->_elements) as $key) {
1277 $name = $this->_elements[$key]->getName();
1278 if ($this->_freezeAll || isset($elementList[$name])) {
1279 $this->_elements[$key]->freeze();
1280 $this->_elements[$key]->setPersistantFreeze(false);
1281 unset($elementList[$name]);
1282 }
1283 }
1284
1285 if (!empty($elementList)) {
1286 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);
1287 }
1288 return true;
1289 } // end func hardFreeze
1290
1291 // }}}
da6f8763 1292}
1293
e24b7f85 1294
da6f8763 1295/**
7f40a229 1296 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
da6f8763 1297 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
7f40a229 1298 *
da6f8763 1299 * Stylesheet is part of standard theme and should be automatically included.
1300 *
1301 * @author Jamie Pratt <me@jamiep.org>
1302 * @license gpl license
1303 */
7f40a229 1304class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
da6f8763 1305
1306 /**
1307 * Element template array
1308 * @var array
1309 * @access private
1310 */
1311 var $_elementTemplates;
49c53687 1312 /**
1313 * Template used when opening a hidden fieldset
1314 * (i.e. a fieldset that is opened when there is no header element)
1315 * @var string
1316 * @access private
1317 */
1318 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\">";
19194f82 1319 /**
1320 * Header Template string
1321 * @var string
1322 * @access private
1323 */
1324 var $_headerTemplate =
a23f0aaf 1325 "\n\t\t<legend>{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div>\n\t\t";
7f40a229 1326
49c53687 1327 /**
1328 * Template used when closing a fieldset
1329 * @var string
1330 * @access private
1331 */
1332 var $_closeFieldsetTemplate = "\n\t\t</fieldset>";
42f248e6 1333
49c53687 1334 /**
1335 * Required Note template string
1336 * @var string
1337 * @access private
1338 */
7f40a229 1339 var $_requiredNoteTemplate =
49c53687 1340 "\n\t\t<div class=\"fdescription\">{requiredNote}</div>";
7f40a229 1341
19194f82 1342 var $_advancedElements = array();
1343
1344 /**
1345 * Whether to display advanced elements (on page load)
1346 *
1347 * @var integer 1 means show 0 means hide
1348 */
1349 var $_showAdvanced;
1350
7f40a229 1351 function MoodleQuickForm_Renderer(){
42f248e6 1352 // switch next two lines for ol li containers for form items.
49c53687 1353 // $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 1354 $this->_elementTemplates = array(
10a31031 1355 '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>",
1356 '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>",
1357 '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 1358
1359 parent::HTML_QuickForm_Renderer_Tableless();
1360 }
7f40a229 1361
19194f82 1362 function setAdvancedElements($elements){
1363 $this->_advancedElements = $elements;
1364 }
1365
1366 /**
1367 * What to do when starting the form
1368 *
1369 * @param MoodleQuickForm $form
1370 */
da6f8763 1371 function startForm(&$form){
9403060a 1372 $this->_reqHTML = $form->getReqHTML();
1373 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
19194f82 1374 $this->_advancedHTML = $form->getAdvancedHTML();
1375 $this->_showAdvanced = $form->getShowAdvanced();
da6f8763 1376 parent::startForm($form);
1377 }
7f40a229 1378
da6f8763 1379 function startGroup(&$group, $required, $error){
1380 if (method_exists($group, 'getElementTemplateType')){
e249661f 1381 $html = $this->_elementTemplates[$group->getElementTemplateType()];
da6f8763 1382 }else{
1383 $html = $this->_elementTemplates['default'];
7f40a229 1384
da6f8763 1385 }
19194f82 1386 if ($this->_showAdvanced){
1387 $advclass = ' advanced';
1388 } else {
1389 $advclass = ' advanced hide';
1390 }
1391 if (isset($this->_advancedElements[$group->getName()])){
1392 $html =str_replace(' {advanced}', $advclass, $html);
1393 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1394 } else {
1395 $html =str_replace(' {advanced}', '', $html);
1396 $html =str_replace('{advancedimg}', '', $html);
1397 }
da6f8763 1398 if (method_exists($group, 'getHelpButton')){
1399 $html =str_replace('{help}', $group->getHelpButton(), $html);
1400 }else{
1401 $html =str_replace('{help}', '', $html);
da6f8763 1402 }
e7004d05 1403 $html =str_replace('{name}', $group->getName(), $html);
49c53687 1404 $html =str_replace('{type}', 'fgroup', $html);
7f40a229 1405
da6f8763 1406 $this->_templates[$group->getName()]=$html;
1407 // Fix for bug in tableless quickforms that didn't allow you to stop a
1408 // fieldset before a group of elements.
1409 // if the element name indicates the end of a fieldset, close the fieldset
1410 if ( in_array($group->getName(), $this->_stopFieldsetElements)
1411 && $this->_fieldsetsOpen > 0
1412 ) {
1413 $this->_html .= $this->_closeFieldsetTemplate;
1414 $this->_fieldsetsOpen--;
1415 }
1416 parent::startGroup($group, $required, $error);
1417 }
7f40a229 1418
da6f8763 1419 function renderElement(&$element, $required, $error){
86aab05c 1420 //manipulate id of all elements before rendering
1421 if (!is_null($element->getAttribute('id'))) {
1422 $id = $element->getAttribute('id');
1423 } else {
1424 $id = $element->getName();
1425 }
1426 //strip qf_ prefix and replace '[' with '_' and strip ']'
1427 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
1428 if (strpos($id, 'id_') !== 0){
1429 $element->updateAttributes(array('id'=>'id_'.$id));
1430 }
1431
1432 //adding stuff to place holders in template
da6f8763 1433 if (method_exists($element, 'getElementTemplateType')){
1434 $html = $this->_elementTemplates[$element->getElementTemplateType()];
1435 }else{
1436 $html = $this->_elementTemplates['default'];
19194f82 1437 }
1438 if ($this->_showAdvanced){
1439 $advclass = ' advanced';
1440 } else {
1441 $advclass = ' advanced hide';
1442 }
1443 if (isset($this->_advancedElements[$element->getName()])){
1444 $html =str_replace(' {advanced}', $advclass, $html);
1445 } else {
1446 $html =str_replace(' {advanced}', '', $html);
1447 }
1448 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
1449 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
1450 } else {
1451 $html =str_replace('{advancedimg}', '', $html);
da6f8763 1452 }
49c53687 1453 $html =str_replace('{type}', 'f'.$element->getType(), $html);
e7004d05 1454 $html =str_replace('{name}', $element->getName(), $html);
da6f8763 1455 if (method_exists($element, 'getHelpButton')){
9403060a 1456 $html = str_replace('{help}', $element->getHelpButton(), $html);
da6f8763 1457 }else{
9403060a 1458 $html = str_replace('{help}', '', $html);
7f40a229 1459
da6f8763 1460 }
86aab05c 1461
9403060a 1462 $this->_templates[$element->getName()] = $html;
86aab05c 1463
da6f8763 1464 parent::renderElement($element, $required, $error);
1465 }
19194f82 1466
bb40325e 1467 function finishForm(&$form){
1468 parent::finishForm($form);
d01a38cb 1469 // add a lockoptions script
bb40325e 1470 if ('' != ($script = $form->getLockOptionEndScript())) {
1471 $this->_html = $this->_html . "\n" . $script;
1472 }
1473 }
19194f82 1474 /**
1475 * Called when visiting a header element
1476 *
1477 * @param object An HTML_QuickForm_header element being visited
1478 * @access public
1479 * @return void
1480 */
1481 function renderHeader(&$header) {
1482 $name = $header->getName();
1483
1484 $id = empty($name) ? '' : ' id="' . $name . '"';
78354cec 1485 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
19194f82 1486 if (is_null($header->_text)) {
1487 $header_html = '';
1488 } elseif (!empty($name) && isset($this->_templates[$name])) {
1489 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
1490 } else {
1491 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
1492 }
1493
1494 if (isset($this->_advancedElements[$name])){
1495 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
1496 } else {
1497 $header_html =str_replace('{advancedimg}', '', $header_html);
1498 }
1499 $elementName='mform_showadvanced';
1500 if ($this->_showAdvanced==0){
1501 $buttonlabel = get_string('showadvanced', 'form');
1502 } else {
1503 $buttonlabel = get_string('hideadvanced', 'form');
1504 }
1505
1506 if (isset($this->_advancedElements[$name])){
1507 $showtext="'".get_string('showadvanced', 'form')."'";
1508 $hidetext="'".get_string('hideadvanced', 'form')."'";
1509 //onclick returns false so if js is on then page is not submitted.
1510 $onclick = 'return showAdvancedOnClick(this, '.$hidetext.', '.$showtext.');';
1511 $button = '<input name="'.$elementName.'" value="'.$buttonlabel.'" type="submit" onclick="'.$onclick.'" />';
1512 $header_html =str_replace('{button}', $button, $header_html);
1513 } else {
1514 $header_html =str_replace('{button}', '', $header_html);
1515 }
1516
1517 if ($this->_fieldsetsOpen > 0) {
1518 $this->_html .= $this->_closeFieldsetTemplate;
1519 $this->_fieldsetsOpen--;
1520 }
1521
1522 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
1523 if ($this->_showAdvanced){
1524 $advclass = ' class="advanced"';
1525 } else {
1526 $advclass = ' class="advanced hide"';
1527 }
1528 if (isset($this->_advancedElements[$name])){
1529 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
1530 } else {
1531 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
1532 }
1533 $this->_html .= $openFieldsetTemplate . $header_html;
1534 $this->_fieldsetsOpen++;
1535 } // end func renderHeader
1536
1537 function getStopFieldsetElements(){
1538 return $this->_stopFieldsetElements;
1539 }
da6f8763 1540}
1541
da6f8763 1542
9403060a 1543$GLOBALS['_HTML_QuickForm_default_renderer'] =& new MoodleQuickForm_Renderer();
da6f8763 1544
7f40a229 1545MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
1546MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
1547MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
1548MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
1549MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
1550MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
1551MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
1552MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
1553MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
1554MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
1555MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
effa85f4 1556MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
7f40a229 1557MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
1558MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
e2294b98 1559MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
1560MoodleQuickForm::registerElementType('modgroupmode', "$CFG->libdir/form/modgroupmode.php", 'MoodleQuickForm_modgroupmode');
e0f40684 1561MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
d4fe14d3 1562MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
19110c57 1563MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
3c7656b4 1564MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
1565MoodleQuickForm::registerElementType('choosecoursefile', "$CFG->libdir/form/choosecoursefile.php", 'MoodleQuickForm_choosecoursefile');
a23f0aaf 1566MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
1567MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
9e93222d 1568MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
111be766 1569MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
9aa022fe 1570?>