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