Fix regression in r49790, weird spacing for Gadgets and Skin tab.
[lhc/web/wiklou.git] / includes / HTMLForm.php
1 <?php
2
3 class HTMLForm {
4
5 static $jsAdded = false;
6
7 /* The descriptor is an array of arrays.
8 i.e. array(
9 'fieldname' => array( 'section' => 'section/subsection',
10 properties... ),
11 ...
12 )
13 */
14
15 static $typeMappings = array(
16 'text' => 'HTMLTextField',
17 'select' => 'HTMLSelectField',
18 'radio' => 'HTMLRadioField',
19 'multiselect' => 'HTMLMultiSelectField',
20 'check' => 'HTMLCheckField',
21 'toggle' => 'HTMLCheckField',
22 'int' => 'HTMLIntField',
23 'info' => 'HTMLInfoField',
24 'selectorother' => 'HTMLSelectOrOtherField',
25 );
26
27 function __construct( $descriptor, $messagePrefix ) {
28 $this->mMessagePrefix = $messagePrefix;
29
30 // Expand out into a tree.
31 $loadedDescriptor = array();
32 $this->mFlatFields = array();
33
34 foreach( $descriptor as $fieldname => $info ) {
35 $section = '';
36 if ( isset( $info['section'] ) )
37 $section = $info['section'];
38
39 $info['name'] = $fieldname;
40
41 $field = $this->loadInputFromParameters( $info );
42 $field->mParent = $this;
43
44 $setSection =& $loadedDescriptor;
45 if ($section) {
46 $sectionParts = explode( '/', $section );
47
48 while( count($sectionParts) ) {
49 $newName = array_shift( $sectionParts );
50
51 if ( !isset($setSection[$newName]) ) {
52 $setSection[$newName] = array();
53 }
54
55 $setSection =& $setSection[$newName];
56 }
57 }
58
59 $setSection[$fieldname] = $field;
60 $this->mFlatFields[$fieldname] = $field;
61 }
62
63 $this->mFieldTree = $loadedDescriptor;
64
65 $this->mShowReset = true;
66 }
67
68 static function addJS() {
69 if (self::$jsAdded) return;
70
71 global $wgOut, $wgStylePath;
72
73 $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
74 }
75
76 static function loadInputFromParameters( $descriptor ) {
77 if ( isset( $descriptor['class'] ) ) {
78 $class = $descriptor['class'];
79 } elseif ( isset( $descriptor['type'] ) ) {
80 $class = self::$typeMappings[$descriptor['type']];
81 $descriptor['class'] = $class;
82 }
83
84 if (!$class) {
85 throw new MWException( "Descriptor with no class: ".print_r( $descriptor, true ) );
86 }
87
88 $obj = new $class( $descriptor );
89
90 return $obj;
91 }
92
93 function show() {
94 $html = '';
95
96 self::addJS();
97
98 // Load data from the request.
99 $this->loadData();
100
101 // Try a submission
102 global $wgUser, $wgRequest;
103 $editToken = $wgRequest->getVal( 'wpEditToken' );
104
105 $result = false;
106 if ( $wgUser->matchEditToken( $editToken ) )
107 $result = $this->trySubmit();
108
109 if ($result === true)
110 return $result;
111
112 // Display form.
113 $this->displayForm( $result );
114 }
115
116 /** Return values:
117 * TRUE == Successful submission
118 * FALSE == No submission attempted
119 * Anything else == Error to display.
120 */
121 function trySubmit() {
122 // Check for validation
123 foreach( $this->mFlatFields as $fieldname => $field ) {
124 if ( !empty($field->mParams['nodata']) ) continue;
125 if ( $field->validate( $this->mFieldData[$fieldname],
126 $this->mFieldData ) !== true ) {
127 return isset($this->mValidationErrorMessage) ?
128 $this->mValidationErrorMessage : array( 'htmlform-invalid-input' );
129 }
130 }
131
132 $callback = $this->mSubmitCallback;
133
134 $data = $this->filterDataForSubmit( $this->mFieldData );
135
136 $res = call_user_func( $callback, $data );
137
138 return $res;
139 }
140
141 function setSubmitCallback( $cb ) {
142 $this->mSubmitCallback = $cb;
143 }
144
145 function setValidationErrorMessage( $msg ) {
146 $this->mValidationErrorMessage = $msg;
147 }
148
149 function displayForm( $submitResult ) {
150 global $wgOut;
151
152 if ( $submitResult !== false ) {
153 $this->displayErrors( $submitResult );
154 }
155
156 $html = $this->getBody();
157
158 // Hidden fields
159 $html .= $this->getHiddenFields();
160
161 // Buttons
162 $html .= $this->getButtons();
163
164 $html = $this->wrapForm( $html );
165
166 $wgOut->addHTML( $html );
167 }
168
169 function wrapForm( $html ) {
170 return Xml::tags( 'form',
171 array(
172 'action' => $this->getTitle()->getFullURL(),
173 'method' => 'post',
174 ),
175 $html );
176 }
177
178 function getHiddenFields() {
179 global $wgUser;
180 $html = '';
181
182 $html .= Xml::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
183 $html .= Xml::hidden( 'title', $this->getTitle() ) . "\n";
184
185 return $html;
186 }
187
188 function getButtons() {
189 $html = '';
190
191 $attribs = array();
192
193 if ( isset($this->mSubmitID) )
194 $attribs['id'] = $this->mSubmitID;
195
196 $attribs['class'] = 'mw-htmlform-submit';
197
198 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
199
200 if ($this->mShowReset) {
201 $html .= Xml::element( 'input',
202 array( 'type' => 'reset',
203 'value' => wfMsg('htmlform-reset')
204 ) ) . "\n";
205 }
206
207 return $html;
208 }
209
210 function getBody() {
211 return $this->displaySection( $this->mFieldTree );
212 }
213
214 function displayErrors( $errors ) {
215 if ( is_array( $errors ) ) {
216 $errorstr = $this->formatErrors( $errors );
217 } else {
218 $errorstr = $errors;
219 }
220
221 $errorstr = Xml::tags( 'div', array( 'class' => 'error' ), $errorstr );
222
223 global $wgOut;
224 $wgOut->addHTML( $errorstr );
225 }
226
227 static function formatErrors( $errors ) {
228 $errorstr = '';
229 foreach ( $errors as $error ) {
230 if (is_array($error)) {
231 $msg = array_shift($error);
232 } else {
233 $msg = $error;
234 $error = array();
235 }
236 $errorstr .= Xml::tags( 'li',
237 null,
238 wfMsgExt( $msg, array( 'parseinline' ), $error )
239 );
240 }
241
242 $errorstr = Xml::tags( 'ul', null, $errorstr );
243
244 return $errorstr;
245 }
246
247 function setSubmitText( $t ) {
248 $this->mSubmitText = $t;
249 }
250
251 function getSubmitText() {
252 return isset($this->mSubmitText) ? $this->mSubmitText : wfMsg('htmlform-submit');
253 }
254
255 function setSubmitID( $t ) {
256 $this->mSubmitID = $t;
257 }
258
259 function setMessagePrefix( $p ) {
260 $this->mMessagePrefix = $p;
261 }
262
263 function setTitle( $t ) {
264 $this->mTitle = $t;
265 }
266
267 function getTitle() {
268 return $this->mTitle;
269 }
270
271 function displaySection( $fields ) {
272 $tableHtml = '';
273 $subsectionHtml = '';
274 $hasLeftColumn = false;
275
276 foreach( $fields as $key => $value ) {
277 if ( is_object( $value ) ) {
278 $v = empty($value->mParams['nodata'])
279 ? $this->mFieldData[$key]
280 : $value->getDefault();
281 $tableHtml .= $value->getTableRow( $v );
282
283 if ($value->getLabel() != '&nbsp;')
284 $hasLeftColumn = true;
285 } elseif ( is_array( $value ) ) {
286 $section = $this->displaySection( $value );
287 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
288 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
289 }
290 }
291
292 $classes = array();
293 if (!$hasLeftColumn) // Avoid strange spacing when no labels exist
294 $classes[] = 'mw-htmlform-nolabel';
295 $classes = implode( ' ', $classes );
296
297 $tableHtml = "<table class='$classes'><tbody>\n$tableHtml\n</tbody></table>\n";
298
299 return $subsectionHtml . "\n" . $tableHtml;
300 }
301
302 function loadData() {
303 global $wgRequest;
304
305 $fieldData = array();
306
307 foreach( $this->mFlatFields as $fieldname => $field ) {
308 if ( !empty($field->mParams['nodata']) ) continue;
309 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
310 }
311
312 // Filter data.
313 foreach( $fieldData as $name => &$value ) {
314 $field = $this->mFlatFields[$name];
315 $value = $field->filter( $value, $this->mFlatFields );
316 }
317
318 $this->mFieldData = $fieldData;
319 }
320
321 function importData( $fieldData ) {
322 // Filter data.
323 foreach( $fieldData as $name => &$value ) {
324 $field = $this->mFlatFields[$name];
325 $value = $field->filter( $value, $this->mFlatFields );
326 }
327
328 foreach( $this->mFlatFields as $fieldname => $field ) {
329 if ( !isset($fieldData[$fieldname]) )
330 $fieldData[$fieldname] = $field->getDefault();
331 }
332
333 $this->mFieldData = $fieldData;
334 }
335
336 function suppressReset( $suppressReset = true ) {
337 $this->mShowReset = !$suppressReset;
338 }
339
340 function filterDataForSubmit( $data ) {
341 return $data;
342 }
343 }
344
345 abstract class HTMLFormField {
346 abstract function getInputHTML( $value );
347
348 function validate( $value, $alldata ) {
349 if ( isset($this->mValidationCallback) ) {
350 return call_user_func( $this->mValidationCallback, $value, $alldata );
351 }
352
353 return true;
354 }
355
356 function filter( $value, $alldata ) {
357 if( isset( $this->mFilterCallback ) ) {
358 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
359 }
360
361 return $value;
362 }
363
364 function loadDataFromRequest( $request ) {
365 if ($request->getCheck( $this->mName ) ) {
366 return $request->getText( $this->mName );
367 } else {
368 return $this->getDefault();
369 }
370 }
371
372 function __construct( $params ) {
373 $this->mParams = $params;
374
375 if (isset( $params['label-message'] ) ) {
376 $msgInfo = $params['label-message'];
377
378 if ( is_array( $msgInfo ) ) {
379 $msg = array_shift( $msgInfo );
380 } else {
381 $msg = $msgInfo;
382 $msgInfo = array();
383 }
384
385 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
386 } elseif ( isset($params['label']) ) {
387 $this->mLabel = $params['label'];
388 }
389
390 if ( isset( $params['name'] ) ) {
391 $this->mName = 'wp'.$params['name'];
392 $this->mID = 'mw-input-'.$params['name'];
393 }
394
395 if ( isset( $params['default'] ) ) {
396 $this->mDefault = $params['default'];
397 }
398
399 if ( isset( $params['id'] ) ) {
400 $this->mID = $params['id'];
401 }
402
403 if ( isset( $params['validation-callback'] ) ) {
404 $this->mValidationCallback = $params['validation-callback'];
405 }
406
407 if ( isset( $params['filter-callback'] ) ) {
408 $this->mFilterCallback = $params['filter-callback'];
409 }
410 }
411
412 function getTableRow( $value ) {
413 // Check for invalid data.
414 global $wgRequest;
415
416 $errors = $this->validate( $value, $this->mParent->mFieldData );
417 if ( $errors === true || !$wgRequest->wasPosted() ) {
418 $errors = '';
419 } else {
420 $errors = Xml::tags( 'span', array( 'class' => 'error' ), $errors );
421 }
422
423 $html = '';
424
425 $html .= Xml::tags( 'td', array( 'class' => 'mw-label' ),
426 Xml::tags( 'label', array( 'for' => $this->mID ), $this->getLabel() )
427 );
428 $html .= Xml::tags( 'td', array( 'class' => 'mw-input' ),
429 $this->getInputHTML( $value ) ."\n$errors" );
430
431 $fieldType = get_class($this);
432
433 $html = Xml::tags( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
434 $html ) . "\n";
435
436 // Help text
437 if ( isset($this->mParams['help-message']) ) {
438 $msg = $this->mParams['help-message'];
439
440 $text = wfMsgExt( $msg, 'parseinline' );
441
442 if (!wfEmptyMsg( $msg, $text ) ) {
443 $row = Xml::tags( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
444 $text );
445
446 $row = Xml::tags( 'tr', null, $row );
447
448 $html .= "$row\n";
449 }
450 }
451
452 return $html;
453 }
454
455 function getLabel() {
456 return $this->mLabel;
457 }
458
459 function getDefault() {
460 if ( isset( $this->mDefault ) ) {
461 return $this->mDefault;
462 } else {
463 return null;
464 }
465 }
466
467 static function flattenOptions( $options ) {
468 $flatOpts = array();
469
470 foreach( $options as $key => $value ) {
471 if ( is_array( $value ) ) {
472 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
473 } else {
474 $flatOpts[] = $value;
475 }
476 }
477
478 return $flatOpts;
479 }
480 }
481
482 class HTMLTextField extends HTMLFormField {
483
484 function getSize() {
485 return isset($this->mParams['size']) ? $this->mParams['size'] : 45;
486 }
487
488 function getInputHTML( $value ) {
489 $attribs = array( 'id' => $this->mID );
490
491 if ( isset($this->mParams['maxlength']) ) {
492 $attribs['maxlength'] = $this->mParams['maxlength'];
493 }
494
495 return Xml::input( $this->mName,
496 $this->getSize(),
497 $value,
498 $attribs );
499 }
500
501 }
502
503 class HTMLIntField extends HTMLTextField {
504 function getSize() {
505 return isset($this->mParams['size']) ? $this->mParams['size'] : 20;
506 }
507
508 function validate( $value, $alldata ) {
509 $p = parent::validate($value, $alldata);
510
511 if ($p !== true) return $p;
512
513 if ( intval($value) != $value ) {
514 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
515 }
516
517 $in_range = true;
518
519 if ( isset($this->mParams['min']) ) {
520 $min = $this->mParams['min'];
521 if ( $min > $value )
522 return wfMsgExt( 'htmlform-int-toolow', 'parse', array($min) );
523 }
524
525 if ( isset($this->mParams['max']) ) {
526 $max = $this->mParams['max'];
527 if ($max < $value)
528 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array($max) );
529 }
530
531 return true;
532 }
533 }
534
535 class HTMLCheckField extends HTMLFormField {
536 function getInputHTML( $value ) {
537 if ( !empty( $this->mParams['invert'] ) )
538 $value = !$value;
539
540 return Xml::check( $this->mName, $value, array( 'id' => $this->mID ) ) . '&nbsp;' .
541 Xml::tags( 'label', array( 'for' => $this->mID ), $this->mLabel );
542 }
543
544 function getLabel( ) {
545 return '&nbsp;'; // In the right-hand column.
546 }
547
548 function loadDataFromRequest( $request ) {
549 $invert = false;
550 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
551 $invert = true;
552 }
553
554 // GetCheck won't work like we want for checks.
555 if ($request->getCheck( 'wpEditToken' ) ) {
556 // XOR has the following truth table, which is what we want
557 // INVERT VALUE | OUTPUT
558 // true true | false
559 // false true | true
560 // false false | false
561 // true false | true
562 return $request->getBool( $this->mName ) xor $invert;
563 } else {
564 return $this->getDefault();
565 }
566 }
567 }
568
569 class HTMLSelectField extends HTMLFormField {
570
571 function validate( $value, $alldata ) {
572 $p = parent::validate( $value, $alldata );
573 if ($p !== true) return $p;
574
575 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
576 if ( in_array( $value, $validOptions ) )
577 return true;
578 else
579 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
580 }
581
582 function getInputHTML( $value ) {
583 $select = new XmlSelect( $this->mName, $this->mID, $value );
584
585 $select->addOptions( $this->mParams['options'] );
586
587 return $select->getHTML();
588 }
589 }
590
591 class HTMLSelectOrOtherField extends HTMLTextField {
592 static $jsAdded = false;
593
594 function __construct( $params ) {
595 if (! array_key_exists('other', $params['options']) ) {
596 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
597 }
598
599 parent::__construct( $params );
600 }
601
602 function getInputHTML( $value ) {
603
604 $valInSelect = false;
605 if ($value !== false)
606 $valInSelect = in_array( $value,
607 HTMLFormField::flattenOptions($this->mParams['options']) );
608
609 $selected = $valInSelect ? $value : 'other';
610
611 $select = new XmlSelect( $this->mName, $this->mID, $selected );
612 $select->addOptions( $this->mParams['options'] );
613
614 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
615
616 $select = $select->getHTML();
617
618 $tbAttribs = array( 'id' => $this->mID.'-other' );
619
620 if ( isset($this->mParams['maxlength']) ) {
621 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
622 }
623
624 $textbox = Xml::input( $this->mName.'-other',
625 $this->getSize(),
626 $valInSelect ? '' : $value,
627 $tbAttribs );
628
629 return "$select<br/>\n$textbox";
630 }
631
632 function loadDataFromRequest( $request ) {
633 if ($request->getCheck( $this->mName ) ) {
634 $val = $request->getText( $this->mName );
635
636 if ($val == 'other') {
637 $val = $request->getText( $this->mName.'-other' );
638 }
639
640 return $val;
641 } else {
642 return $this->getDefault();
643 }
644 }
645 }
646
647 class HTMLMultiSelectField extends HTMLFormField {
648 function validate( $value, $alldata ) {
649 $p = parent::validate( $value, $alldata );
650 if ($p !== true) return $p;
651
652 if (!is_array($value)) return false;
653
654 // If all options are valid, array_intersect of the valid options and the provided
655 // options will return the provided options.
656 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
657
658 $validValues = array_intersect( $value, $validOptions );
659 if ( count( $validValues ) == count($value) )
660 return true;
661 else
662 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
663 }
664
665 function getInputHTML( $value ) {
666 $html = $this->formatOptions( $this->mParams['options'], $value );
667
668 return $html;
669 }
670
671 function formatOptions( $options, $value ) {
672 $html = '';
673 foreach( $options as $label => $info ) {
674 if (is_array($info)) {
675 $html .= Xml::tags( 'h1', null, $label ) . "\n";
676 $html .= $this->formatOptions( $info, $value );
677 } else {
678 $checkbox = Xml::check( $this->mName.'[]', in_array( $info, $value ),
679 array( 'id' => $this->mID."-$info", 'value' => $info ) );
680 $checkbox .= '&nbsp;' . Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
681
682 $html .= $checkbox . '<br />';
683 }
684 }
685
686 return $html;
687 }
688
689 function loadDataFromRequest( $request ) {
690 // won't work with getCheck
691 if ($request->getCheck( 'wpEditToken' ) ) {
692 $arr = $request->getArray( $this->mName );
693
694 if (!$arr)
695 $arr = array();
696
697 return $arr;
698 } else {
699 return $this->getDefault();
700 }
701 }
702
703 function getDefault() {
704 if ( isset( $this->mDefault ) ) {
705 return $this->mDefault;
706 } else {
707 return array();
708 }
709 }
710 }
711
712 class HTMLRadioField extends HTMLFormField {
713 function validate( $value, $alldata ) {
714 $p = parent::validate( $value, $alldata );
715 if ($p !== true) return $p;
716
717 if (!is_string($value) && !is_int($value))
718 return false;
719
720 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
721
722 if ( in_array( $value, $validOptions ) )
723 return true;
724 else
725 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
726 }
727
728 function getInputHTML( $value ) {
729 $html = $this->formatOptions( $this->mParams['options'], $value );
730
731 return $html;
732 }
733
734 function formatOptions( $options, $value ) {
735 $html = '';
736 foreach( $options as $label => $info ) {
737 if (is_array($info)) {
738 $html .= Xml::tags( 'h1', null, $label ) . "\n";
739 $html .= $this->formatOptions( $info, $value );
740 } else {
741 $html .= Xml::radio( $this->mName, $info, $info == $value,
742 array( 'id' => $this->mID."-$info" ) );
743 $html .= '&nbsp;' .
744 Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
745
746 $html .= "<br/>\n";
747 }
748 }
749
750 return $html;
751 }
752 }
753
754 class HTMLInfoField extends HTMLFormField {
755 function __construct( $info ) {
756 $info['nodata'] = true;
757
758 parent::__construct($info);
759 }
760
761 function getInputHTML( $value ) {
762 return !empty($this->mParams['raw']) ? $value : htmlspecialchars($value);
763 }
764
765 function getTableRow( $value ) {
766 if ( !empty($this->mParams['rawrow']) ) {
767 return $value;
768 }
769
770 return parent::getTableRow( $value );
771 }
772 }