3 * Object handling generic submission, CSRF protection, layout and
4 * other logic for UI forms. in a reusable manner.
6 * In order to generate the form, the HTMLForm object takes an array
7 * structure detailing the form fields available. Each element of the
8 * array is a basic property-list, including the type of field, the
9 * label it is to be given in the form, callbacks for validation and
10 * 'filtering', and other pertinent information.
12 * Field types are implemented as subclasses of the generic HTMLFormField
13 * object, and typically implement at least getInputHTML, which generates
14 * the HTML for the input field to be placed in the table.
16 * The constructor input is an associative array of $fieldname => $info,
17 * where $info is an Associative Array with any of the following:
19 * 'class' -- the subclass of HTMLFormField that will be used
20 * to create the object. *NOT* the CSS class!
21 * 'type' -- roughly translates into the <select> type attribute.
22 * if 'class' is not specified, this is used as a map
23 * through HTMLForm::$typeMappings to get the class name.
24 * 'default' -- default value when the form is displayed
25 * 'id' -- HTML id attribute
26 * 'cssclass' -- CSS class
27 * 'options' -- varies according to the specific object.
28 * 'label-message' -- message key for a message to use as the label.
29 * can be an array of msg key and then parameters to
31 * 'label' -- alternatively, a raw text message. Overridden by
33 * 'help-message' -- message key for a message to use as a help text.
34 * can be an array of msg key and then parameters to
36 * Overwrites 'help-messages'.
37 * 'help-messages' -- array of message key. As above, each item can
38 * be an array of msg key and then parameters.
39 * Overwrites 'help-message'.
40 * 'required' -- passed through to the object, indicating that it
41 * is a required field.
42 * 'size' -- the length of text fields
43 * 'filter-callback -- a function name to give you the chance to
44 * massage the inputted value before it's processed.
45 * @see HTMLForm::filter()
46 * 'validation-callback' -- a function name to give you the chance
47 * to impose extra validation on the field input.
48 * @see HTMLForm::validate()
49 * 'name' -- By default, the 'name' attribute of the input field
50 * is "wp{$fieldname}". If you want a different name
51 * (eg one without the "wp" prefix), specify it here and
52 * it will be used without modification.
54 * TODO: Document 'section' / 'subsection' stuff
57 static $jsAdded = false;
59 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
60 static $typeMappings = array(
61 'text' => 'HTMLTextField',
62 'textarea' => 'HTMLTextAreaField',
63 'select' => 'HTMLSelectField',
64 'radio' => 'HTMLRadioField',
65 'multiselect' => 'HTMLMultiSelectField',
66 'check' => 'HTMLCheckField',
67 'toggle' => 'HTMLCheckField',
68 'int' => 'HTMLIntField',
69 'float' => 'HTMLFloatField',
70 'info' => 'HTMLInfoField',
71 'selectorother' => 'HTMLSelectOrOtherField',
72 'submit' => 'HTMLSubmitField',
73 'hidden' => 'HTMLHiddenField',
74 'edittools' => 'HTMLEditTools',
76 # HTMLTextField will output the correct type="" attribute automagically.
77 # There are about four zillion other HTML5 input types, like url, but
78 # we don't use those at the moment, so no point in adding all of them.
79 'email' => 'HTMLTextField',
80 'password' => 'HTMLTextField',
83 protected $mMessagePrefix;
84 protected $mFlatFields;
85 protected $mFieldTree;
86 protected $mShowReset = false;
89 protected $mSubmitCallback;
90 protected $mValidationErrorMessage;
93 protected $mHeader = '';
94 protected $mFooter = '';
95 protected $mSectionHeaders = array();
96 protected $mSectionFooters = array();
97 protected $mPost = '';
100 protected $mSubmitID;
101 protected $mSubmitName;
102 protected $mSubmitText;
103 protected $mSubmitTooltip;
105 protected $mMethod = 'post';
107 protected $mUseMultipart = false;
108 protected $mHiddenFields = array();
109 protected $mButtons = array();
111 protected $mWrapperLegend = false;
114 * Build a new HTMLForm from an array of field attributes
115 * @param $descriptor Array of Field constructs, as described above
116 * @param $messagePrefix String a prefix to go in front of default messages
118 public function __construct( $descriptor, $messagePrefix = '' ) {
119 $this->mMessagePrefix
= $messagePrefix;
121 // Expand out into a tree.
122 $loadedDescriptor = array();
123 $this->mFlatFields
= array();
125 foreach ( $descriptor as $fieldname => $info ) {
126 $section = isset( $info['section'] )
130 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
131 $this->mUseMultipart
= true;
134 $field = self
::loadInputFromParameters( $fieldname, $info );
135 $field->mParent
= $this;
137 $setSection =& $loadedDescriptor;
139 $sectionParts = explode( '/', $section );
141 while ( count( $sectionParts ) ) {
142 $newName = array_shift( $sectionParts );
144 if ( !isset( $setSection[$newName] ) ) {
145 $setSection[$newName] = array();
148 $setSection =& $setSection[$newName];
152 $setSection[$fieldname] = $field;
153 $this->mFlatFields
[$fieldname] = $field;
156 $this->mFieldTree
= $loadedDescriptor;
160 * Add the HTMLForm-specific JavaScript, if it hasn't been
163 static function addJS() {
164 if ( self
::$jsAdded ) return;
168 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
172 * Initialise a new Object for the field
173 * @param $descriptor input Descriptor, as described above
174 * @return HTMLFormField subclass
176 static function loadInputFromParameters( $fieldname, $descriptor ) {
177 if ( isset( $descriptor['class'] ) ) {
178 $class = $descriptor['class'];
179 } elseif ( isset( $descriptor['type'] ) ) {
180 $class = self
::$typeMappings[$descriptor['type']];
181 $descriptor['class'] = $class;
185 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
188 $descriptor['fieldname'] = $fieldname;
190 $obj = new $class( $descriptor );
196 * Prepare form for submission
198 function prepareForm() {
199 # Check if we have the info we need
200 if ( ! $this->mTitle
) {
201 throw new MWException( "You must call setTitle() on an HTMLForm" );
204 // FIXME shouldn't this be closer to displayForm() ?
207 # Load data from the request.
212 * Try submitting, with edit token check first
213 * @return Status|boolean
215 function tryAuthorizedSubmit() {
216 global $wgUser, $wgRequest;
217 $editToken = $wgRequest->getVal( 'wpEditToken' );
220 if ( $this->getMethod() != 'post' ||
$wgUser->matchEditToken( $editToken ) ) {
221 $result = $this->trySubmit();
227 * The here's-one-I-made-earlier option: do the submission if
228 * posted, or display the form with or without funky valiation
230 * @return Bool or Status whether submission was successful.
233 $this->prepareForm();
235 $result = $this->tryAuthorizedSubmit();
236 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
240 $this->displayForm( $result );
245 * Validate all the fields, and call the submision callback
246 * function if everything is kosher.
247 * @return Mixed Bool true == Successful submission, Bool false
248 * == No submission attempted, anything else == Error to
251 function trySubmit() {
252 # Check for validation
253 foreach ( $this->mFlatFields
as $fieldname => $field ) {
254 if ( !empty( $field->mParams
['nodata'] ) ) {
257 if ( $field->validate(
258 $this->mFieldData
[$fieldname],
262 return isset( $this->mValidationErrorMessage
)
263 ?
$this->mValidationErrorMessage
264 : array( 'htmlform-invalid-input' );
268 $callback = $this->mSubmitCallback
;
270 $data = $this->filterDataForSubmit( $this->mFieldData
);
272 $res = call_user_func( $callback, $data );
278 * Set a callback to a function to do something with the form
279 * once it's been successfully validated.
280 * @param $cb String function name. The function will be passed
281 * the output from HTMLForm::filterDataForSubmit, and must
282 * return Bool true on success, Bool false if no submission
283 * was attempted, or String HTML output to display on error.
285 function setSubmitCallback( $cb ) {
286 $this->mSubmitCallback
= $cb;
290 * Set a message to display on a validation error.
291 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
292 * (so each entry can be either a String or Array)
294 function setValidationErrorMessage( $msg ) {
295 $this->mValidationErrorMessage
= $msg;
299 * Set the introductory message, overwriting any existing message.
300 * @param $msg String complete text of message to display
302 function setIntro( $msg ) { $this->mPre
= $msg; }
305 * Add introductory text.
306 * @param $msg String complete text of message to display
308 function addPreText( $msg ) { $this->mPre
.= $msg; }
311 * Add header text, inside the form.
312 * @param $msg String complete text of message to display
314 function addHeaderText( $msg, $section = null ) {
315 if ( is_null( $section ) ) {
316 $this->mHeader
.= $msg;
318 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
319 $this->mSectionHeaders
[$section] = '';
321 $this->mSectionHeaders
[$section] .= $msg;
326 * Add footer text, inside the form.
327 * @param $msg String complete text of message to display
329 function addFooterText( $msg, $section = null ) {
330 if ( is_null( $section ) ) {
331 $this->mFooter
.= $msg;
333 if ( !isset( $this->mSectionFooters
[$section] ) ) {
334 $this->mSectionFooters
[$section] = '';
336 $this->mSectionFooters
[$section] .= $msg;
341 * Add text to the end of the display.
342 * @param $msg String complete text of message to display
344 function addPostText( $msg ) { $this->mPost
.= $msg; }
347 * Add a hidden field to the output
348 * @param $name String field name. This will be used exactly as entered
349 * @param $value String field value
350 * @param $attribs Array
352 public function addHiddenField( $name, $value, $attribs = array() ) {
353 $attribs +
= array( 'name' => $name );
354 $this->mHiddenFields
[] = array( $value, $attribs );
357 public function addButton( $name, $value, $id = null, $attribs = null ) {
358 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
362 * Display the form (sending to wgOut), with an appropriate error
363 * message or stack of messages, and any validation errors, etc.
364 * @param $submitResult Mixed output from HTMLForm::trySubmit()
366 function displayForm( $submitResult ) {
369 # For good measure (it is the default)
370 $wgOut->preventClickjacking();
373 . $this->getErrors( $submitResult )
376 . $this->getHiddenFields()
377 . $this->getButtons()
381 $html = $this->wrapForm( $html );
391 * Wrap the form innards in an actual <form> element
392 * @param $html String HTML contents to wrap.
393 * @return String wrapped HTML.
395 function wrapForm( $html ) {
397 # Include a <fieldset> wrapper for style, if requested.
398 if ( $this->mWrapperLegend
!== false ) {
399 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
401 # Use multipart/form-data
402 $encType = $this->mUseMultipart
403 ?
'multipart/form-data'
404 : 'application/x-www-form-urlencoded';
407 'action' => $this->getTitle()->getFullURL(),
408 'method' => $this->mMethod
,
409 'class' => 'visualClear',
410 'enctype' => $encType,
412 if ( !empty( $this->mId
) ) {
413 $attribs['id'] = $this->mId
;
416 return Html
::rawElement( 'form', $attribs, $html );
420 * Get the hidden fields that should go inside the form.
421 * @return String HTML.
423 function getHiddenFields() {
428 if( $this->getMethod() == 'post' ){
429 $html .= Html
::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
430 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
433 foreach ( $this->mHiddenFields
as $data ) {
434 list( $value, $attribs ) = $data;
435 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
442 * Get the submit and (potentially) reset buttons.
443 * @return String HTML.
445 function getButtons() {
449 if ( isset( $this->mSubmitID
) ) {
450 $attribs['id'] = $this->mSubmitID
;
453 if ( isset( $this->mSubmitName
) ) {
454 $attribs['name'] = $this->mSubmitName
;
457 if ( isset( $this->mSubmitTooltip
) ) {
459 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
462 $attribs['class'] = 'mw-htmlform-submit';
464 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
466 if ( $this->mShowReset
) {
467 $html .= Html
::element(
471 'value' => wfMsg( 'htmlform-reset' )
476 foreach ( $this->mButtons
as $button ) {
479 'name' => $button['name'],
480 'value' => $button['value']
483 if ( $button['attribs'] ) {
484 $attrs +
= $button['attribs'];
487 if ( isset( $button['id'] ) ) {
488 $attrs['id'] = $button['id'];
491 $html .= Html
::element( 'input', $attrs );
498 * Get the whole body of the form.
501 return $this->displaySection( $this->mFieldTree
);
505 * Format and display an error message stack.
506 * @param $errors Mixed String or Array of message keys
509 function getErrors( $errors ) {
510 if ( $errors instanceof Status
) {
512 $errorstr = $wgOut->parse( $errors->getWikiText() );
513 } elseif ( is_array( $errors ) ) {
514 $errorstr = $this->formatErrors( $errors );
520 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
525 * Format a stack of error messages into a single HTML string
526 * @param $errors Array of message keys/values
527 * @return String HTML, a <ul> list of errors
529 static function formatErrors( $errors ) {
532 foreach ( $errors as $error ) {
533 if ( is_array( $error ) ) {
534 $msg = array_shift( $error );
540 $errorstr .= Html
::rawElement(
543 wfMsgExt( $msg, array( 'parseinline' ), $error )
547 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
553 * Set the text for the submit button
554 * @param $t String plaintext.
556 function setSubmitText( $t ) {
557 $this->mSubmitText
= $t;
561 * Get the text for the submit button, either customised or a default.
562 * @return unknown_type
564 function getSubmitText() {
565 return $this->mSubmitText
567 : wfMsg( 'htmlform-submit' );
570 public function setSubmitName( $name ) {
571 $this->mSubmitName
= $name;
574 public function setSubmitTooltip( $name ) {
575 $this->mSubmitTooltip
= $name;
579 * Set the id for the submit button.
580 * @param $t String. FIXME: Integrity is *not* validated
582 function setSubmitID( $t ) {
583 $this->mSubmitID
= $t;
586 public function setId( $id ) {
590 * Prompt the whole form to be wrapped in a <fieldset>, with
591 * this text as its <legend> element.
592 * @param $legend String HTML to go inside the <legend> element.
595 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
598 * Set the prefix for various default messages
599 * TODO: currently only used for the <fieldset> legend on forms
600 * with multiple sections; should be used elsewhre?
603 function setMessagePrefix( $p ) {
604 $this->mMessagePrefix
= $p;
608 * Set the title for form submission
609 * @param $t Title of page the form is on/should be posted to
611 function setTitle( $t ) {
619 function getTitle() {
620 return $this->mTitle
;
624 * Set the method used to submit the form
625 * @param $method String
627 public function setMethod( $method='post' ){
628 $this->mMethod
= $method;
631 public function getMethod(){
632 return $this->mMethod
;
639 function displaySection( $fields, $sectionName = '' ) {
641 $subsectionHtml = '';
642 $hasLeftColumn = false;
644 foreach ( $fields as $key => $value ) {
645 if ( is_object( $value ) ) {
646 $v = empty( $value->mParams
['nodata'] )
647 ?
$this->mFieldData
[$key]
648 : $value->getDefault();
649 $tableHtml .= $value->getTableRow( $v );
651 if ( $value->getLabel() != ' ' )
652 $hasLeftColumn = true;
653 } elseif ( is_array( $value ) ) {
654 $section = $this->displaySection( $value, $key );
655 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
656 if ( isset( $this->mSectionHeaders
[$key] ) ) {
657 $section = $this->mSectionHeaders
[$key] . $section;
659 if ( isset( $this->mSectionFooters
[$key] ) ) {
660 $section .= $this->mSectionFooters
[$key];
662 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
668 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
669 $classes[] = 'mw-htmlform-nolabel';
673 'class' => implode( ' ', $classes ),
676 if ( $sectionName ) {
677 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
680 $tableHtml = Html
::rawElement( 'table', $attribs,
681 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
683 return $subsectionHtml . "\n" . $tableHtml;
687 * Construct the form fields from the Descriptor array
689 function loadData() {
692 $fieldData = array();
694 foreach ( $this->mFlatFields
as $fieldname => $field ) {
695 if ( !empty( $field->mParams
['nodata'] ) ) {
697 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
698 $fieldData[$fieldname] = $field->getDefault();
700 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
705 foreach ( $fieldData as $name => &$value ) {
706 $field = $this->mFlatFields
[$name];
707 $value = $field->filter( $value, $this->mFlatFields
);
710 $this->mFieldData
= $fieldData;
714 * Stop a reset button being shown for this form
715 * @param $suppressReset Bool set to false to re-enable the
718 function suppressReset( $suppressReset = true ) {
719 $this->mShowReset
= !$suppressReset;
723 * Overload this if you want to apply special filtration routines
724 * to the form as a whole, after it's submitted but before it's
727 * @return unknown_type
729 function filterDataForSubmit( $data ) {
735 * The parent class to generate form fields. Any field type should
736 * be a subclass of this.
738 abstract class HTMLFormField
{
740 protected $mValidationCallback;
741 protected $mFilterCallback;
744 protected $mLabel; # String label. Set on construction
746 protected $mClass = '';
751 * This function must be implemented to return the HTML to generate
752 * the input object itself. It should not implement the surrounding
753 * table cells/rows, or labels/help messages.
754 * @param $value String the value to set the input to; eg a default
755 * text for a text input.
756 * @return String valid HTML.
758 abstract function getInputHTML( $value );
761 * Override this function to add specific validation checks on the
762 * field input. Don't forget to call parent::validate() to ensure
763 * that the user-defined callback mValidationCallback is still run
764 * @param $value String the value the field was submitted with
765 * @param $alldata Array the data collected from the form
766 * @return Mixed Bool true on success, or String error to display.
768 function validate( $value, $alldata ) {
769 if ( isset( $this->mValidationCallback
) ) {
770 return call_user_func( $this->mValidationCallback
, $value, $alldata );
773 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
774 return wfMsgExt( 'htmlform-required', 'parseinline' );
780 function filter( $value, $alldata ) {
781 if ( isset( $this->mFilterCallback
) ) {
782 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
789 * Should this field have a label, or is there no input element with the
790 * appropriate id for the label to point to?
792 * @return bool True to output a label, false to suppress
794 protected function needsLabel() {
799 * Get the value that this input has been set to from a posted form,
800 * or the input's default value if it has not been set.
801 * @param $request WebRequest
802 * @return String the value
804 function loadDataFromRequest( $request ) {
805 if ( $request->getCheck( $this->mName
) ) {
806 return $request->getText( $this->mName
);
808 return $this->getDefault();
813 * Initialise the object
814 * @param $params Associative Array. See HTMLForm doc for syntax.
816 function __construct( $params ) {
817 $this->mParams
= $params;
819 # Generate the label from a message, if possible
820 if ( isset( $params['label-message'] ) ) {
821 $msgInfo = $params['label-message'];
823 if ( is_array( $msgInfo ) ) {
824 $msg = array_shift( $msgInfo );
830 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
831 } elseif ( isset( $params['label'] ) ) {
832 $this->mLabel
= $params['label'];
835 $this->mName
= "wp{$params['fieldname']}";
836 if ( isset( $params['name'] ) ) {
837 $this->mName
= $params['name'];
840 $validName = Sanitizer
::escapeId( $this->mName
);
841 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
842 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
845 $this->mID
= "mw-input-{$this->mName}";
847 if ( isset( $params['default'] ) ) {
848 $this->mDefault
= $params['default'];
851 if ( isset( $params['id'] ) ) {
853 $validId = Sanitizer
::escapeId( $id );
855 if ( $id != $validId ) {
856 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
862 if ( isset( $params['cssclass'] ) ) {
863 $this->mClass
= $params['cssclass'];
866 if ( isset( $params['validation-callback'] ) ) {
867 $this->mValidationCallback
= $params['validation-callback'];
870 if ( isset( $params['filter-callback'] ) ) {
871 $this->mFilterCallback
= $params['filter-callback'];
876 * Get the complete table row for the input, including help text,
877 * labels, and whatever.
878 * @param $value String the value to set the input to.
879 * @return String complete HTML table row.
881 function getTableRow( $value ) {
882 # Check for invalid data.
885 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
887 $cellAttributes = array();
888 $verticalLabel = false;
890 if ( !empty($this->mParams
['vertical-label']) ) {
891 $cellAttributes['colspan'] = 2;
892 $verticalLabel = true;
895 if ( $errors === true ||
( !$wgRequest->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
898 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
901 $label = $this->getLabelHtml( $cellAttributes );
902 $field = Html
::rawElement(
904 array( 'class' => 'mw-input' ) +
$cellAttributes,
905 $this->getInputHTML( $value ) . "\n$errors"
908 $fieldType = get_class( $this );
910 if ($verticalLabel) {
911 $html = Html
::rawElement( 'tr',
912 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
913 $html .= Html
::rawElement( 'tr',
914 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
917 $html = Html
::rawElement( 'tr',
918 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
924 if ( isset( $this->mParams
['help-message'] ) ) {
925 $msg = $this->mParams
['help-message'];
926 $helptext = wfMsgExt( $msg, 'parseinline' );
927 if ( wfEmptyMsg( $msg, $helptext ) ) {
931 } elseif ( isset( $this->mParams
['help-messages'] ) ) {
932 # help-message can be passed a message key (string) or an array containing
933 # a message key and additional parameters. This makes it impossible to pass
934 # an array of message key
935 foreach( $this->mParams
['help-messages'] as $msg ) {
936 $candidate = wfMsgExt( $msg, 'parseinline' );
937 if( wfEmptyMsg( $msg ) ) {
940 $helptext .= $candidate; // append message
942 } elseif ( isset( $this->mParams
['help'] ) ) {
943 $helptext = $this->mParams
['help'];
946 if ( !is_null( $helptext ) ) {
947 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
949 $row = Html
::rawElement( 'tr', array(), $row );
956 function getLabel() {
957 return $this->mLabel
;
959 function getLabelHtml( $cellAttributes = array() ) {
960 # Don't output a for= attribute for labels with no associated input.
961 # Kind of hacky here, possibly we don't want these to be <label>s at all.
964 if ( $this->needsLabel() ) {
965 $for['for'] = $this->mID
;
968 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
969 Html
::rawElement( 'label', $for, $this->getLabel() )
973 function getDefault() {
974 if ( isset( $this->mDefault
) ) {
975 return $this->mDefault
;
982 * Returns the attributes required for the tooltip and accesskey.
984 * @return array Attributes
986 public function getTooltipAndAccessKey() {
987 if ( empty( $this->mParams
['tooltip'] ) ) {
993 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
997 * flatten an array of options to a single array, for instance,
998 * a set of <options> inside <optgroups>.
999 * @param $options Associative Array with values either Strings
1001 * @return Array flattened input
1003 public static function flattenOptions( $options ) {
1004 $flatOpts = array();
1006 foreach ( $options as $value ) {
1007 if ( is_array( $value ) ) {
1008 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1010 $flatOpts[] = $value;
1018 class HTMLTextField
extends HTMLFormField
{
1019 function getSize() {
1020 return isset( $this->mParams
['size'] )
1021 ?
$this->mParams
['size']
1025 function getInputHTML( $value ) {
1028 'name' => $this->mName
,
1029 'size' => $this->getSize(),
1031 ) +
$this->getTooltipAndAccessKey();
1033 if ( isset( $this->mParams
['maxlength'] ) ) {
1034 $attribs['maxlength'] = $this->mParams
['maxlength'];
1037 if ( !empty( $this->mParams
['disabled'] ) ) {
1038 $attribs['disabled'] = 'disabled';
1041 # TODO: Enforce pattern, step, required, readonly on the server side as
1043 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1044 'placeholder' ) as $param ) {
1045 if ( isset( $this->mParams
[$param] ) ) {
1046 $attribs[$param] = $this->mParams
[$param];
1050 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1051 if ( isset( $this->mParams
[$param] ) ) {
1052 $attribs[$param] = '';
1056 # Implement tiny differences between some field variants
1057 # here, rather than creating a new class for each one which
1058 # is essentially just a clone of this one.
1059 if ( isset( $this->mParams
['type'] ) ) {
1060 switch ( $this->mParams
['type'] ) {
1062 $attribs['type'] = 'email';
1065 $attribs['type'] = 'number';
1068 $attribs['type'] = 'number';
1069 $attribs['step'] = 'any';
1074 $attribs['type'] = $this->mParams
['type'];
1079 return Html
::element( 'input', $attribs );
1082 class HTMLTextAreaField
extends HTMLFormField
{
1083 function getCols() {
1084 return isset( $this->mParams
['cols'] )
1085 ?
$this->mParams
['cols']
1089 function getRows() {
1090 return isset( $this->mParams
['rows'] )
1091 ?
$this->mParams
['rows']
1095 function getInputHTML( $value ) {
1098 'name' => $this->mName
,
1099 'cols' => $this->getCols(),
1100 'rows' => $this->getRows(),
1101 ) +
$this->getTooltipAndAccessKey();
1104 if ( !empty( $this->mParams
['disabled'] ) ) {
1105 $attribs['disabled'] = 'disabled';
1108 if ( !empty( $this->mParams
['readonly'] ) ) {
1109 $attribs['readonly'] = 'readonly';
1112 foreach ( array( 'required', 'autofocus' ) as $param ) {
1113 if ( isset( $this->mParams
[$param] ) ) {
1114 $attribs[$param] = '';
1118 return Html
::element( 'textarea', $attribs, $value );
1123 * A field that will contain a numeric value
1125 class HTMLFloatField
extends HTMLTextField
{
1126 function getSize() {
1127 return isset( $this->mParams
['size'] )
1128 ?
$this->mParams
['size']
1132 function validate( $value, $alldata ) {
1133 $p = parent
::validate( $value, $alldata );
1135 if ( $p !== true ) {
1139 $value = trim( $value );
1141 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1142 # with the addition that a leading '+' sign is ok.
1143 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1144 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1147 # The "int" part of these message names is rather confusing.
1148 # They make equal sense for all numbers.
1149 if ( isset( $this->mParams
['min'] ) ) {
1150 $min = $this->mParams
['min'];
1152 if ( $min > $value ) {
1153 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1157 if ( isset( $this->mParams
['max'] ) ) {
1158 $max = $this->mParams
['max'];
1160 if ( $max < $value ) {
1161 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1170 * A field that must contain a number
1172 class HTMLIntField
extends HTMLFloatField
{
1173 function validate( $value, $alldata ) {
1174 $p = parent
::validate( $value, $alldata );
1176 if ( $p !== true ) {
1180 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1181 # with the addition that a leading '+' sign is ok. Note that leading zeros
1182 # are fine, and will be left in the input, which is useful for things like
1183 # phone numbers when you know that they are integers (the HTML5 type=tel
1184 # input does not require its value to be numeric). If you want a tidier
1185 # value to, eg, save in the DB, clean it up with intval().
1186 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1188 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1198 class HTMLCheckField
extends HTMLFormField
{
1199 function getInputHTML( $value ) {
1200 if ( !empty( $this->mParams
['invert'] ) ) {
1204 $attr = $this->getTooltipAndAccessKey();
1205 $attr['id'] = $this->mID
;
1207 if ( !empty( $this->mParams
['disabled'] ) ) {
1208 $attr['disabled'] = 'disabled';
1211 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1212 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1216 * For a checkbox, the label goes on the right hand side, and is
1217 * added in getInputHTML(), rather than HTMLFormField::getRow()
1219 function getLabel() {
1223 function loadDataFromRequest( $request ) {
1225 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1229 // GetCheck won't work like we want for checks.
1230 if ( $request->getCheck( 'wpEditToken' ) ) {
1231 // XOR has the following truth table, which is what we want
1232 // INVERT VALUE | OUTPUT
1233 // true true | false
1234 // false true | true
1235 // false false | false
1236 // true false | true
1237 return $request->getBool( $this->mName
) xor $invert;
1239 return $this->getDefault();
1245 * A select dropdown field. Basically a wrapper for Xmlselect class
1247 class HTMLSelectField
extends HTMLFormField
{
1248 function validate( $value, $alldata ) {
1249 $p = parent
::validate( $value, $alldata );
1251 if ( $p !== true ) {
1255 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1257 if ( in_array( $value, $validOptions ) )
1260 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1263 function getInputHTML( $value ) {
1264 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1266 # If one of the options' 'name' is int(0), it is automatically selected.
1267 # because PHP sucks and things int(0) == 'some string'.
1268 # Working around this by forcing all of them to strings.
1269 foreach( $this->mParams
['options'] as $key => &$opt ){
1270 if( is_int( $opt ) ){
1271 $opt = strval( $opt );
1274 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1276 if ( !empty( $this->mParams
['disabled'] ) ) {
1277 $select->setAttribute( 'disabled', 'disabled' );
1280 $select->addOptions( $this->mParams
['options'] );
1282 return $select->getHTML();
1287 * Select dropdown field, with an additional "other" textbox.
1289 class HTMLSelectOrOtherField
extends HTMLTextField
{
1290 static $jsAdded = false;
1292 function __construct( $params ) {
1293 if ( !in_array( 'other', $params['options'], true ) ) {
1294 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1297 parent
::__construct( $params );
1300 static function forceToStringRecursive( $array ) {
1301 if ( is_array( $array ) ) {
1302 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1304 return strval( $array );
1308 function getInputHTML( $value ) {
1309 $valInSelect = false;
1311 if ( $value !== false ) {
1312 $valInSelect = in_array(
1314 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1318 $selected = $valInSelect ?
$value : 'other';
1320 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1322 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1323 $select->addOptions( $opts );
1325 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1327 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1329 if ( !empty( $this->mParams
['disabled'] ) ) {
1330 $select->setAttribute( 'disabled', 'disabled' );
1331 $tbAttribs['disabled'] = 'disabled';
1334 $select = $select->getHTML();
1336 if ( isset( $this->mParams
['maxlength'] ) ) {
1337 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1340 $textbox = Html
::input(
1341 $this->mName
. '-other',
1342 $valInSelect ?
'' : $value,
1347 return "$select<br />\n$textbox";
1350 function loadDataFromRequest( $request ) {
1351 if ( $request->getCheck( $this->mName
) ) {
1352 $val = $request->getText( $this->mName
);
1354 if ( $val == 'other' ) {
1355 $val = $request->getText( $this->mName
. '-other' );
1360 return $this->getDefault();
1366 * Multi-select field
1368 class HTMLMultiSelectField
extends HTMLFormField
{
1369 function validate( $value, $alldata ) {
1370 $p = parent
::validate( $value, $alldata );
1372 if ( $p !== true ) {
1376 if ( !is_array( $value ) ) {
1380 # If all options are valid, array_intersect of the valid options
1381 # and the provided options will return the provided options.
1382 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1384 $validValues = array_intersect( $value, $validOptions );
1385 if ( count( $validValues ) == count( $value ) ) {
1388 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1392 function getInputHTML( $value ) {
1393 $html = $this->formatOptions( $this->mParams
['options'], $value );
1398 function formatOptions( $options, $value ) {
1403 if ( !empty( $this->mParams
['disabled'] ) ) {
1404 $attribs['disabled'] = 'disabled';
1407 foreach ( $options as $label => $info ) {
1408 if ( is_array( $info ) ) {
1409 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1410 $html .= $this->formatOptions( $info, $value );
1412 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1414 $checkbox = Xml
::check(
1415 $this->mName
. '[]',
1416 in_array( $info, $value, true ),
1417 $attribs +
$thisAttribs );
1418 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1420 $html .= $checkbox . '<br />';
1427 function loadDataFromRequest( $request ) {
1428 # won't work with getCheck
1429 if ( $request->getCheck( 'wpEditToken' ) ) {
1430 $arr = $request->getArray( $this->mName
);
1438 return $this->getDefault();
1442 function getDefault() {
1443 if ( isset( $this->mDefault
) ) {
1444 return $this->mDefault
;
1450 protected function needsLabel() {
1456 * Radio checkbox fields.
1458 class HTMLRadioField
extends HTMLFormField
{
1459 function validate( $value, $alldata ) {
1460 $p = parent
::validate( $value, $alldata );
1462 if ( $p !== true ) {
1466 if ( !is_string( $value ) && !is_int( $value ) ) {
1470 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1472 if ( in_array( $value, $validOptions ) ) {
1475 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1480 * This returns a block of all the radio options, in one cell.
1481 * @see includes/HTMLFormField#getInputHTML()
1483 function getInputHTML( $value ) {
1484 $html = $this->formatOptions( $this->mParams
['options'], $value );
1489 function formatOptions( $options, $value ) {
1493 if ( !empty( $this->mParams
['disabled'] ) ) {
1494 $attribs['disabled'] = 'disabled';
1497 # TODO: should this produce an unordered list perhaps?
1498 foreach ( $options as $label => $info ) {
1499 if ( is_array( $info ) ) {
1500 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1501 $html .= $this->formatOptions( $info, $value );
1503 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1504 $html .= Xml
::radio(
1508 $attribs +
array( 'id' => $id )
1511 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1513 $html .= "<br />\n";
1520 protected function needsLabel() {
1526 * An information field (text blob), not a proper input.
1528 class HTMLInfoField
extends HTMLFormField
{
1529 function __construct( $info ) {
1530 $info['nodata'] = true;
1532 parent
::__construct( $info );
1535 function getInputHTML( $value ) {
1536 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1539 function getTableRow( $value ) {
1540 if ( !empty( $this->mParams
['rawrow'] ) ) {
1544 return parent
::getTableRow( $value );
1547 protected function needsLabel() {
1552 class HTMLHiddenField
extends HTMLFormField
{
1553 public function __construct( $params ) {
1554 parent
::__construct( $params );
1556 # Per HTML5 spec, hidden fields cannot be 'required'
1557 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1558 unset( $this->mParams
['required'] );
1561 public function getTableRow( $value ) {
1564 $params['id'] = $this->mID
;
1567 $this->mParent
->addHiddenField(
1576 public function getInputHTML( $value ) { return ''; }
1580 * Add a submit button inline in the form (as opposed to
1581 * HTMLForm::addButton(), which will add it at the end).
1583 class HTMLSubmitField
extends HTMLFormField
{
1585 function __construct( $info ) {
1586 $info['nodata'] = true;
1587 parent
::__construct( $info );
1590 function getInputHTML( $value ) {
1591 return Xml
::submitButton(
1594 'class' => 'mw-htmlform-submit',
1595 'name' => $this->mName
,
1601 protected function needsLabel() {
1606 * Button cannot be invalid
1608 public function validate( $value, $alldata ){
1613 class HTMLEditTools
extends HTMLFormField
{
1614 public function getInputHTML( $value ) {
1618 public function getTableRow( $value ) {
1619 if ( empty( $this->mParams
['message'] ) ) {
1620 $msg = wfMessage( 'edittools' );
1622 $msg = wfMessage( $this->mParams
['message'] );
1623 if ( $msg->isDisabled() ) {
1624 $msg = wfMessage( 'edittools' );
1627 $msg->inContentLanguage();
1630 return '<tr><td></td><td class="mw-input">'
1631 . '<div class="mw-editTools">'
1632 . $msg->parseAsBlock()
1633 . "</div></td></tr>\n";