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