4 * HTML form generation and submission handling.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
25 * Object handling generic submission, CSRF protection, layout and
26 * other logic for UI forms. in a reusable manner.
28 * In order to generate the form, the HTMLForm object takes an array
29 * structure detailing the form fields available. Each element of the
30 * array is a basic property-list, including the type of field, the
31 * label it is to be given in the form, callbacks for validation and
32 * 'filtering', and other pertinent information.
34 * Field types are implemented as subclasses of the generic HTMLFormField
35 * object, and typically implement at least getInputHTML, which generates
36 * the HTML for the input field to be placed in the table.
38 * You can find extensive documentation on the www.mediawiki.org wiki:
39 * - https://www.mediawiki.org/wiki/HTMLForm
40 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
42 * The constructor input is an associative array of $fieldname => $info,
43 * where $info is an Associative Array with any of the following:
45 * 'class' -- the subclass of HTMLFormField that will be used
46 * to create the object. *NOT* the CSS class!
47 * 'type' -- roughly translates into the <select> type attribute.
48 * if 'class' is not specified, this is used as a map
49 * through HTMLForm::$typeMappings to get the class name.
50 * 'default' -- default value when the form is displayed
51 * 'id' -- HTML id attribute
52 * 'cssclass' -- CSS class
53 * 'csshelpclass' -- CSS class used to style help text
54 * 'dir' -- Direction of the element.
55 * 'options' -- associative array mapping labels to values.
56 * Some field types support multi-level arrays.
57 * 'options-messages' -- associative array mapping message keys to values.
58 * Some field types support multi-level arrays.
59 * 'options-message' -- message key or object to be parsed to extract the list of
60 * options (like 'ipbreason-dropdown').
61 * 'label-message' -- message key or object for a message to use as the label.
62 * can be an array of msg key and then parameters to
64 * 'label' -- alternatively, a raw text message. Overridden by
66 * 'help' -- message text for a message to use as a help text.
67 * 'help-message' -- message key or object for a message to use as a help text.
68 * can be an array of msg key and then parameters to
70 * Overwrites 'help-messages' and 'help'.
71 * 'help-messages' -- array of message keys/objects. As above, each item can
72 * be an array of msg key and then parameters.
74 * 'required' -- passed through to the object, indicating that it
75 * is a required field.
76 * 'size' -- the length of text fields
77 * 'filter-callback' -- a function name to give you the chance to
78 * massage the inputted value before it's processed.
79 * @see HTMLFormField::filter()
80 * 'validation-callback' -- a function name to give you the chance
81 * to impose extra validation on the field input.
82 * @see HTMLFormField::validate()
83 * 'name' -- By default, the 'name' attribute of the input field
84 * is "wp{$fieldname}". If you want a different name
85 * (eg one without the "wp" prefix), specify it here and
86 * it will be used without modification.
87 * 'hide-if' -- expression given as an array stating when the field
88 * should be hidden. The first array value has to be the
89 * expression's logic operator. Supported expressions:
91 * [ 'NOT', array $expression ]
92 * To hide a field if a given expression is not true.
94 * [ '===', string $fieldName, string $value ]
95 * To hide a field if another field identified by
96 * $field has the value $value.
98 * [ '!==', string $fieldName, string $value ]
99 * Same as [ 'NOT', [ '===', $fieldName, $value ]
100 * 'OR', 'AND', 'NOR', 'NAND'
101 * [ 'XXX', array $expression1, ..., array $expressionN ]
102 * To hide a field if one or more (OR), all (AND),
103 * neither (NOR) or not all (NAND) given expressions
104 * are evaluated as true.
105 * The expressions will be given to a JavaScript frontend
106 * module which will continually update the field's
109 * Since 1.20, you can chain mutators to ease the form generation:
112 * $form = new HTMLForm( $someFields );
113 * $form->setMethod( 'get' )
114 * ->setWrapperLegendMsg( 'message-key' )
116 * ->displayForm( '' );
118 * Note that you will have prepareForm and displayForm at the end. Other
119 * methods call done after that would simply not be part of the form :(
121 * @todo Document 'section' / 'subsection' stuff
123 class HTMLForm
extends ContextSource
{
124 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
125 public static $typeMappings = [
126 'api' => 'HTMLApiField',
127 'text' => 'HTMLTextField',
128 'textwithbutton' => 'HTMLTextFieldWithButton',
129 'textarea' => 'HTMLTextAreaField',
130 'select' => 'HTMLSelectField',
131 'combobox' => 'HTMLComboboxField',
132 'radio' => 'HTMLRadioField',
133 'multiselect' => 'HTMLMultiSelectField',
134 'limitselect' => 'HTMLSelectLimitField',
135 'check' => 'HTMLCheckField',
136 'toggle' => 'HTMLCheckField',
137 'int' => 'HTMLIntField',
138 'float' => 'HTMLFloatField',
139 'info' => 'HTMLInfoField',
140 'selectorother' => 'HTMLSelectOrOtherField',
141 'selectandother' => 'HTMLSelectAndOtherField',
142 'namespaceselect' => 'HTMLSelectNamespace',
143 'namespaceselectwithbutton' => 'HTMLSelectNamespaceWithButton',
144 'tagfilter' => 'HTMLTagFilter',
145 'submit' => 'HTMLSubmitField',
146 'hidden' => 'HTMLHiddenField',
147 'edittools' => 'HTMLEditTools',
148 'checkmatrix' => 'HTMLCheckMatrix',
149 'cloner' => 'HTMLFormFieldCloner',
150 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
151 // HTMLTextField will output the correct type="" attribute automagically.
152 // There are about four zillion other HTML5 input types, like range, but
153 // we don't use those at the moment, so no point in adding all of them.
154 'email' => 'HTMLTextField',
155 'password' => 'HTMLTextField',
156 'url' => 'HTMLTextField',
157 'title' => 'HTMLTitleTextField',
158 'user' => 'HTMLUserTextField',
163 protected $mMessagePrefix;
165 /** @var HTMLFormField[] */
166 protected $mFlatFields;
168 protected $mFieldTree;
169 protected $mShowReset = false;
170 protected $mShowSubmit = true;
171 protected $mSubmitFlags = [ 'constructive', 'primary' ];
172 protected $mShowCancel = false;
173 protected $mCancelTarget;
175 protected $mSubmitCallback;
176 protected $mValidationErrorMessage;
178 protected $mPre = '';
179 protected $mHeader = '';
180 protected $mFooter = '';
181 protected $mSectionHeaders = [];
182 protected $mSectionFooters = [];
183 protected $mPost = '';
186 protected $mTableId = '';
188 protected $mSubmitID;
189 protected $mSubmitName;
190 protected $mSubmitText;
191 protected $mSubmitTooltip;
193 protected $mFormIdentifier;
195 protected $mMethod = 'post';
196 protected $mWasSubmitted = false;
199 * Form action URL. false means we will use the URL to set Title
203 protected $mAction = false;
206 * Form attribute autocomplete. false does not set the attribute
210 protected $mAutocomplete = false;
212 protected $mUseMultipart = false;
213 protected $mHiddenFields = [];
214 protected $mButtons = [];
216 protected $mWrapperLegend = false;
219 * Salt for the edit token.
222 protected $mTokenSalt = '';
225 * If true, sections that contain both fields and subsections will
226 * render their subsections before their fields.
228 * Subclasses may set this to false to render subsections after fields
231 protected $mSubSectionBeforeFields = true;
234 * Format in which to display form. For viable options,
235 * @see $availableDisplayFormats
238 protected $displayFormat = 'table';
241 * Available formats in which to display the form
244 protected $availableDisplayFormats = [
252 * Available formats in which to display the form
255 protected $availableSubclassDisplayFormats = [
261 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
263 * @param string $displayFormat
264 * @param mixed $arguments... Additional arguments to pass to the constructor.
267 public static function factory( $displayFormat/*, $arguments...*/ ) {
268 $arguments = func_get_args();
269 array_shift( $arguments );
271 switch ( $displayFormat ) {
273 $reflector = new ReflectionClass( 'VFormHTMLForm' );
274 return $reflector->newInstanceArgs( $arguments );
276 $reflector = new ReflectionClass( 'OOUIHTMLForm' );
277 return $reflector->newInstanceArgs( $arguments );
279 $reflector = new ReflectionClass( 'HTMLForm' );
280 $form = $reflector->newInstanceArgs( $arguments );
281 $form->setDisplayFormat( $displayFormat );
287 * Build a new HTMLForm from an array of field attributes
289 * @param array $descriptor Array of Field constructs, as described above
290 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
291 * Obviates the need to call $form->setTitle()
292 * @param string $messagePrefix A prefix to go in front of default messages
294 public function __construct( $descriptor, /*IContextSource*/ $context = null,
297 if ( $context instanceof IContextSource
) {
298 $this->setContext( $context );
299 $this->mTitle
= false; // We don't need them to set a title
300 $this->mMessagePrefix
= $messagePrefix;
301 } elseif ( $context === null && $messagePrefix !== '' ) {
302 $this->mMessagePrefix
= $messagePrefix;
303 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
305 // it's actually $messagePrefix
306 $this->mMessagePrefix
= $context;
309 // Evil hack for mobile :(
311 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
312 && $this->displayFormat
=== 'table'
314 $this->displayFormat
= 'div';
317 // Expand out into a tree.
318 $loadedDescriptor = [];
319 $this->mFlatFields
= [];
321 foreach ( $descriptor as $fieldname => $info ) {
322 $section = isset( $info['section'] )
326 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
327 $this->mUseMultipart
= true;
330 $field = static::loadInputFromParameters( $fieldname, $info, $this );
332 $setSection =& $loadedDescriptor;
334 $sectionParts = explode( '/', $section );
336 while ( count( $sectionParts ) ) {
337 $newName = array_shift( $sectionParts );
339 if ( !isset( $setSection[$newName] ) ) {
340 $setSection[$newName] = [];
343 $setSection =& $setSection[$newName];
347 $setSection[$fieldname] = $field;
348 $this->mFlatFields
[$fieldname] = $field;
351 $this->mFieldTree
= $loadedDescriptor;
355 * Set format in which to display the form
357 * @param string $format The name of the format to use, must be one of
358 * $this->availableDisplayFormats
360 * @throws MWException
362 * @return HTMLForm $this for chaining calls (since 1.20)
364 public function setDisplayFormat( $format ) {
366 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
367 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
369 throw new MWException( 'Cannot change display format after creation, ' .
370 'use HTMLForm::factory() instead' );
373 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
374 throw new MWException( 'Display format must be one of ' .
375 print_r( $this->availableDisplayFormats
, true ) );
378 // Evil hack for mobile :(
379 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
383 $this->displayFormat
= $format;
389 * Getter for displayFormat
393 public function getDisplayFormat() {
394 return $this->displayFormat
;
398 * Test if displayFormat is 'vform'
400 * @deprecated since 1.25
403 public function isVForm() {
404 wfDeprecated( __METHOD__
, '1.25' );
409 * Get the HTMLFormField subclass for this descriptor.
411 * The descriptor can be passed either 'class' which is the name of
412 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
413 * This makes sure the 'class' is always set, and also is returned by
414 * this function for ease.
418 * @param string $fieldname Name of the field
419 * @param array $descriptor Input Descriptor, as described above
421 * @throws MWException
422 * @return string Name of a HTMLFormField subclass
424 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
425 if ( isset( $descriptor['class'] ) ) {
426 $class = $descriptor['class'];
427 } elseif ( isset( $descriptor['type'] ) ) {
428 $class = static::$typeMappings[$descriptor['type']];
429 $descriptor['class'] = $class;
435 throw new MWException( "Descriptor with no class for $fieldname: "
436 . print_r( $descriptor, true ) );
443 * Initialise a new Object for the field
445 * @param string $fieldname Name of the field
446 * @param array $descriptor Input Descriptor, as described above
447 * @param HTMLForm|null $parent Parent instance of HTMLForm
449 * @throws MWException
450 * @return HTMLFormField Instance of a subclass of HTMLFormField
452 public static function loadInputFromParameters( $fieldname, $descriptor,
453 HTMLForm
$parent = null
455 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
457 $descriptor['fieldname'] = $fieldname;
459 $descriptor['parent'] = $parent;
462 # @todo This will throw a fatal error whenever someone try to use
463 # 'class' to feed a CSS class instead of 'cssclass'. Would be
464 # great to avoid the fatal error and show a nice error.
465 return new $class( $descriptor );
469 * Prepare form for submission.
471 * @attention When doing method chaining, that should be the very last
472 * method call before displayForm().
474 * @throws MWException
475 * @return HTMLForm $this for chaining calls (since 1.20)
477 public function prepareForm() {
478 # Check if we have the info we need
479 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
480 throw new MWException( 'You must call setTitle() on an HTMLForm' );
483 # Load data from the request.
485 $this->mFormIdentifier
=== null ||
486 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
490 $this->mFieldData
= [];
497 * Try submitting, with edit token check first
498 * @return Status|bool
500 public function tryAuthorizedSubmit() {
504 if ( $this->mFormIdentifier
=== null ) {
507 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
511 if ( $this->getMethod() !== 'post' ) {
512 $tokenOkay = true; // no session check needed
513 } elseif ( $this->getRequest()->wasPosted() ) {
514 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
515 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
516 // Session tokens for logged-out users have no security value.
517 // However, if the user gave one, check it in order to give a nice
518 // "session expired" error instead of "permission denied" or such.
519 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
525 if ( $tokenOkay && $identOkay ) {
526 $this->mWasSubmitted
= true;
527 $result = $this->trySubmit();
534 * The here's-one-I-made-earlier option: do the submission if
535 * posted, or display the form with or without funky validation
537 * @return bool|Status Whether submission was successful.
539 public function show() {
540 $this->prepareForm();
542 $result = $this->tryAuthorizedSubmit();
543 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
547 $this->displayForm( $result );
553 * Same as self::show with the difference, that the form will be
554 * added to the output, no matter, if the validation was good or not.
555 * @return bool|Status Whether submission was successful.
557 public function showAlways() {
558 $this->prepareForm();
560 $result = $this->tryAuthorizedSubmit();
562 $this->displayForm( $result );
568 * Validate all the fields, and call the submission callback
569 * function if everything is kosher.
570 * @throws MWException
571 * @return bool|string|array|Status
572 * - Bool true or a good Status object indicates success,
573 * - Bool false indicates no submission was attempted,
574 * - Anything else indicates failure. The value may be a fatal Status
575 * object, an HTML string, or an array of arrays (message keys and
576 * params) or strings (message keys)
578 public function trySubmit() {
581 $hoistedErrors[] = isset( $this->mValidationErrorMessage
)
582 ?
$this->mValidationErrorMessage
583 : [ 'htmlform-invalid-input' ];
585 $this->mWasSubmitted
= true;
587 # Check for cancelled submission
588 foreach ( $this->mFlatFields
as $fieldname => $field ) {
589 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
592 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
593 $this->mWasSubmitted
= false;
598 # Check for validation
599 foreach ( $this->mFlatFields
as $fieldname => $field ) {
600 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
603 if ( $field->isHidden( $this->mFieldData
) ) {
606 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
607 if ( $res !== true ) {
609 if ( $res !== false && !$field->canDisplayErrors() ) {
610 $hoistedErrors[] = [ 'rawmessage', $res ];
616 if ( count( $hoistedErrors ) === 1 ) {
617 $hoistedErrors = $hoistedErrors[0];
619 return $hoistedErrors;
622 $callback = $this->mSubmitCallback
;
623 if ( !is_callable( $callback ) ) {
624 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
625 'setSubmitCallback() to set one.' );
628 $data = $this->filterDataForSubmit( $this->mFieldData
);
630 $res = call_user_func( $callback, $data, $this );
631 if ( $res === false ) {
632 $this->mWasSubmitted
= false;
639 * Test whether the form was considered to have been submitted or not, i.e.
640 * whether the last call to tryAuthorizedSubmit or trySubmit returned
643 * This will return false until HTMLForm::tryAuthorizedSubmit or
644 * HTMLForm::trySubmit is called.
649 public function wasSubmitted() {
650 return $this->mWasSubmitted
;
654 * Set a callback to a function to do something with the form
655 * once it's been successfully validated.
657 * @param callable $cb The function will be passed the output from
658 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
659 * return as documented for HTMLForm::trySubmit
661 * @return HTMLForm $this for chaining calls (since 1.20)
663 public function setSubmitCallback( $cb ) {
664 $this->mSubmitCallback
= $cb;
670 * Set a message to display on a validation error.
672 * @param string|array $msg String or Array of valid inputs to wfMessage()
673 * (so each entry can be either a String or Array)
675 * @return HTMLForm $this for chaining calls (since 1.20)
677 public function setValidationErrorMessage( $msg ) {
678 $this->mValidationErrorMessage
= $msg;
684 * Set the introductory message, overwriting any existing message.
686 * @param string $msg Complete text of message to display
688 * @return HTMLForm $this for chaining calls (since 1.20)
690 public function setIntro( $msg ) {
691 $this->setPreText( $msg );
697 * Set the introductory message HTML, overwriting any existing message.
700 * @param string $msg Complete HTML of message to display
702 * @return HTMLForm $this for chaining calls (since 1.20)
704 public function setPreText( $msg ) {
711 * Add HTML to introductory message.
713 * @param string $msg Complete HTML of message to display
715 * @return HTMLForm $this for chaining calls (since 1.20)
717 public function addPreText( $msg ) {
724 * Add HTML to the header, inside the form.
726 * @param string $msg Additional HTML to display in header
727 * @param string|null $section The section to add the header to
729 * @return HTMLForm $this for chaining calls (since 1.20)
731 public function addHeaderText( $msg, $section = null ) {
732 if ( $section === null ) {
733 $this->mHeader
.= $msg;
735 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
736 $this->mSectionHeaders
[$section] = '';
738 $this->mSectionHeaders
[$section] .= $msg;
745 * Set header text, inside the form.
748 * @param string $msg Complete HTML of header to display
749 * @param string|null $section The section to add the header to
751 * @return HTMLForm $this for chaining calls (since 1.20)
753 public function setHeaderText( $msg, $section = null ) {
754 if ( $section === null ) {
755 $this->mHeader
= $msg;
757 $this->mSectionHeaders
[$section] = $msg;
766 * @param string|null $section The section to get the header text for
768 * @return string HTML
770 public function getHeaderText( $section = null ) {
771 if ( $section === null ) {
772 return $this->mHeader
;
774 return isset( $this->mSectionHeaders
[$section] ) ?
$this->mSectionHeaders
[$section] : '';
779 * Add footer text, inside the form.
781 * @param string $msg Complete text of message to display
782 * @param string|null $section The section to add the footer text to
784 * @return HTMLForm $this for chaining calls (since 1.20)
786 public function addFooterText( $msg, $section = null ) {
787 if ( $section === null ) {
788 $this->mFooter
.= $msg;
790 if ( !isset( $this->mSectionFooters
[$section] ) ) {
791 $this->mSectionFooters
[$section] = '';
793 $this->mSectionFooters
[$section] .= $msg;
800 * Set footer text, inside the form.
803 * @param string $msg Complete text of message to display
804 * @param string|null $section The section to add the footer text to
806 * @return HTMLForm $this for chaining calls (since 1.20)
808 public function setFooterText( $msg, $section = null ) {
809 if ( $section === null ) {
810 $this->mFooter
= $msg;
812 $this->mSectionFooters
[$section] = $msg;
821 * @param string|null $section The section to get the footer text for
825 public function getFooterText( $section = null ) {
826 if ( $section === null ) {
827 return $this->mFooter
;
829 return isset( $this->mSectionFooters
[$section] ) ?
$this->mSectionFooters
[$section] : '';
834 * Add text to the end of the display.
836 * @param string $msg Complete text of message to display
838 * @return HTMLForm $this for chaining calls (since 1.20)
840 public function addPostText( $msg ) {
841 $this->mPost
.= $msg;
847 * Set text at the end of the display.
849 * @param string $msg Complete text of message to display
851 * @return HTMLForm $this for chaining calls (since 1.20)
853 public function setPostText( $msg ) {
860 * Add a hidden field to the output
862 * @param string $name Field name. This will be used exactly as entered
863 * @param string $value Field value
864 * @param array $attribs
866 * @return HTMLForm $this for chaining calls (since 1.20)
868 public function addHiddenField( $name, $value, array $attribs = [] ) {
869 $attribs +
= [ 'name' => $name ];
870 $this->mHiddenFields
[] = [ $value, $attribs ];
876 * Add an array of hidden fields to the output
880 * @param array $fields Associative array of fields to add;
881 * mapping names to their values
883 * @return HTMLForm $this for chaining calls
885 public function addHiddenFields( array $fields ) {
886 foreach ( $fields as $name => $value ) {
887 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
894 * Add a button to the form
896 * @since 1.27 takes an array as shown. Earlier versions accepted
897 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
899 * @note Custom labels ('label', 'label-message', 'label-raw') are not
900 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
901 * they will be served buttons using 'value' as the button label.
902 * @param array $data Data to define the button:
903 * - name: (string) Button name.
904 * - value: (string) Button value.
905 * - label-message: (string, optional) Button label message key to use
906 * instead of 'value'. Overrides 'label' and 'label-raw'.
907 * - label: (string, optional) Button label text to use instead of
908 * 'value'. Overrides 'label-raw'.
909 * - label-raw: (string, optional) Button label HTML to use instead of
911 * - id: (string, optional) DOM id for the button.
912 * - attribs: (array, optional) Additional HTML attributes.
913 * - flags: (string|string[], optional) OOUI flags.
914 * - framed: (boolean=true, optional) OOUI framed attribute.
915 * @return HTMLForm $this for chaining calls (since 1.20)
917 public function addButton( $data ) {
918 if ( !is_array( $data ) ) {
919 $args = func_get_args();
920 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
921 throw new InvalidArgumentException(
922 'Incorrect number of arguments for deprecated calling style'
928 'id' => isset( $args[2] ) ?
$args[2] : null,
929 'attribs' => isset( $args[3] ) ?
$args[3] : null,
932 if ( !isset( $data['name'] ) ) {
933 throw new InvalidArgumentException( 'A name is required' );
935 if ( !isset( $data['value'] ) ) {
936 throw new InvalidArgumentException( 'A value is required' );
939 $this->mButtons
[] = $data +
[
950 * Set the salt for the edit token.
952 * Only useful when the method is "post".
955 * @param string|array $salt Salt to use
956 * @return HTMLForm $this For chaining calls
958 public function setTokenSalt( $salt ) {
959 $this->mTokenSalt
= $salt;
965 * Display the form (sending to the context's OutputPage object), with an
966 * appropriate error message or stack of messages, and any validation errors, etc.
968 * @attention You should call prepareForm() before calling this function.
969 * Moreover, when doing method chaining this should be the very last method
970 * call just after prepareForm().
972 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
974 * @return void Nothing, should be last call
976 public function displayForm( $submitResult ) {
977 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
981 * Returns the raw HTML generated by the form
983 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
985 * @return string HTML
987 public function getHTML( $submitResult ) {
988 # For good measure (it is the default)
989 $this->getOutput()->preventClickjacking();
990 $this->getOutput()->addModules( 'mediawiki.htmlform' );
991 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
994 . $this->getErrors( $submitResult )
995 . $this->getHeaderText()
997 . $this->getHiddenFields()
998 . $this->getButtons()
999 . $this->getFooterText();
1001 $html = $this->wrapForm( $html );
1003 return '' . $this->mPre
. $html . $this->mPost
;
1007 * Get HTML attributes for the `<form>` tag.
1010 protected function getFormAttributes() {
1011 # Use multipart/form-data
1012 $encType = $this->mUseMultipart
1013 ?
'multipart/form-data'
1014 : 'application/x-www-form-urlencoded';
1017 'action' => $this->getAction(),
1018 'method' => $this->getMethod(),
1019 'enctype' => $encType,
1022 $attribs['id'] = $this->mId
;
1024 if ( $this->mAutocomplete
) {
1025 $attribs['autocomplete'] = $this->mAutocomplete
;
1027 if ( $this->mName
) {
1028 $attribs['name'] = $this->mName
;
1034 * Wrap the form innards in an actual "<form>" element
1036 * @param string $html HTML contents to wrap.
1038 * @return string Wrapped HTML.
1040 public function wrapForm( $html ) {
1041 # Include a <fieldset> wrapper for style, if requested.
1042 if ( $this->mWrapperLegend
!== false ) {
1043 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1044 $html = Xml
::fieldset( $legend, $html );
1047 return Html
::rawElement(
1049 $this->getFormAttributes() +
[ 'class' => 'visualClear' ],
1055 * Get the hidden fields that should go inside the form.
1056 * @return string HTML.
1058 public function getHiddenFields() {
1060 if ( $this->mFormIdentifier
!== null ) {
1061 $html .= Html
::hidden(
1063 $this->mFormIdentifier
1066 if ( $this->getMethod() === 'post' ) {
1067 $html .= Html
::hidden(
1069 $this->getUser()->getEditToken( $this->mTokenSalt
),
1070 [ 'id' => 'wpEditToken' ]
1072 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1075 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1076 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1077 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1080 foreach ( $this->mHiddenFields
as $data ) {
1081 list( $value, $attribs ) = $data;
1082 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1089 * Get the submit and (potentially) reset buttons.
1090 * @return string HTML.
1092 public function getButtons() {
1094 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1096 if ( $this->mShowSubmit
) {
1099 if ( isset( $this->mSubmitID
) ) {
1100 $attribs['id'] = $this->mSubmitID
;
1103 if ( isset( $this->mSubmitName
) ) {
1104 $attribs['name'] = $this->mSubmitName
;
1107 if ( isset( $this->mSubmitTooltip
) ) {
1108 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1111 $attribs['class'] = [ 'mw-htmlform-submit' ];
1113 if ( $useMediaWikiUIEverywhere ) {
1114 foreach ( $this->mSubmitFlags
as $flag ) {
1115 $attribs['class'][] = 'mw-ui-' . $flag;
1117 $attribs['class'][] = 'mw-ui-button';
1120 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1123 if ( $this->mShowReset
) {
1124 $buttons .= Html
::element(
1128 'value' => $this->msg( 'htmlform-reset' )->text(),
1129 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1134 if ( $this->mShowCancel
) {
1135 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1136 if ( $target instanceof Title
) {
1137 $target = $target->getLocalURL();
1139 $buttons .= Html
::element(
1142 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1145 $this->msg( 'cancel' )->text()
1149 // IE<8 has bugs with <button>, so we'll need to avoid them.
1150 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1152 foreach ( $this->mButtons
as $button ) {
1155 'name' => $button['name'],
1156 'value' => $button['value']
1159 if ( isset( $button['label-message'] ) ) {
1160 $label = $this->getMessage( $button['label-message'] )->parse();
1161 } elseif ( isset( $button['label'] ) ) {
1162 $label = htmlspecialchars( $button['label'] );
1163 } elseif ( isset( $button['label-raw'] ) ) {
1164 $label = $button['label-raw'];
1166 $label = htmlspecialchars( $button['value'] );
1169 if ( $button['attribs'] ) {
1170 $attrs +
= $button['attribs'];
1173 if ( isset( $button['id'] ) ) {
1174 $attrs['id'] = $button['id'];
1177 if ( $useMediaWikiUIEverywhere ) {
1178 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1179 $attrs['class'][] = 'mw-ui-button';
1183 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1185 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1193 return Html
::rawElement( 'span',
1194 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1198 * Get the whole body of the form.
1201 public function getBody() {
1202 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1206 * Format and display an error message stack.
1208 * @param string|array|Status $errors
1212 public function getErrors( $errors ) {
1213 if ( $errors instanceof Status
) {
1214 if ( $errors->isOK() ) {
1217 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1219 } elseif ( is_array( $errors ) ) {
1220 $errorstr = $this->formatErrors( $errors );
1222 $errorstr = $errors;
1226 ? Html
::rawElement( 'div', [ 'class' => 'error' ], $errorstr )
1231 * Format a stack of error messages into a single HTML string
1233 * @param array $errors Array of message keys/values
1235 * @return string HTML, a "<ul>" list of errors
1237 public function formatErrors( $errors ) {
1240 foreach ( $errors as $error ) {
1241 $errorstr .= Html
::rawElement(
1244 $this->getMessage( $error )->parse()
1248 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1254 * Set the text for the submit button
1256 * @param string $t Plaintext
1258 * @return HTMLForm $this for chaining calls (since 1.20)
1260 public function setSubmitText( $t ) {
1261 $this->mSubmitText
= $t;
1267 * Identify that the submit button in the form has a destructive action
1270 * @return HTMLForm $this for chaining calls (since 1.28)
1272 public function setSubmitDestructive() {
1273 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1279 * Identify that the submit button in the form has a progressive action
1282 * @return HTMLForm $this for chaining calls (since 1.28)
1284 public function setSubmitProgressive() {
1285 $this->mSubmitFlags
= [ 'progressive', 'primary' ];
1291 * Set the text for the submit button to a message
1294 * @param string|Message $msg Message key or Message object
1296 * @return HTMLForm $this for chaining calls (since 1.20)
1298 public function setSubmitTextMsg( $msg ) {
1299 if ( !$msg instanceof Message
) {
1300 $msg = $this->msg( $msg );
1302 $this->setSubmitText( $msg->text() );
1308 * Get the text for the submit button, either customised or a default.
1311 public function getSubmitText() {
1312 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1316 * @param string $name Submit button name
1318 * @return HTMLForm $this for chaining calls (since 1.20)
1320 public function setSubmitName( $name ) {
1321 $this->mSubmitName
= $name;
1327 * @param string $name Tooltip for the submit button
1329 * @return HTMLForm $this for chaining calls (since 1.20)
1331 public function setSubmitTooltip( $name ) {
1332 $this->mSubmitTooltip
= $name;
1338 * Set the id for the submit button.
1342 * @todo FIXME: Integrity of $t is *not* validated
1343 * @return HTMLForm $this for chaining calls (since 1.20)
1345 public function setSubmitID( $t ) {
1346 $this->mSubmitID
= $t;
1352 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1353 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1356 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1357 * was submitted, and not attempt to validate the other ones.
1358 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1359 * HTMLForm to distinguish between the initial page view and a form submission with all
1360 * checkboxes or select options unchecked.
1363 * @param string $ident
1366 public function setFormIdentifier( $ident ) {
1367 $this->mFormIdentifier
= $ident;
1373 * Stop a default submit button being shown for this form. This implies that an
1374 * alternate submit method must be provided manually.
1378 * @param bool $suppressSubmit Set to false to re-enable the button again
1380 * @return HTMLForm $this for chaining calls
1382 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1383 $this->mShowSubmit
= !$suppressSubmit;
1389 * Show a cancel button (or prevent it). The button is not shown by default.
1391 * @return HTMLForm $this for chaining calls
1394 public function showCancel( $show = true ) {
1395 $this->mShowCancel
= $show;
1400 * Sets the target where the user is redirected to after clicking cancel.
1401 * @param Title|string $target Target as a Title object or an URL
1402 * @return HTMLForm $this for chaining calls
1405 public function setCancelTarget( $target ) {
1406 $this->mCancelTarget
= $target;
1411 * Set the id of the \<table\> or outermost \<div\> element.
1415 * @param string $id New value of the id attribute, or "" to remove
1417 * @return HTMLForm $this for chaining calls
1419 public function setTableId( $id ) {
1420 $this->mTableId
= $id;
1426 * @param string $id DOM id for the form
1428 * @return HTMLForm $this for chaining calls (since 1.20)
1430 public function setId( $id ) {
1437 * @param string $name 'name' attribute for the form
1438 * @return HTMLForm $this for chaining calls
1440 public function setName( $name ) {
1441 $this->mName
= $name;
1447 * Prompt the whole form to be wrapped in a "<fieldset>", with
1448 * this text as its "<legend>" element.
1450 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1451 * If true, a wrapper will be displayed, but no legend.
1452 * If a string, a wrapper will be displayed with that string as a legend.
1453 * The string will be escaped before being output (this doesn't support HTML).
1455 * @return HTMLForm $this for chaining calls (since 1.20)
1457 public function setWrapperLegend( $legend ) {
1458 $this->mWrapperLegend
= $legend;
1464 * Prompt the whole form to be wrapped in a "<fieldset>", with
1465 * this message as its "<legend>" element.
1468 * @param string|Message $msg Message key or Message object
1470 * @return HTMLForm $this for chaining calls (since 1.20)
1472 public function setWrapperLegendMsg( $msg ) {
1473 if ( !$msg instanceof Message
) {
1474 $msg = $this->msg( $msg );
1476 $this->setWrapperLegend( $msg->text() );
1482 * Set the prefix for various default messages
1483 * @todo Currently only used for the "<fieldset>" legend on forms
1484 * with multiple sections; should be used elsewhere?
1488 * @return HTMLForm $this for chaining calls (since 1.20)
1490 public function setMessagePrefix( $p ) {
1491 $this->mMessagePrefix
= $p;
1497 * Set the title for form submission
1499 * @param Title $t Title of page the form is on/should be posted to
1501 * @return HTMLForm $this for chaining calls (since 1.20)
1503 public function setTitle( $t ) {
1513 public function getTitle() {
1514 return $this->mTitle
=== false
1515 ?
$this->getContext()->getTitle()
1520 * Set the method used to submit the form
1522 * @param string $method
1524 * @return HTMLForm $this for chaining calls (since 1.20)
1526 public function setMethod( $method = 'post' ) {
1527 $this->mMethod
= strtolower( $method );
1533 * @return string Always lowercase
1535 public function getMethod() {
1536 return $this->mMethod
;
1540 * Wraps the given $section into an user-visible fieldset.
1542 * @param string $legend Legend text for the fieldset
1543 * @param string $section The section content in plain Html
1544 * @param array $attributes Additional attributes for the fieldset
1545 * @return string The fieldset's Html
1547 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1548 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1554 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1556 * @param string $sectionName ID attribute of the "<table>" tag for this
1557 * section, ignored if empty.
1558 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1559 * each subsection, ignored if empty.
1560 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1561 * @throws LogicException When called on uninitialized field data, e.g. When
1562 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1567 public function displaySection( $fields,
1569 $fieldsetIDPrefix = '',
1570 &$hasUserVisibleFields = false
1572 if ( $this->mFieldData
=== null ) {
1573 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1574 . 'You probably called displayForm() without calling prepareForm() first.' );
1577 $displayFormat = $this->getDisplayFormat();
1580 $subsectionHtml = '';
1583 // Conveniently, PHP method names are case-insensitive.
1584 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1585 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1587 foreach ( $fields as $key => $value ) {
1588 if ( $value instanceof HTMLFormField
) {
1589 $v = array_key_exists( $key, $this->mFieldData
)
1590 ?
$this->mFieldData
[$key]
1591 : $value->getDefault();
1593 $retval = $value->$getFieldHtmlMethod( $v );
1595 // check, if the form field should be added to
1597 if ( $value->hasVisibleOutput() ) {
1600 $labelValue = trim( $value->getLabel() );
1601 if ( $labelValue !== ' ' && $labelValue !== '' ) {
1605 $hasUserVisibleFields = true;
1607 } elseif ( is_array( $value ) ) {
1608 $subsectionHasVisibleFields = false;
1610 $this->displaySection( $value,
1612 "$fieldsetIDPrefix$key-",
1613 $subsectionHasVisibleFields );
1616 if ( $subsectionHasVisibleFields === true ) {
1617 // Display the section with various niceties.
1618 $hasUserVisibleFields = true;
1620 $legend = $this->getLegend( $key );
1622 $section = $this->getHeaderText( $key ) .
1624 $this->getFooterText( $key );
1627 if ( $fieldsetIDPrefix ) {
1628 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1630 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1632 // Just return the inputs, nothing fancy.
1633 $subsectionHtml .= $section;
1638 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1640 if ( $subsectionHtml ) {
1641 if ( $this->mSubSectionBeforeFields
) {
1642 return $subsectionHtml . "\n" . $html;
1644 return $html . "\n" . $subsectionHtml;
1652 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1653 * @param array $fieldsHtml
1654 * @param string $sectionName
1655 * @param bool $anyFieldHasLabel
1656 * @return string HTML
1658 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1659 $displayFormat = $this->getDisplayFormat();
1660 $html = implode( '', $fieldsHtml );
1662 if ( $displayFormat === 'raw' ) {
1668 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1669 $classes[] = 'mw-htmlform-nolabel';
1673 'class' => implode( ' ', $classes ),
1676 if ( $sectionName ) {
1677 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1680 if ( $displayFormat === 'table' ) {
1681 return Html
::rawElement( 'table',
1683 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1684 } elseif ( $displayFormat === 'inline' ) {
1685 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1687 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1692 * Construct the form fields from the Descriptor array
1694 public function loadData() {
1697 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1698 $request = $this->getRequest();
1699 if ( $field->skipLoadData( $request ) ) {
1701 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1702 $fieldData[$fieldname] = $field->getDefault();
1704 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1709 foreach ( $fieldData as $name => &$value ) {
1710 $field = $this->mFlatFields
[$name];
1711 $value = $field->filter( $value, $this->mFlatFields
);
1714 $this->mFieldData
= $fieldData;
1718 * Stop a reset button being shown for this form
1720 * @param bool $suppressReset Set to false to re-enable the button again
1722 * @return HTMLForm $this for chaining calls (since 1.20)
1724 public function suppressReset( $suppressReset = true ) {
1725 $this->mShowReset
= !$suppressReset;
1731 * Overload this if you want to apply special filtration routines
1732 * to the form as a whole, after it's submitted but before it's
1735 * @param array $data
1739 public function filterDataForSubmit( $data ) {
1744 * Get a string to go in the "<legend>" of a section fieldset.
1745 * Override this if you want something more complicated.
1747 * @param string $key
1751 public function getLegend( $key ) {
1752 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1756 * Set the value for the action attribute of the form.
1757 * When set to false (which is the default state), the set title is used.
1761 * @param string|bool $action
1763 * @return HTMLForm $this for chaining calls (since 1.20)
1765 public function setAction( $action ) {
1766 $this->mAction
= $action;
1772 * Get the value for the action attribute of the form.
1778 public function getAction() {
1779 // If an action is alredy provided, return it
1780 if ( $this->mAction
!== false ) {
1781 return $this->mAction
;
1784 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1785 // Check whether we are in GET mode and the ArticlePath contains a "?"
1786 // meaning that getLocalURL() would return something like "index.php?title=...".
1787 // As browser remove the query string before submitting GET forms,
1788 // it means that the title would be lost. In such case use wfScript() instead
1789 // and put title in an hidden field (see getHiddenFields()).
1790 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1794 return $this->getTitle()->getLocalURL();
1798 * Set the value for the autocomplete attribute of the form.
1799 * When set to false (which is the default state), the attribute get not set.
1803 * @param string|bool $autocomplete
1805 * @return HTMLForm $this for chaining calls
1807 public function setAutocomplete( $autocomplete ) {
1808 $this->mAutocomplete
= $autocomplete;
1814 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1815 * name + parameters array) into a Message.
1816 * @param mixed $value
1819 protected function getMessage( $value ) {
1820 return Message
::newFromSpecifier( $value )->setContext( $this );