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',
29 'password' => 'HTMLTextField',
32 function __construct( $descriptor, $messagePrefix ) {
33 $this->mMessagePrefix
= $messagePrefix;
35 // Expand out into a tree.
36 $loadedDescriptor = array();
37 $this->mFlatFields
= array();
39 foreach( $descriptor as $fieldname => $info ) {
41 if ( isset( $info['section'] ) )
42 $section = $info['section'];
44 $info['name'] = $fieldname;
46 $field = $this->loadInputFromParameters( $info );
47 $field->mParent
= $this;
49 $setSection =& $loadedDescriptor;
51 $sectionParts = explode( '/', $section );
53 while( count( $sectionParts ) ) {
54 $newName = array_shift( $sectionParts );
56 if ( !isset( $setSection[$newName] ) ) {
57 $setSection[$newName] = array();
60 $setSection =& $setSection[$newName];
64 $setSection[$fieldname] = $field;
65 $this->mFlatFields
[$fieldname] = $field;
68 $this->mFieldTree
= $loadedDescriptor;
70 $this->mShowReset
= true;
73 static function addJS() {
74 if( self
::$jsAdded ) return;
78 $wgOut->addScriptClass( 'htmlform' );
81 static function loadInputFromParameters( $descriptor ) {
82 if ( isset( $descriptor['class'] ) ) {
83 $class = $descriptor['class'];
84 } elseif ( isset( $descriptor['type'] ) ) {
85 $class = self
::$typeMappings[$descriptor['type']];
86 $descriptor['class'] = $class;
90 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
93 $obj = new $class( $descriptor );
103 // Load data from the request.
107 global $wgUser, $wgRequest;
108 $editToken = $wgRequest->getVal( 'wpEditToken' );
111 if ( $wgUser->matchEditToken( $editToken ) )
112 $result = $this->trySubmit();
114 if( $result === true )
118 $this->displayForm( $result );
122 * TRUE == Successful submission
123 * FALSE == No submission attempted
124 * Anything else == Error to display.
126 function trySubmit() {
127 // Check for validation
128 foreach( $this->mFlatFields
as $fieldname => $field ) {
129 if ( !empty( $field->mParams
['nodata'] ) ) continue;
130 if ( $field->validate( $this->mFieldData
[$fieldname],
131 $this->mFieldData
) !== true ) {
132 return isset( $this->mValidationErrorMessage
) ?
133 $this->mValidationErrorMessage
: array( 'htmlform-invalid-input' );
137 $callback = $this->mSubmitCallback
;
139 $data = $this->filterDataForSubmit( $this->mFieldData
);
141 $res = call_user_func( $callback, $data );
146 function setSubmitCallback( $cb ) {
147 $this->mSubmitCallback
= $cb;
150 function setValidationErrorMessage( $msg ) {
151 $this->mValidationErrorMessage
= $msg;
154 function setIntro( $msg ) {
155 $this->mIntro
= $msg;
158 function displayForm( $submitResult ) {
161 if ( $submitResult !== false ) {
162 $this->displayErrors( $submitResult );
165 if ( isset( $this->mIntro
) ) {
166 $wgOut->addHTML( $this->mIntro
);
169 $html = $this->getBody();
172 $html .= $this->getHiddenFields();
175 $html .= $this->getButtons();
177 $html = $this->wrapForm( $html );
179 $wgOut->addHTML( $html );
182 function wrapForm( $html ) {
183 return Html
::rawElement(
186 'action' => $this->getTitle()->getFullURL(),
193 function getHiddenFields() {
197 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
198 $html .= Html
::hidden( 'title', $this->getTitle() ) . "\n";
203 function getButtons() {
208 if ( isset( $this->mSubmitID
) )
209 $attribs['id'] = $this->mSubmitID
;
211 $attribs['class'] = 'mw-htmlform-submit';
213 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
215 if( $this->mShowReset
) {
216 $html .= Html
::element(
220 'value' => wfMsg( 'htmlform-reset' )
229 return $this->displaySection( $this->mFieldTree
);
232 function displayErrors( $errors ) {
233 if ( is_array( $errors ) ) {
234 $errorstr = $this->formatErrors( $errors );
239 $errorstr = Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr );
242 $wgOut->addHTML( $errorstr );
245 static function formatErrors( $errors ) {
247 foreach ( $errors as $error ) {
248 if( is_array( $error ) ) {
249 $msg = array_shift( $error );
254 $errorstr .= Html
::rawElement(
257 wfMsgExt( $msg, array( 'parseinline' ), $error )
261 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
266 function setSubmitText( $t ) {
267 $this->mSubmitText
= $t;
270 function getSubmitText() {
271 return isset( $this->mSubmitText
) ?
$this->mSubmitText
: wfMsg( 'htmlform-submit' );
274 function setSubmitID( $t ) {
275 $this->mSubmitID
= $t;
278 function setMessagePrefix( $p ) {
279 $this->mMessagePrefix
= $p;
282 function setTitle( $t ) {
286 function getTitle() {
287 return $this->mTitle
;
290 function displaySection( $fields ) {
292 $subsectionHtml = '';
293 $hasLeftColumn = false;
295 foreach( $fields as $key => $value ) {
296 if ( is_object( $value ) ) {
297 $v = empty( $value->mParams
['nodata'] )
298 ?
$this->mFieldData
[$key]
299 : $value->getDefault();
300 $tableHtml .= $value->getTableRow( $v );
302 if( $value->getLabel() != ' ' )
303 $hasLeftColumn = true;
304 } elseif ( is_array( $value ) ) {
305 $section = $this->displaySection( $value );
306 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
307 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
312 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
313 $classes[] = 'mw-htmlform-nolabel';
314 $classes = implode( ' ', $classes );
316 $tableHtml = Html
::rawElement( 'table', array( 'class' => $classes ),
317 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
319 return $subsectionHtml . "\n" . $tableHtml;
322 function loadData() {
325 $fieldData = array();
327 foreach( $this->mFlatFields
as $fieldname => $field ) {
328 if ( !empty( $field->mParams
['nodata'] ) ) continue;
329 if ( !empty( $field->mParams
['disabled'] ) ) {
330 $fieldData[$fieldname] = $field->getDefault();
332 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
337 foreach( $fieldData as $name => &$value ) {
338 $field = $this->mFlatFields
[$name];
339 $value = $field->filter( $value, $this->mFlatFields
);
342 $this->mFieldData
= $fieldData;
345 function importData( $fieldData ) {
347 foreach( $fieldData as $name => &$value ) {
348 $field = $this->mFlatFields
[$name];
349 $value = $field->filter( $value, $this->mFlatFields
);
352 foreach( $this->mFlatFields
as $fieldname => $field ) {
353 if ( !isset( $fieldData[$fieldname] ) )
354 $fieldData[$fieldname] = $field->getDefault();
357 $this->mFieldData
= $fieldData;
360 function suppressReset( $suppressReset = true ) {
361 $this->mShowReset
= !$suppressReset;
364 function filterDataForSubmit( $data ) {
369 abstract class HTMLFormField
{
370 abstract function getInputHTML( $value );
372 function validate( $value, $alldata ) {
373 if ( isset( $this->mValidationCallback
) ) {
374 return call_user_func( $this->mValidationCallback
, $value, $alldata );
380 function filter( $value, $alldata ) {
381 if( isset( $this->mFilterCallback
) ) {
382 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
389 * Should this field have a label, or is there no input element with the
390 * appropriate id for the label to point to?
392 * @return bool True to output a label, false to suppress
394 protected function needsLabel() {
398 function loadDataFromRequest( $request ) {
399 if( $request->getCheck( $this->mName
) ) {
400 return $request->getText( $this->mName
);
402 return $this->getDefault();
406 function __construct( $params ) {
407 $this->mParams
= $params;
409 if( isset( $params['label-message'] ) ) {
410 $msgInfo = $params['label-message'];
412 if ( is_array( $msgInfo ) ) {
413 $msg = array_shift( $msgInfo );
419 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
420 } elseif ( isset( $params['label'] ) ) {
421 $this->mLabel
= $params['label'];
424 if ( isset( $params['name'] ) ) {
425 $name = $params['name'];
426 $validName = Sanitizer
::escapeId( $name );
427 if( $name != $validName ) {
428 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
430 $this->mName
= 'wp'.$name;
431 $this->mID
= 'mw-input-'.$name;
434 if ( isset( $params['default'] ) ) {
435 $this->mDefault
= $params['default'];
438 if ( isset( $params['id'] ) ) {
440 $validId = Sanitizer
::escapeId( $id );
441 if( $id != $validId ) {
442 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
447 if ( isset( $params['validation-callback'] ) ) {
448 $this->mValidationCallback
= $params['validation-callback'];
451 if ( isset( $params['filter-callback'] ) ) {
452 $this->mFilterCallback
= $params['filter-callback'];
456 function getTableRow( $value ) {
457 // Check for invalid data.
460 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
461 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
464 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
469 # Don't output a for= attribute for labels with no associated input.
470 # Kind of hacky here, possibly we don't want these to be <label>s at all.
472 if ( $this->needsLabel() ) {
473 $for['for'] = $this->mID
;
475 $html .= Html
::rawElement( 'td', array( 'class' => 'mw-label' ),
476 Html
::rawElement( 'label', $for, $this->getLabel() )
478 $html .= Html
::rawElement( 'td', array( 'class' => 'mw-input' ),
479 $this->getInputHTML( $value ) ."\n$errors" );
481 $fieldType = get_class( $this );
483 $html = Html
::rawElement( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
487 if ( isset( $this->mParams
['help-message'] ) ) {
488 $msg = $this->mParams
['help-message'];
489 $helptext = wfMsgExt( $msg, 'parseinline' );
490 if ( wfEmptyMsg( $msg, $helptext ) ) {
494 } elseif ( isset( $this->mParams
['help'] ) ) {
495 $helptext = $this->mParams
['help'];
498 if ( !is_null( $helptext ) ) {
499 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
501 $row = Html
::rawElement( 'tr', array(), $row );
508 function getLabel() {
509 return $this->mLabel
;
512 function getDefault() {
513 if ( isset( $this->mDefault
) ) {
514 return $this->mDefault
;
520 static function flattenOptions( $options ) {
523 foreach( $options as $key => $value ) {
524 if ( is_array( $value ) ) {
525 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
527 $flatOpts[] = $value;
535 class HTMLTextField
extends HTMLFormField
{
536 # Override in derived classes to use other Xml::... functions
537 protected $mFunction = 'input';
540 return isset( $this->mParams
['size'] ) ?
$this->mParams
['size'] : 45;
543 function getInputHTML( $value ) {
547 'name' => $this->mName
,
548 'size' => $this->getSize(),
552 if ( isset( $this->mParams
['maxlength'] ) ) {
553 $attribs['maxlength'] = $this->mParams
['maxlength'];
556 if ( !empty( $this->mParams
['disabled'] ) ) {
557 $attribs['disabled'] = 'disabled';
561 # TODO: Enforce pattern, step, required, readonly on the server
563 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
564 'placeholder' ) as $param ) {
565 if ( isset( $this->mParams
[$param] ) ) {
566 $attribs[$param] = $this->mParams
[$param];
569 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
571 if ( isset( $this->mParams
[$param] ) ) {
572 $attribs[$param] = '';
575 if ( isset( $this->mParams
['type'] ) ) {
576 switch ( $this->mParams
['type'] ) {
578 $attribs['type'] = 'email';
581 $attribs['type'] = 'number';
584 $attribs['type'] = 'number';
585 $attribs['step'] = 'any';
588 $attribs['type'] = 'password';
594 return Html
::element( 'input', $attribs );
598 class HTMLFloatField
extends HTMLTextField
{
600 return isset( $this->mParams
['size'] ) ?
$this->mParams
['size'] : 20;
603 function validate( $value, $alldata ) {
604 $p = parent
::validate( $value, $alldata );
606 if ( $p !== true ) return $p;
608 if ( floatval( $value ) != $value ) {
609 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
614 # The "int" part of these message names is rather confusing. They make
615 # equal sense for all numbers.
616 if ( isset( $this->mParams
['min'] ) ) {
617 $min = $this->mParams
['min'];
619 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
622 if ( isset( $this->mParams
['max'] ) ) {
623 $max = $this->mParams
['max'];
625 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
632 class HTMLIntField
extends HTMLFloatField
{
633 function validate( $value, $alldata ) {
634 $p = parent
::validate( $value, $alldata );
636 if ( $p !== true ) return $p;
638 if ( intval( $value ) != $value ) {
639 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
646 class HTMLCheckField
extends HTMLFormField
{
647 function getInputHTML( $value ) {
648 if ( !empty( $this->mParams
['invert'] ) )
651 $attr = array( 'id' => $this->mID
);
652 if( !empty( $this->mParams
['disabled'] ) ) {
653 $attr['disabled'] = 'disabled';
656 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
657 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
660 function getLabel() {
661 return ' '; // In the right-hand column.
664 function loadDataFromRequest( $request ) {
666 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
670 // GetCheck won't work like we want for checks.
671 if( $request->getCheck( 'wpEditToken' ) ) {
672 // XOR has the following truth table, which is what we want
673 // INVERT VALUE | OUTPUT
676 // false false | false
678 return $request->getBool( $this->mName
) xor $invert;
680 return $this->getDefault();
685 class HTMLSelectField
extends HTMLFormField
{
687 function validate( $value, $alldata ) {
688 $p = parent
::validate( $value, $alldata );
689 if( $p !== true ) return $p;
691 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
692 if ( in_array( $value, $validOptions ) )
695 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
698 function getInputHTML( $value ) {
699 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
701 // If one of the options' 'name' is int(0), it is automatically selected.
702 // because PHP sucks and things int(0) == 'some string'.
703 // Working around this by forcing all of them to strings.
704 $options = array_map( 'strval', $this->mParams
['options'] );
706 if( !empty( $this->mParams
['disabled'] ) ) {
707 $select->setAttribute( 'disabled', 'disabled' );
710 $select->addOptions( $options );
712 return $select->getHTML();
716 class HTMLSelectOrOtherField
extends HTMLTextField
{
717 static $jsAdded = false;
719 function __construct( $params ) {
720 if( !in_array( 'other', $params['options'], true ) ) {
721 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
724 parent
::__construct( $params );
727 static function forceToStringRecursive( $array ) {
728 if ( is_array($array) ) {
729 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
731 return strval($array);
735 function getInputHTML( $value ) {
736 $valInSelect = false;
738 if( $value !== false )
739 $valInSelect = in_array( $value,
740 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
742 $selected = $valInSelect ?
$value : 'other';
744 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
746 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
747 $select->addOptions( $opts );
749 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
751 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
752 if( !empty( $this->mParams
['disabled'] ) ) {
753 $select->setAttribute( 'disabled', 'disabled' );
754 $tbAttribs['disabled'] = 'disabled';
757 $select = $select->getHTML();
759 if ( isset( $this->mParams
['maxlength'] ) ) {
760 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
763 $textbox = Html
::input( $this->mName
. '-other',
764 $valInSelect ?
'' : $value,
768 return "$select<br/>\n$textbox";
771 function loadDataFromRequest( $request ) {
772 if( $request->getCheck( $this->mName
) ) {
773 $val = $request->getText( $this->mName
);
775 if( $val == 'other' ) {
776 $val = $request->getText( $this->mName
. '-other' );
781 return $this->getDefault();
786 class HTMLMultiSelectField
extends HTMLFormField
{
787 function validate( $value, $alldata ) {
788 $p = parent
::validate( $value, $alldata );
789 if( $p !== true ) return $p;
791 if( !is_array( $value ) ) return false;
793 // If all options are valid, array_intersect of the valid options and the provided
794 // options will return the provided options.
795 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
797 $validValues = array_intersect( $value, $validOptions );
798 if ( count( $validValues ) == count( $value ) )
801 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
804 function getInputHTML( $value ) {
805 $html = $this->formatOptions( $this->mParams
['options'], $value );
810 function formatOptions( $options, $value ) {
814 if ( !empty( $this->mParams
['disabled'] ) ) {
815 $attribs['disabled'] = 'disabled';
818 foreach( $options as $label => $info ) {
819 if( is_array( $info ) ) {
820 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
821 $html .= $this->formatOptions( $info, $value );
823 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
825 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
826 $attribs +
$thisAttribs );
827 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
829 $html .= $checkbox . '<br />';
836 function loadDataFromRequest( $request ) {
837 // won't work with getCheck
838 if( $request->getCheck( 'wpEditToken' ) ) {
839 $arr = $request->getArray( $this->mName
);
846 return $this->getDefault();
850 function getDefault() {
851 if ( isset( $this->mDefault
) ) {
852 return $this->mDefault
;
858 protected function needsLabel() {
863 class HTMLRadioField
extends HTMLFormField
{
864 function validate( $value, $alldata ) {
865 $p = parent
::validate( $value, $alldata );
866 if( $p !== true ) return $p;
868 if( !is_string( $value ) && !is_int( $value ) )
871 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
873 if ( in_array( $value, $validOptions ) )
876 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
879 function getInputHTML( $value ) {
880 $html = $this->formatOptions( $this->mParams
['options'], $value );
885 function formatOptions( $options, $value ) {
889 if ( !empty( $this->mParams
['disabled'] ) ) {
890 $attribs['disabled'] = 'disabled';
893 foreach( $options as $label => $info ) {
894 if( is_array( $info ) ) {
895 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
896 $html .= $this->formatOptions( $info, $value );
898 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
899 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
900 $attribs +
array( 'id' => $id ) );
902 Html
::rawElement( 'label', array( 'for' => $id ), $label );
911 protected function needsLabel() {
916 class HTMLInfoField
extends HTMLFormField
{
917 function __construct( $info ) {
918 $info['nodata'] = true;
920 parent
::__construct( $info );
923 function getInputHTML( $value ) {
924 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
927 function getTableRow( $value ) {
928 if ( !empty( $this->mParams
['rawrow'] ) ) {
932 return parent
::getTableRow( $value );
935 protected function needsLabel() {