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