4 static $jsAdded = false;
6 /* The descriptor is an array of arrays.
8 'fieldname' => array( 'section' => 'section/subsection',
14 static $typeMappings = array(
15 'text' => 'HTMLTextField',
16 'select' => 'HTMLSelectField',
17 'radio' => 'HTMLRadioField',
18 'multiselect' => 'HTMLMultiSelectField',
19 'check' => 'HTMLCheckField',
20 'toggle' => 'HTMLCheckField',
21 'int' => 'HTMLIntField',
22 'float' => 'HTMLFloatField',
23 'info' => 'HTMLInfoField',
24 'selectorother' => 'HTMLSelectOrOtherField',
25 # HTMLTextField will output the correct type="" attribute automagically.
26 # There are about four zillion other HTML 5 input types, like url, but
27 # we don't use those at the moment, so no point in adding all of them.
28 'email' => 'HTMLTextField',
31 function __construct( $descriptor, $messagePrefix ) {
32 $this->mMessagePrefix
= $messagePrefix;
34 // Expand out into a tree.
35 $loadedDescriptor = array();
36 $this->mFlatFields
= array();
38 foreach( $descriptor as $fieldname => $info ) {
40 if ( isset( $info['section'] ) )
41 $section = $info['section'];
43 $info['name'] = $fieldname;
45 $field = $this->loadInputFromParameters( $info );
46 $field->mParent
= $this;
48 $setSection =& $loadedDescriptor;
50 $sectionParts = explode( '/', $section );
52 while( count( $sectionParts ) ) {
53 $newName = array_shift( $sectionParts );
55 if ( !isset( $setSection[$newName] ) ) {
56 $setSection[$newName] = array();
59 $setSection =& $setSection[$newName];
63 $setSection[$fieldname] = $field;
64 $this->mFlatFields
[$fieldname] = $field;
67 $this->mFieldTree
= $loadedDescriptor;
69 $this->mShowReset
= true;
72 static function addJS() {
73 if( self
::$jsAdded ) return;
77 $wgOut->addScriptClass( 'htmlform' );
80 static function loadInputFromParameters( $descriptor ) {
81 if ( isset( $descriptor['class'] ) ) {
82 $class = $descriptor['class'];
83 } elseif ( isset( $descriptor['type'] ) ) {
84 $class = self
::$typeMappings[$descriptor['type']];
85 $descriptor['class'] = $class;
89 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
92 $obj = new $class( $descriptor );
102 // Load data from the request.
106 global $wgUser, $wgRequest;
107 $editToken = $wgRequest->getVal( 'wpEditToken' );
110 if ( $wgUser->matchEditToken( $editToken ) )
111 $result = $this->trySubmit();
113 if( $result === true )
117 $this->displayForm( $result );
121 * TRUE == Successful submission
122 * FALSE == No submission attempted
123 * Anything else == Error to display.
125 function trySubmit() {
126 // Check for validation
127 foreach( $this->mFlatFields
as $fieldname => $field ) {
128 if ( !empty( $field->mParams
['nodata'] ) ) continue;
129 if ( $field->validate( $this->mFieldData
[$fieldname],
130 $this->mFieldData
) !== true ) {
131 return isset( $this->mValidationErrorMessage
) ?
132 $this->mValidationErrorMessage
: array( 'htmlform-invalid-input' );
136 $callback = $this->mSubmitCallback
;
138 $data = $this->filterDataForSubmit( $this->mFieldData
);
140 $res = call_user_func( $callback, $data );
145 function setSubmitCallback( $cb ) {
146 $this->mSubmitCallback
= $cb;
149 function setValidationErrorMessage( $msg ) {
150 $this->mValidationErrorMessage
= $msg;
153 function setIntro( $msg ) {
154 $this->mIntro
= $msg;
157 function displayForm( $submitResult ) {
160 if ( $submitResult !== false ) {
161 $this->displayErrors( $submitResult );
164 if ( isset( $this->mIntro
) ) {
165 $wgOut->addHTML( $this->mIntro
);
168 $html = $this->getBody();
171 $html .= $this->getHiddenFields();
174 $html .= $this->getButtons();
176 $html = $this->wrapForm( $html );
178 $wgOut->addHTML( $html );
181 function wrapForm( $html ) {
185 'action' => $this->getTitle()->getFullURL(),
192 function getHiddenFields() {
196 $html .= Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
197 $html .= Xml
::hidden( 'title', $this->getTitle() ) . "\n";
202 function getButtons() {
207 if ( isset( $this->mSubmitID
) )
208 $attribs['id'] = $this->mSubmitID
;
210 $attribs['class'] = 'mw-htmlform-submit';
212 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
214 if( $this->mShowReset
) {
215 $html .= Xml
::element(
219 'value' => wfMsg( 'htmlform-reset' )
228 return $this->displaySection( $this->mFieldTree
);
231 function displayErrors( $errors ) {
232 if ( is_array( $errors ) ) {
233 $errorstr = $this->formatErrors( $errors );
238 $errorstr = Xml
::tags( 'div', array( 'class' => 'error' ), $errorstr );
241 $wgOut->addHTML( $errorstr );
244 static function formatErrors( $errors ) {
246 foreach ( $errors as $error ) {
247 if( is_array( $error ) ) {
248 $msg = array_shift( $error );
253 $errorstr .= Xml
::tags(
256 wfMsgExt( $msg, array( 'parseinline' ), $error )
260 $errorstr = Xml
::tags( 'ul', null, $errorstr );
265 function setSubmitText( $t ) {
266 $this->mSubmitText
= $t;
269 function getSubmitText() {
270 return isset( $this->mSubmitText
) ?
$this->mSubmitText
: wfMsg( 'htmlform-submit' );
273 function setSubmitID( $t ) {
274 $this->mSubmitID
= $t;
277 function setMessagePrefix( $p ) {
278 $this->mMessagePrefix
= $p;
281 function setTitle( $t ) {
285 function getTitle() {
286 return $this->mTitle
;
289 function displaySection( $fields ) {
291 $subsectionHtml = '';
292 $hasLeftColumn = false;
294 foreach( $fields as $key => $value ) {
295 if ( is_object( $value ) ) {
296 $v = empty( $value->mParams
['nodata'] )
297 ?
$this->mFieldData
[$key]
298 : $value->getDefault();
299 $tableHtml .= $value->getTableRow( $v );
301 if( $value->getLabel() != ' ' )
302 $hasLeftColumn = true;
303 } elseif ( is_array( $value ) ) {
304 $section = $this->displaySection( $value );
305 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
306 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
311 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
312 $classes[] = 'mw-htmlform-nolabel';
313 $classes = implode( ' ', $classes );
315 $tableHtml = "<table class='$classes'><tbody>\n$tableHtml\n</tbody></table>\n";
317 return $subsectionHtml . "\n" . $tableHtml;
320 function loadData() {
323 $fieldData = array();
325 foreach( $this->mFlatFields
as $fieldname => $field ) {
326 if ( !empty( $field->mParams
['nodata'] ) ) continue;
327 if ( !empty( $field->mParams
['disabled'] ) ) {
328 $fieldData[$fieldname] = $field->getDefault();
330 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
335 foreach( $fieldData as $name => &$value ) {
336 $field = $this->mFlatFields
[$name];
337 $value = $field->filter( $value, $this->mFlatFields
);
340 $this->mFieldData
= $fieldData;
343 function importData( $fieldData ) {
345 foreach( $fieldData as $name => &$value ) {
346 $field = $this->mFlatFields
[$name];
347 $value = $field->filter( $value, $this->mFlatFields
);
350 foreach( $this->mFlatFields
as $fieldname => $field ) {
351 if ( !isset( $fieldData[$fieldname] ) )
352 $fieldData[$fieldname] = $field->getDefault();
355 $this->mFieldData
= $fieldData;
358 function suppressReset( $suppressReset = true ) {
359 $this->mShowReset
= !$suppressReset;
362 function filterDataForSubmit( $data ) {
367 abstract class HTMLFormField
{
368 abstract function getInputHTML( $value );
370 function validate( $value, $alldata ) {
371 if ( isset( $this->mValidationCallback
) ) {
372 return call_user_func( $this->mValidationCallback
, $value, $alldata );
378 function filter( $value, $alldata ) {
379 if( isset( $this->mFilterCallback
) ) {
380 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
386 function loadDataFromRequest( $request ) {
387 if( $request->getCheck( $this->mName
) ) {
388 return $request->getText( $this->mName
);
390 return $this->getDefault();
394 function __construct( $params ) {
395 $this->mParams
= $params;
397 if( isset( $params['label-message'] ) ) {
398 $msgInfo = $params['label-message'];
400 if ( is_array( $msgInfo ) ) {
401 $msg = array_shift( $msgInfo );
407 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
408 } elseif ( isset( $params['label'] ) ) {
409 $this->mLabel
= $params['label'];
412 if ( isset( $params['name'] ) ) {
413 $name = $params['name'];
414 $validName = Sanitizer
::escapeId( $name );
415 if( $name != $validName ) {
416 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
418 $this->mName
= 'wp'.$name;
419 $this->mID
= 'mw-input-'.$name;
422 if ( isset( $params['default'] ) ) {
423 $this->mDefault
= $params['default'];
426 if ( isset( $params['id'] ) ) {
428 $validId = Sanitizer
::escapeId( $id );
429 if( $id != $validId ) {
430 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
435 if ( isset( $params['validation-callback'] ) ) {
436 $this->mValidationCallback
= $params['validation-callback'];
439 if ( isset( $params['filter-callback'] ) ) {
440 $this->mFilterCallback
= $params['filter-callback'];
444 function getTableRow( $value ) {
445 // Check for invalid data.
448 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
449 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
452 $errors = Xml
::tags( 'span', array( 'class' => 'error' ), $errors );
457 $html .= Xml
::tags( 'td', array( 'class' => 'mw-label' ),
458 Xml
::tags( 'label', array( 'for' => $this->mID
), $this->getLabel() )
460 $html .= Xml
::tags( 'td', array( 'class' => 'mw-input' ),
461 $this->getInputHTML( $value ) ."\n$errors" );
463 $fieldType = get_class( $this );
465 $html = Xml
::tags( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
469 if ( isset( $this->mParams
['help-message'] ) ) {
470 $msg = $this->mParams
['help-message'];
471 $helptext = wfMsgExt( $msg, 'parseinline' );
472 if ( wfEmptyMsg( $msg, $helptext ) ) {
476 } elseif ( isset( $this->mParams
['help'] ) ) {
477 $helptext = $this->mParams
['help'];
480 if ( !is_null( $helptext ) ) {
481 $row = Xml
::tags( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
483 $row = Xml
::tags( 'tr', null, $row );
490 function getLabel() {
491 return $this->mLabel
;
494 function getDefault() {
495 if ( isset( $this->mDefault
) ) {
496 return $this->mDefault
;
502 static function flattenOptions( $options ) {
505 foreach( $options as $key => $value ) {
506 if ( is_array( $value ) ) {
507 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
509 $flatOpts[] = $value;
517 class HTMLTextField
extends HTMLFormField
{
519 return isset( $this->mParams
['size'] ) ?
$this->mParams
['size'] : 45;
522 function getInputHTML( $value ) {
524 $attribs = array( 'id' => $this->mID
);
526 if ( isset( $this->mParams
['maxlength'] ) ) {
527 $attribs['maxlength'] = $this->mParams
['maxlength'];
530 if ( !empty( $this->mParams
['disabled'] ) ) {
531 $attribs['disabled'] = 'disabled';
535 # TODO: Enforce pattern, step, required, readonly on the server
537 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
538 'placeholder' ) as $param ) {
539 if ( isset( $this->mParams
[$param] ) ) {
540 $attribs[$param] = $this->mParams
[$param];
543 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
545 if ( isset( $this->mParams
[$param] ) ) {
546 $attribs[$param] = '';
549 if ( isset( $this->mParams
['type'] ) ) {
550 switch ( $this->mParams
['type'] ) {
552 $attribs['type'] = 'email';
555 $attribs['type'] = 'number';
558 $attribs['type'] = 'number';
559 $attribs['step'] = 'any';
574 class HTMLFloatField
extends HTMLTextField
{
576 return isset( $this->mParams
['size'] ) ?
$this->mParams
['size'] : 20;
579 function validate( $value, $alldata ) {
580 $p = parent
::validate( $value, $alldata );
582 if ( $p !== true ) return $p;
584 if ( floatval( $value ) != $value ) {
585 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
590 # The "int" part of these message names is rather confusing. They make
591 # equal sense for all numbers.
592 if ( isset( $this->mParams
['min'] ) ) {
593 $min = $this->mParams
['min'];
595 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
598 if ( isset( $this->mParams
['max'] ) ) {
599 $max = $this->mParams
['max'];
601 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
608 class HTMLIntField
extends HTMLFloatField
{
609 function validate( $value, $alldata ) {
610 $p = parent
::validate( $value, $alldata );
612 if ( $p !== true ) return $p;
614 if ( intval( $value ) != $value ) {
615 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
622 class HTMLCheckField
extends HTMLFormField
{
623 function getInputHTML( $value ) {
624 if ( !empty( $this->mParams
['invert'] ) )
627 $attr = array( 'id' => $this->mID
);
628 if( !empty( $this->mParams
['disabled'] ) ) {
629 $attr['disabled'] = 'disabled';
632 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
633 Xml
::tags( 'label', array( 'for' => $this->mID
), $this->mLabel
);
636 function getLabel() {
637 return ' '; // In the right-hand column.
640 function loadDataFromRequest( $request ) {
642 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
646 // GetCheck won't work like we want for checks.
647 if( $request->getCheck( 'wpEditToken' ) ) {
648 // XOR has the following truth table, which is what we want
649 // INVERT VALUE | OUTPUT
652 // false false | false
654 return $request->getBool( $this->mName
) xor $invert;
656 return $this->getDefault();
661 class HTMLSelectField
extends HTMLFormField
{
663 function validate( $value, $alldata ) {
664 $p = parent
::validate( $value, $alldata );
665 if( $p !== true ) return $p;
667 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
668 if ( in_array( $value, $validOptions ) )
671 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
674 function getInputHTML( $value ) {
675 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
677 // If one of the options' 'name' is int(0), it is automatically selected.
678 // because PHP sucks and things int(0) == 'some string'.
679 // Working around this by forcing all of them to strings.
680 $options = array_map( 'strval', $this->mParams
['options'] );
682 if( !empty( $this->mParams
['disabled'] ) ) {
683 $select->setAttribute( 'disabled', 'disabled' );
686 $select->addOptions( $options );
688 return $select->getHTML();
692 class HTMLSelectOrOtherField
extends HTMLTextField
{
693 static $jsAdded = false;
695 function __construct( $params ) {
696 if( !in_array( 'other', $params['options'] ) ) {
697 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
700 parent
::__construct( $params );
703 static function forceToStringRecursive( $array ) {
704 if ( is_array($array) ) {
705 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
707 return strval($array);
711 function getInputHTML( $value ) {
712 $valInSelect = false;
714 if( $value !== false )
715 $valInSelect = in_array( $value,
716 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
718 $selected = $valInSelect ?
$value : 'other';
720 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
722 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
723 $select->addOptions( $opts );
725 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
727 $tbAttribs = array( 'id' => $this->mID
. '-other' );
728 if( !empty( $this->mParams
['disabled'] ) ) {
729 $select->setAttribute( 'disabled', 'disabled' );
730 $tbAttribs['disabled'] = 'disabled';
733 $select = $select->getHTML();
735 if ( isset( $this->mParams
['maxlength'] ) ) {
736 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
739 $textbox = Xml
::input( $this->mName
. '-other',
741 $valInSelect ?
'' : $value,
744 return "$select<br/>\n$textbox";
747 function loadDataFromRequest( $request ) {
748 if( $request->getCheck( $this->mName
) ) {
749 $val = $request->getText( $this->mName
);
751 if( $val == 'other' ) {
752 $val = $request->getText( $this->mName
. '-other' );
757 return $this->getDefault();
762 class HTMLMultiSelectField
extends HTMLFormField
{
763 function validate( $value, $alldata ) {
764 $p = parent
::validate( $value, $alldata );
765 if( $p !== true ) return $p;
767 if( !is_array( $value ) ) return false;
769 // If all options are valid, array_intersect of the valid options and the provided
770 // options will return the provided options.
771 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
773 $validValues = array_intersect( $value, $validOptions );
774 if ( count( $validValues ) == count( $value ) )
777 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
780 function getInputHTML( $value ) {
781 $html = $this->formatOptions( $this->mParams
['options'], $value );
786 function formatOptions( $options, $value ) {
790 if ( !empty( $this->mParams
['disabled'] ) ) {
791 $attribs['disabled'] = 'disabled';
794 foreach( $options as $label => $info ) {
795 if( is_array( $info ) ) {
796 $html .= Xml
::tags( 'h1', null, $label ) . "\n";
797 $html .= $this->formatOptions( $info, $value );
799 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
801 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
802 $attribs +
$thisAttribs );
803 $checkbox .= ' ' . Xml
::tags( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
805 $html .= $checkbox . '<br />';
812 function loadDataFromRequest( $request ) {
813 // won't work with getCheck
814 if( $request->getCheck( 'wpEditToken' ) ) {
815 $arr = $request->getArray( $this->mName
);
822 return $this->getDefault();
826 function getDefault() {
827 if ( isset( $this->mDefault
) ) {
828 return $this->mDefault
;
835 class HTMLRadioField
extends HTMLFormField
{
836 function validate( $value, $alldata ) {
837 $p = parent
::validate( $value, $alldata );
838 if( $p !== true ) return $p;
840 if( !is_string( $value ) && !is_int( $value ) )
843 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
845 if ( in_array( $value, $validOptions ) )
848 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
851 function getInputHTML( $value ) {
852 $html = $this->formatOptions( $this->mParams
['options'], $value );
857 function formatOptions( $options, $value ) {
861 if ( !empty( $this->mParams
['disabled'] ) ) {
862 $attribs['disabled'] = 'disabled';
865 foreach( $options as $label => $info ) {
866 if( is_array( $info ) ) {
867 $html .= Xml
::tags( 'h1', null, $label ) . "\n";
868 $html .= $this->formatOptions( $info, $value );
870 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
871 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
872 $attribs +
array( 'id' => $id ) );
874 Xml
::tags( 'label', array( 'for' => $id ), $label );
884 class HTMLInfoField
extends HTMLFormField
{
885 function __construct( $info ) {
886 $info['nodata'] = true;
888 parent
::__construct( $info );
891 function getInputHTML( $value ) {
892 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
895 function getTableRow( $value ) {
896 if ( !empty( $this->mParams
['rawrow'] ) ) {
900 return parent
::getTableRow( $value );