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