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