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