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 ) {
186 'action' => $this->getTitle()->getFullURL(),
193 function getHiddenFields() {
197 $html .= Xml
::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
198 $html .= Xml
::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 .= Xml
::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 = Xml
::tags( '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 .= Xml
::tags(
257 wfMsgExt( $msg, array( 'parseinline' ), $error )
261 $errorstr = Xml
::tags( 'ul', null, $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 = "<table class='$classes'><tbody>\n$tableHtml\n</tbody></table>\n";
318 return $subsectionHtml . "\n" . $tableHtml;
321 function loadData() {
324 $fieldData = array();
326 foreach( $this->mFlatFields
as $fieldname => $field ) {
327 if ( !empty( $field->mParams
['nodata'] ) ) continue;
328 if ( !empty( $field->mParams
['disabled'] ) ) {
329 $fieldData[$fieldname] = $field->getDefault();
331 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
336 foreach( $fieldData as $name => &$value ) {
337 $field = $this->mFlatFields
[$name];
338 $value = $field->filter( $value, $this->mFlatFields
);
341 $this->mFieldData
= $fieldData;
344 function importData( $fieldData ) {
346 foreach( $fieldData as $name => &$value ) {
347 $field = $this->mFlatFields
[$name];
348 $value = $field->filter( $value, $this->mFlatFields
);
351 foreach( $this->mFlatFields
as $fieldname => $field ) {
352 if ( !isset( $fieldData[$fieldname] ) )
353 $fieldData[$fieldname] = $field->getDefault();
356 $this->mFieldData
= $fieldData;
359 function suppressReset( $suppressReset = true ) {
360 $this->mShowReset
= !$suppressReset;
363 function filterDataForSubmit( $data ) {
368 abstract class HTMLFormField
{
369 abstract function getInputHTML( $value );
371 function validate( $value, $alldata ) {
372 if ( isset( $this->mValidationCallback
) ) {
373 return call_user_func( $this->mValidationCallback
, $value, $alldata );
379 function filter( $value, $alldata ) {
380 if( isset( $this->mFilterCallback
) ) {
381 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
387 function loadDataFromRequest( $request ) {
388 if( $request->getCheck( $this->mName
) ) {
389 return $request->getText( $this->mName
);
391 return $this->getDefault();
395 function __construct( $params ) {
396 $this->mParams
= $params;
398 if( isset( $params['label-message'] ) ) {
399 $msgInfo = $params['label-message'];
401 if ( is_array( $msgInfo ) ) {
402 $msg = array_shift( $msgInfo );
408 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
409 } elseif ( isset( $params['label'] ) ) {
410 $this->mLabel
= $params['label'];
413 if ( isset( $params['name'] ) ) {
414 $name = $params['name'];
415 $validName = Sanitizer
::escapeId( $name );
416 if( $name != $validName ) {
417 throw new MWException("Invalid name '$name' passed to " . __METHOD__
);
419 $this->mName
= 'wp'.$name;
420 $this->mID
= 'mw-input-'.$name;
423 if ( isset( $params['default'] ) ) {
424 $this->mDefault
= $params['default'];
427 if ( isset( $params['id'] ) ) {
429 $validId = Sanitizer
::escapeId( $id );
430 if( $id != $validId ) {
431 throw new MWException("Invalid id '$id' passed to " . __METHOD__
);
436 if ( isset( $params['validation-callback'] ) ) {
437 $this->mValidationCallback
= $params['validation-callback'];
440 if ( isset( $params['filter-callback'] ) ) {
441 $this->mFilterCallback
= $params['filter-callback'];
445 function getTableRow( $value ) {
446 // Check for invalid data.
449 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
450 if ( $errors === true ||
!$wgRequest->wasPosted() ) {
453 $errors = Xml
::tags( 'span', array( 'class' => 'error' ), $errors );
458 $html .= Xml
::tags( 'td', array( 'class' => 'mw-label' ),
459 Xml
::tags( 'label', array( 'for' => $this->mID
), $this->getLabel() )
461 $html .= Xml
::tags( 'td', array( 'class' => 'mw-input' ),
462 $this->getInputHTML( $value ) ."\n$errors" );
464 $fieldType = get_class( $this );
466 $html = Xml
::tags( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
470 if ( isset( $this->mParams
['help-message'] ) ) {
471 $msg = $this->mParams
['help-message'];
472 $helptext = wfMsgExt( $msg, 'parseinline' );
473 if ( wfEmptyMsg( $msg, $helptext ) ) {
477 } elseif ( isset( $this->mParams
['help'] ) ) {
478 $helptext = $this->mParams
['help'];
481 if ( !is_null( $helptext ) ) {
482 $row = Xml
::tags( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
484 $row = Xml
::tags( 'tr', null, $row );
491 function getLabel() {
492 return $this->mLabel
;
495 function getDefault() {
496 if ( isset( $this->mDefault
) ) {
497 return $this->mDefault
;
503 static function flattenOptions( $options ) {
506 foreach( $options as $key => $value ) {
507 if ( is_array( $value ) ) {
508 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
510 $flatOpts[] = $value;
518 class HTMLTextField
extends HTMLFormField
{
519 # Override in derived classes to use other Xml::... functions
520 protected $mFunction = 'input';
523 return isset( $this->mParams
['size'] ) ?
$this->mParams
['size'] : 45;
526 function getInputHTML( $value ) {
530 'name' => $this->mName
,
531 'size' => $this->getSize(),
535 if ( isset( $this->mParams
['maxlength'] ) ) {
536 $attribs['maxlength'] = $this->mParams
['maxlength'];
539 if ( !empty( $this->mParams
['disabled'] ) ) {
540 $attribs['disabled'] = 'disabled';
544 # TODO: Enforce pattern, step, required, readonly on the server
546 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
547 'placeholder' ) as $param ) {
548 if ( isset( $this->mParams
[$param] ) ) {
549 $attribs[$param] = $this->mParams
[$param];
552 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
554 if ( isset( $this->mParams
[$param] ) ) {
555 $attribs[$param] = '';
558 if ( isset( $this->mParams
['type'] ) ) {
559 switch ( $this->mParams
['type'] ) {
561 $attribs['type'] = 'email';
564 $attribs['type'] = 'number';
567 $attribs['type'] = 'number';
568 $attribs['step'] = 'any';
571 $attribs['type'] = 'password';
577 return Html
::element( 'input', $attribs );
581 class HTMLFloatField
extends HTMLTextField
{
583 return isset( $this->mParams
['size'] ) ?
$this->mParams
['size'] : 20;
586 function validate( $value, $alldata ) {
587 $p = parent
::validate( $value, $alldata );
589 if ( $p !== true ) return $p;
591 if ( floatval( $value ) != $value ) {
592 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
597 # The "int" part of these message names is rather confusing. They make
598 # equal sense for all numbers.
599 if ( isset( $this->mParams
['min'] ) ) {
600 $min = $this->mParams
['min'];
602 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
605 if ( isset( $this->mParams
['max'] ) ) {
606 $max = $this->mParams
['max'];
608 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
615 class HTMLIntField
extends HTMLFloatField
{
616 function validate( $value, $alldata ) {
617 $p = parent
::validate( $value, $alldata );
619 if ( $p !== true ) return $p;
621 if ( intval( $value ) != $value ) {
622 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
629 class HTMLCheckField
extends HTMLFormField
{
630 function getInputHTML( $value ) {
631 if ( !empty( $this->mParams
['invert'] ) )
634 $attr = array( 'id' => $this->mID
);
635 if( !empty( $this->mParams
['disabled'] ) ) {
636 $attr['disabled'] = 'disabled';
639 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
640 Xml
::tags( 'label', array( 'for' => $this->mID
), $this->mLabel
);
643 function getLabel() {
644 return ' '; // In the right-hand column.
647 function loadDataFromRequest( $request ) {
649 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
653 // GetCheck won't work like we want for checks.
654 if( $request->getCheck( 'wpEditToken' ) ) {
655 // XOR has the following truth table, which is what we want
656 // INVERT VALUE | OUTPUT
659 // false false | false
661 return $request->getBool( $this->mName
) xor $invert;
663 return $this->getDefault();
668 class HTMLSelectField
extends HTMLFormField
{
670 function validate( $value, $alldata ) {
671 $p = parent
::validate( $value, $alldata );
672 if( $p !== true ) return $p;
674 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
675 if ( in_array( $value, $validOptions ) )
678 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
681 function getInputHTML( $value ) {
682 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
684 // If one of the options' 'name' is int(0), it is automatically selected.
685 // because PHP sucks and things int(0) == 'some string'.
686 // Working around this by forcing all of them to strings.
687 $options = array_map( 'strval', $this->mParams
['options'] );
689 if( !empty( $this->mParams
['disabled'] ) ) {
690 $select->setAttribute( 'disabled', 'disabled' );
693 $select->addOptions( $options );
695 return $select->getHTML();
699 class HTMLSelectOrOtherField
extends HTMLTextField
{
700 static $jsAdded = false;
702 function __construct( $params ) {
703 if( !in_array( 'other', $params['options'] ) ) {
704 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
707 parent
::__construct( $params );
710 static function forceToStringRecursive( $array ) {
711 if ( is_array($array) ) {
712 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
714 return strval($array);
718 function getInputHTML( $value ) {
719 $valInSelect = false;
721 if( $value !== false )
722 $valInSelect = in_array( $value,
723 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
725 $selected = $valInSelect ?
$value : 'other';
727 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
729 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
730 $select->addOptions( $opts );
732 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
734 $tbAttribs = array( 'id' => $this->mID
. '-other' );
735 if( !empty( $this->mParams
['disabled'] ) ) {
736 $select->setAttribute( 'disabled', 'disabled' );
737 $tbAttribs['disabled'] = 'disabled';
740 $select = $select->getHTML();
742 if ( isset( $this->mParams
['maxlength'] ) ) {
743 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
746 $textbox = Xml
::input( $this->mName
. '-other',
748 $valInSelect ?
'' : $value,
751 return "$select<br/>\n$textbox";
754 function loadDataFromRequest( $request ) {
755 if( $request->getCheck( $this->mName
) ) {
756 $val = $request->getText( $this->mName
);
758 if( $val == 'other' ) {
759 $val = $request->getText( $this->mName
. '-other' );
764 return $this->getDefault();
769 class HTMLMultiSelectField
extends HTMLFormField
{
770 function validate( $value, $alldata ) {
771 $p = parent
::validate( $value, $alldata );
772 if( $p !== true ) return $p;
774 if( !is_array( $value ) ) return false;
776 // If all options are valid, array_intersect of the valid options and the provided
777 // options will return the provided options.
778 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
780 $validValues = array_intersect( $value, $validOptions );
781 if ( count( $validValues ) == count( $value ) )
784 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
787 function getInputHTML( $value ) {
788 $html = $this->formatOptions( $this->mParams
['options'], $value );
793 function formatOptions( $options, $value ) {
797 if ( !empty( $this->mParams
['disabled'] ) ) {
798 $attribs['disabled'] = 'disabled';
801 foreach( $options as $label => $info ) {
802 if( is_array( $info ) ) {
803 $html .= Xml
::tags( 'h1', null, $label ) . "\n";
804 $html .= $this->formatOptions( $info, $value );
806 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
808 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
809 $attribs +
$thisAttribs );
810 $checkbox .= ' ' . Xml
::tags( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
812 $html .= $checkbox . '<br />';
819 function loadDataFromRequest( $request ) {
820 // won't work with getCheck
821 if( $request->getCheck( 'wpEditToken' ) ) {
822 $arr = $request->getArray( $this->mName
);
829 return $this->getDefault();
833 function getDefault() {
834 if ( isset( $this->mDefault
) ) {
835 return $this->mDefault
;
842 class HTMLRadioField
extends HTMLFormField
{
843 function validate( $value, $alldata ) {
844 $p = parent
::validate( $value, $alldata );
845 if( $p !== true ) return $p;
847 if( !is_string( $value ) && !is_int( $value ) )
850 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
852 if ( in_array( $value, $validOptions ) )
855 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
858 function getInputHTML( $value ) {
859 $html = $this->formatOptions( $this->mParams
['options'], $value );
864 function formatOptions( $options, $value ) {
868 if ( !empty( $this->mParams
['disabled'] ) ) {
869 $attribs['disabled'] = 'disabled';
872 foreach( $options as $label => $info ) {
873 if( is_array( $info ) ) {
874 $html .= Xml
::tags( 'h1', null, $label ) . "\n";
875 $html .= $this->formatOptions( $info, $value );
877 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
878 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
879 $attribs +
array( 'id' => $id ) );
881 Xml
::tags( 'label', array( 'for' => $id ), $label );
891 class HTMLInfoField
extends HTMLFormField
{
892 function __construct( $info ) {
893 $info['nodata'] = true;
895 parent
::__construct( $info );
898 function getInputHTML( $value ) {
899 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
902 function getTableRow( $value ) {
903 if ( !empty( $this->mParams
['rawrow'] ) ) {
907 return parent
::getTableRow( $value );