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