5 static $jsAdded = false;
7 /* The descriptor is an array of arrays.
9 'fieldname' => array( 'section' => 'section/subsection',
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 # HTMLTextField will output the correct type="" attribute automagically.
27 # There are about four zillion other HTML 5 input types, like url, but
28 # we don't use those at the moment, so no point in adding all of them.
29 'email' => '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
{
520 return isset( $this->mParams
['size'] ) ?
$this->mParams
['size'] : 45;
523 function getInputHTML( $value ) {
525 $attribs = array( 'id' => $this->mID
);
527 if ( isset( $this->mParams
['maxlength'] ) ) {
528 $attribs['maxlength'] = $this->mParams
['maxlength'];
531 if ( !empty( $this->mParams
['disabled'] ) ) {
532 $attribs['disabled'] = 'disabled';
536 # TODO: Enforce pattern, step, required, readonly on the server
538 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
539 'placeholder' ) as $param ) {
540 if ( isset( $this->mParams
[$param] ) ) {
541 $attribs[$param] = $this->mParams
[$param];
544 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
546 if ( isset( $this->mParams
[$param] ) ) {
547 $attribs[$param] = '';
550 if ( isset( $this->mParams
['type'] ) ) {
551 switch ( $this->mParams
['type'] ) {
553 $attribs['type'] = 'email';
556 $attribs['type'] = 'number';
559 $attribs['type'] = 'number';
560 $attribs['step'] = 'any';
575 class HTMLFloatField
extends HTMLTextField
{
577 return isset( $this->mParams
['size'] ) ?
$this->mParams
['size'] : 20;
580 function validate( $value, $alldata ) {
581 $p = parent
::validate( $value, $alldata );
583 if ( $p !== true ) return $p;
585 if ( floatval( $value ) != $value ) {
586 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
591 # The "int" part of these message names is rather confusing. They make
592 # equal sense for all numbers.
593 if ( isset( $this->mParams
['min'] ) ) {
594 $min = $this->mParams
['min'];
596 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
599 if ( isset( $this->mParams
['max'] ) ) {
600 $max = $this->mParams
['max'];
602 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
609 class HTMLIntField
extends HTMLFloatField
{
610 function validate( $value, $alldata ) {
611 $p = parent
::validate( $value, $alldata );
613 if ( $p !== true ) return $p;
615 if ( intval( $value ) != $value ) {
616 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
623 class HTMLCheckField
extends HTMLFormField
{
624 function getInputHTML( $value ) {
625 if ( !empty( $this->mParams
['invert'] ) )
628 $attr = array( 'id' => $this->mID
);
629 if( !empty( $this->mParams
['disabled'] ) ) {
630 $attr['disabled'] = 'disabled';
633 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
634 Xml
::tags( 'label', array( 'for' => $this->mID
), $this->mLabel
);
637 function getLabel() {
638 return ' '; // In the right-hand column.
641 function loadDataFromRequest( $request ) {
643 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
647 // GetCheck won't work like we want for checks.
648 if( $request->getCheck( 'wpEditToken' ) ) {
649 // XOR has the following truth table, which is what we want
650 // INVERT VALUE | OUTPUT
653 // false false | false
655 return $request->getBool( $this->mName
) xor $invert;
657 return $this->getDefault();
662 class HTMLSelectField
extends HTMLFormField
{
664 function validate( $value, $alldata ) {
665 $p = parent
::validate( $value, $alldata );
666 if( $p !== true ) return $p;
668 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
669 if ( in_array( $value, $validOptions ) )
672 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
675 function getInputHTML( $value ) {
676 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
678 // If one of the options' 'name' is int(0), it is automatically selected.
679 // because PHP sucks and things int(0) == 'some string'.
680 // Working around this by forcing all of them to strings.
681 $options = array_map( 'strval', $this->mParams
['options'] );
683 if( !empty( $this->mParams
['disabled'] ) ) {
684 $select->setAttribute( 'disabled', 'disabled' );
687 $select->addOptions( $options );
689 return $select->getHTML();
693 class HTMLSelectOrOtherField
extends HTMLTextField
{
694 static $jsAdded = false;
696 function __construct( $params ) {
697 if( !in_array( 'other', $params['options'] ) ) {
698 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
701 parent
::__construct( $params );
704 static function forceToStringRecursive( $array ) {
705 if ( is_array($array) ) {
706 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array);
708 return strval($array);
712 function getInputHTML( $value ) {
713 $valInSelect = false;
715 if( $value !== false )
716 $valInSelect = in_array( $value,
717 HTMLFormField
::flattenOptions( $this->mParams
['options'] ) );
719 $selected = $valInSelect ?
$value : 'other';
721 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
723 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
724 $select->addOptions( $opts );
726 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
728 $tbAttribs = array( 'id' => $this->mID
. '-other' );
729 if( !empty( $this->mParams
['disabled'] ) ) {
730 $select->setAttribute( 'disabled', 'disabled' );
731 $tbAttribs['disabled'] = 'disabled';
734 $select = $select->getHTML();
736 if ( isset( $this->mParams
['maxlength'] ) ) {
737 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
740 $textbox = Xml
::input( $this->mName
. '-other',
742 $valInSelect ?
'' : $value,
745 return "$select<br/>\n$textbox";
748 function loadDataFromRequest( $request ) {
749 if( $request->getCheck( $this->mName
) ) {
750 $val = $request->getText( $this->mName
);
752 if( $val == 'other' ) {
753 $val = $request->getText( $this->mName
. '-other' );
758 return $this->getDefault();
763 class HTMLMultiSelectField
extends HTMLFormField
{
764 function validate( $value, $alldata ) {
765 $p = parent
::validate( $value, $alldata );
766 if( $p !== true ) return $p;
768 if( !is_array( $value ) ) return false;
770 // If all options are valid, array_intersect of the valid options and the provided
771 // options will return the provided options.
772 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
774 $validValues = array_intersect( $value, $validOptions );
775 if ( count( $validValues ) == count( $value ) )
778 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
781 function getInputHTML( $value ) {
782 $html = $this->formatOptions( $this->mParams
['options'], $value );
787 function formatOptions( $options, $value ) {
791 if ( !empty( $this->mParams
['disabled'] ) ) {
792 $attribs['disabled'] = 'disabled';
795 foreach( $options as $label => $info ) {
796 if( is_array( $info ) ) {
797 $html .= Xml
::tags( 'h1', null, $label ) . "\n";
798 $html .= $this->formatOptions( $info, $value );
800 $thisAttribs = array( 'id' => $this->mID
. "-$info", 'value' => $info );
802 $checkbox = Xml
::check( $this->mName
. '[]', in_array( $info, $value ),
803 $attribs +
$thisAttribs );
804 $checkbox .= ' ' . Xml
::tags( 'label', array( 'for' => $this->mID
. "-$info" ), $label );
806 $html .= $checkbox . '<br />';
813 function loadDataFromRequest( $request ) {
814 // won't work with getCheck
815 if( $request->getCheck( 'wpEditToken' ) ) {
816 $arr = $request->getArray( $this->mName
);
823 return $this->getDefault();
827 function getDefault() {
828 if ( isset( $this->mDefault
) ) {
829 return $this->mDefault
;
836 class HTMLRadioField
extends HTMLFormField
{
837 function validate( $value, $alldata ) {
838 $p = parent
::validate( $value, $alldata );
839 if( $p !== true ) return $p;
841 if( !is_string( $value ) && !is_int( $value ) )
844 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
846 if ( in_array( $value, $validOptions ) )
849 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
852 function getInputHTML( $value ) {
853 $html = $this->formatOptions( $this->mParams
['options'], $value );
858 function formatOptions( $options, $value ) {
862 if ( !empty( $this->mParams
['disabled'] ) ) {
863 $attribs['disabled'] = 'disabled';
866 foreach( $options as $label => $info ) {
867 if( is_array( $info ) ) {
868 $html .= Xml
::tags( 'h1', null, $label ) . "\n";
869 $html .= $this->formatOptions( $info, $value );
871 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
872 $html .= Xml
::radio( $this->mName
, $info, $info == $value,
873 $attribs +
array( 'id' => $id ) );
875 Xml
::tags( 'label', array( 'for' => $id ), $label );
885 class HTMLInfoField
extends HTMLFormField
{
886 function __construct( $info ) {
887 $info['nodata'] = true;
889 parent
::__construct( $info );
892 function getInputHTML( $value ) {
893 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
896 function getTableRow( $value ) {
897 if ( !empty( $this->mParams
['rawrow'] ) ) {
901 return parent
::getTableRow( $value );