Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
34.84% covered (danger)
34.84%
185 / 531
25.93% covered (danger)
25.93%
21 / 81
CRAP
0.00% covered (danger)
0.00%
0 / 1
HTMLForm
34.91% covered (danger)
34.91%
185 / 530
25.93% covered (danger)
25.93%
21 / 81
14693.41
0.00% covered (danger)
0.00%
0 / 1
 factory
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 addFields
26.67% covered (danger)
26.67%
4 / 15
0.00% covered (danger)
0.00%
0 / 1
20.20
 hasField
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getField
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 setDisplayFormat
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 getDisplayFormat
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getClassFromDescriptor
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 loadInputFromParameters
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 prepareForm
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
5.12
 tryAuthorizedSubmit
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
8.09
 show
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 showAlways
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 trySubmit
35.56% covered (danger)
35.56%
16 / 45
0.00% covered (danger)
0.00%
0 / 1
151.54
 wasSubmitted
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setSubmitCallback
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setValidationErrorMessage
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setPreHtml
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 addPreHtml
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getPreHtml
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addHeaderHtml
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 setHeaderHtml
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getHeaderHtml
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 addFooterHtml
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 setFooterHtml
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getFooterHtml
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 addPostHtml
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setPostHtml
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getPostHtml
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setSections
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 addHiddenField
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 addHiddenFields
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 addButton
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
42
 setTokenSalt
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 displayForm
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getHiddenTitle
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 getHTML
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
2
 setCollapsibleOptions
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getFormAttributes
77.78% covered (warning)
77.78%
14 / 18
0.00% covered (danger)
0.00%
0 / 1
6.40
 wrapForm
50.00% covered (danger)
50.00%
6 / 12
0.00% covered (danger)
0.00%
0 / 1
6.00
 getHiddenFields
68.75% covered (warning)
68.75%
11 / 16
0.00% covered (danger)
0.00%
0 / 1
4.49
 getButtons
30.95% covered (danger)
30.95%
13 / 42
0.00% covered (danger)
0.00%
0 / 1
68.63
 getBody
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getErrorsOrWarnings
78.26% covered (warning)
78.26%
18 / 23
0.00% covered (danger)
0.00%
0 / 1
12.24
 formatErrors
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 setSubmitText
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setSubmitDestructive
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setSubmitTextMsg
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getSubmitText
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 setSubmitName
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setSubmitTooltip
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setSubmitID
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setFormIdentifier
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 suppressDefaultSubmit
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 showCancel
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setCancelTarget
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getCancelTargetURL
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 setTableId
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setId
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setName
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setWrapperLegend
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setWrapperAttributes
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setWrapperLegendMsg
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 setMessagePrefix
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setTitle
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getTitle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 setMethod
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getMethod
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 wrapFieldSetSection
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 displaySection
21.74% covered (danger)
21.74%
10 / 46
0.00% covered (danger)
0.00%
0 / 1
107.95
 formatField
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
42
 formatSection
12.50% covered (danger)
12.50%
2 / 16
0.00% covered (danger)
0.00%
0 / 1
39.83
 loadData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 loadFieldData
37.50% covered (danger)
37.50%
6 / 16
0.00% covered (danger)
0.00%
0 / 1
18.96
 filterDataForSubmit
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getLegend
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 setAction
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getAction
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
4.59
 setAutocomplete
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getMessage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 needsJSForHtml5FormValidation
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
4.12
1<?php
2
3/**
4 * HTML form generation and submission handling.
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 */
23
24namespace MediaWiki\HTMLForm;
25
26use DomainException;
27use InvalidArgumentException;
28use LogicException;
29use MediaWiki\Context\ContextSource;
30use MediaWiki\Context\IContextSource;
31use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
32use MediaWiki\Html\Html;
33use MediaWiki\HTMLForm\Field\HTMLApiField;
34use MediaWiki\HTMLForm\Field\HTMLAutoCompleteSelectField;
35use MediaWiki\HTMLForm\Field\HTMLCheckField;
36use MediaWiki\HTMLForm\Field\HTMLCheckMatrix;
37use MediaWiki\HTMLForm\Field\HTMLComboboxField;
38use MediaWiki\HTMLForm\Field\HTMLDateTimeField;
39use MediaWiki\HTMLForm\Field\HTMLEditTools;
40use MediaWiki\HTMLForm\Field\HTMLExpiryField;
41use MediaWiki\HTMLForm\Field\HTMLFileField;
42use MediaWiki\HTMLForm\Field\HTMLFloatField;
43use MediaWiki\HTMLForm\Field\HTMLFormFieldCloner;
44use MediaWiki\HTMLForm\Field\HTMLHiddenField;
45use MediaWiki\HTMLForm\Field\HTMLInfoField;
46use MediaWiki\HTMLForm\Field\HTMLIntField;
47use MediaWiki\HTMLForm\Field\HTMLMultiSelectField;
48use MediaWiki\HTMLForm\Field\HTMLNamespacesMultiselectField;
49use MediaWiki\HTMLForm\Field\HTMLOrderedMultiselectField;
50use MediaWiki\HTMLForm\Field\HTMLRadioField;
51use MediaWiki\HTMLForm\Field\HTMLSelectAndOtherField;
52use MediaWiki\HTMLForm\Field\HTMLSelectField;
53use MediaWiki\HTMLForm\Field\HTMLSelectLanguageField;
54use MediaWiki\HTMLForm\Field\HTMLSelectLimitField;
55use MediaWiki\HTMLForm\Field\HTMLSelectNamespace;
56use MediaWiki\HTMLForm\Field\HTMLSelectNamespaceWithButton;
57use MediaWiki\HTMLForm\Field\HTMLSelectOrOtherField;
58use MediaWiki\HTMLForm\Field\HTMLSizeFilterField;
59use MediaWiki\HTMLForm\Field\HTMLSubmitField;
60use MediaWiki\HTMLForm\Field\HTMLTagFilter;
61use MediaWiki\HTMLForm\Field\HTMLTagMultiselectField;
62use MediaWiki\HTMLForm\Field\HTMLTextAreaField;
63use MediaWiki\HTMLForm\Field\HTMLTextField;
64use MediaWiki\HTMLForm\Field\HTMLTextFieldWithButton;
65use MediaWiki\HTMLForm\Field\HTMLTimezoneField;
66use MediaWiki\HTMLForm\Field\HTMLTitlesMultiselectField;
67use MediaWiki\HTMLForm\Field\HTMLTitleTextField;
68use MediaWiki\HTMLForm\Field\HTMLUsersMultiselectField;
69use MediaWiki\HTMLForm\Field\HTMLUserTextField;
70use MediaWiki\Linker\Linker;
71use MediaWiki\Linker\LinkTarget;
72use MediaWiki\MainConfigNames;
73use MediaWiki\Message\Message;
74use MediaWiki\Page\PageReference;
75use MediaWiki\Parser\Sanitizer;
76use MediaWiki\Session\CsrfTokenSet;
77use MediaWiki\Status\Status;
78use MediaWiki\Title\Title;
79use MediaWiki\Title\TitleValue;
80use StatusValue;
81use Stringable;
82use Wikimedia\Message\MessageParam;
83use Wikimedia\Message\MessageSpecifier;
84
85/**
86 * Object handling generic submission, CSRF protection, layout and
87 * other logic for UI forms in a reusable manner.
88 *
89 * In order to generate the form, the HTMLForm object takes an array
90 * structure detailing the form fields available. Each element of the
91 * array is a basic property-list, including the type of field, the
92 * label it is to be given in the form, callbacks for validation and
93 * 'filtering', and other pertinent information.
94 *
95 * Field types are implemented as subclasses of the generic HTMLFormField
96 * object, and typically implement at least getInputHTML, which generates
97 * the HTML for the input field to be placed in the table.
98 *
99 * You can find extensive documentation on the www.mediawiki.org wiki:
100 *  - https://www.mediawiki.org/wiki/HTMLForm
101 *  - https://www.mediawiki.org/wiki/HTMLForm/tutorial
102 *
103 * The constructor input is an associative array of $fieldname => $info,
104 * where $info is an Associative Array with any of the following:
105 *
106 *    'class'               -- the subclass of HTMLFormField that will be used
107 *                             to create the object.  *NOT* the CSS class!
108 *    'type'                -- roughly translates into the <select> type attribute.
109 *                             if 'class' is not specified, this is used as a map
110 *                             through HTMLForm::$typeMappings to get the class name.
111 *    'default'             -- default value when the form is displayed
112 *    'nodata'              -- if set (to any value, which casts to true), the data
113 *                             for this field will not be loaded from the actual request. Instead,
114 *                             always the default data is set as the value of this field.
115 *    'id'                  -- HTML id attribute
116 *    'cssclass'            -- CSS class
117 *    'csshelpclass'        -- CSS class used to style help text
118 *    'dir'                 -- Direction of the element.
119 *    'options'             -- associative array mapping raw HTML labels to values.
120 *                             Some field types support multi-level arrays.
121 *                             Overwrites 'options-message'.
122 *    'options-messages'    -- associative array mapping message keys to values.
123 *                             Some field types support multi-level arrays.
124 *                             Overwrites 'options' and 'options-message'.
125 *    'options-messages-parse' -- Flag to parse the messages in 'options-messages'.
126 *    'options-message'     -- message key or object to be parsed to extract the list of
127 *                             options (like 'ipbreason-dropdown').
128 *    'label-message'       -- message key or object for a message to use as the label.
129 *                             can be an array of msg key and then parameters to
130 *                             the message.
131 *    'label'               -- alternatively, a raw text message. Overridden by
132 *                             label-message
133 *    'help-raw'            -- message text for a message to use as a help text.
134 *    'help-message'        -- message key or object for a message to use as a help text.
135 *                             can be an array of msg key and then parameters to
136 *                             the message.
137 *                             Overwrites 'help-messages' and 'help-raw'.
138 *    'help-messages'       -- array of message keys/objects. As above, each item can
139 *                             be an array of msg key and then parameters.
140 *                             Overwrites 'help-raw'.
141 *    'help-inline'         -- Whether help text (defined using options above) will be shown
142 *                             inline after the input field, rather than in a popup.
143 *                             Defaults to true. Only used by OOUI form fields.
144 *    'notices'             -- Array of plain text notices to display below the input field.
145 *                             Only used by OOUI form fields.
146 *    'required'            -- passed through to the object, indicating that it
147 *                             is a required field.
148 *    'size'                -- the length of text fields
149 *    'filter-callback'     -- a function name to give you the chance to
150 *                             massage the inputted value before it's processed.
151 *                             @see HTMLFormField::filter()
152 *    'validation-callback' -- a function name to give you the chance
153 *                             to impose extra validation on the field input. The signature should be
154 *                             as documented in {@see HTMLFormField::$mValidationCallback}.
155 *                             @see HTMLFormField::validate()
156 *    'name'                -- By default, the 'name' attribute of the input field
157 *                             is "wp{$fieldname}".  If you want a different name
158 *                             (eg one without the "wp" prefix), specify it here and
159 *                             it will be used without modification.
160 *    'hide-if'             -- expression given as an array stating when the field
161 *                             should be hidden. The first array value has to be the
162 *                             expression's logic operator. Supported expressions:
163 *                               'NOT'
164 *                                 [ 'NOT', array $expression ]
165 *                                 To hide a field if a given expression is not true.
166 *                               '==='
167 *                                 [ '===', string $fieldName, string $value ]
168 *                                 To hide a field if another field identified by
169 *                                 $field has the value $value.
170 *                               '!=='
171 *                                 [ '!==', string $fieldName, string $value ]
172 *                                 Same as [ 'NOT', [ '===', $fieldName, $value ]
173 *                               'OR', 'AND', 'NOR', 'NAND'
174 *                                 [ 'XXX', array $expression1, ..., array $expressionN ]
175 *                                 To hide a field if one or more (OR), all (AND),
176 *                                 neither (NOR) or not all (NAND) given expressions
177 *                                 are evaluated as true.
178 *                             The expressions will be given to a JavaScript frontend
179 *                             module which will continually update the field's
180 *                             visibility.
181 *    'disable-if'          -- expression given as an array stating when the field
182 *                             should be disabled. See 'hide-if' for supported expressions.
183 *                             The 'hide-if' logic would also disable fields, you don't need
184 *                             to set this attribute with the same condition manually.
185 *                             You can pass both 'disabled' and this attribute to omit extra
186 *                             check, but this would function only for not 'disabled' fields.
187 *    'section'             -- A string name for the section of the form to which the field
188 *                             belongs. Subsections may be added using the separator '/', e.g.:
189 *                               'section' => 'section1/subsection1'
190 *                             More levels may be added, e.g.:
191 *                               'section' => 'section1/subsection2/subsubsection1'
192 *                             The message key for a section or subsection header is built from
193 *                             its name and the form's message prefix (if present).
194 *
195 * Since 1.20, you can chain mutators to ease the form generation:
196 * @par Example:
197 * @code
198 * $form = new HTMLForm( $someFields, $this->getContext() );
199 * $form->setMethod( 'get' )
200 *      ->setWrapperLegendMsg( 'message-key' )
201 *      ->prepareForm()
202 *      ->displayForm( '' );
203 * @endcode
204 * Note that you will have prepareForm and displayForm at the end. Other
205 * method calls done after that would simply not be part of the form :(
206 *
207 * @stable to extend
208 */
209class HTMLForm extends ContextSource {
210    use ProtectedHookAccessorTrait;
211
212    /** @var string[] A mapping of 'type' inputs onto standard HTMLFormField subclasses */
213    public static $typeMappings = [
214        'api' => HTMLApiField::class,
215        'text' => HTMLTextField::class,
216        'textwithbutton' => HTMLTextFieldWithButton::class,
217        'textarea' => HTMLTextAreaField::class,
218        'select' => HTMLSelectField::class,
219        'combobox' => HTMLComboboxField::class,
220        'radio' => HTMLRadioField::class,
221        'multiselect' => HTMLMultiSelectField::class,
222        'limitselect' => HTMLSelectLimitField::class,
223        'check' => HTMLCheckField::class,
224        'toggle' => HTMLCheckField::class,
225        'int' => HTMLIntField::class,
226        'file' => HTMLFileField::class,
227        'float' => HTMLFloatField::class,
228        'info' => HTMLInfoField::class,
229        'selectorother' => HTMLSelectOrOtherField::class,
230        'selectandother' => HTMLSelectAndOtherField::class,
231        'namespaceselect' => HTMLSelectNamespace::class,
232        'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
233        'tagfilter' => HTMLTagFilter::class,
234        'sizefilter' => HTMLSizeFilterField::class,
235        'submit' => HTMLSubmitField::class,
236        'hidden' => HTMLHiddenField::class,
237        'edittools' => HTMLEditTools::class,
238        'checkmatrix' => HTMLCheckMatrix::class,
239        'cloner' => HTMLFormFieldCloner::class,
240        'autocompleteselect' => HTMLAutoCompleteSelectField::class,
241        'language' => HTMLSelectLanguageField::class,
242        'date' => HTMLDateTimeField::class,
243        'time' => HTMLDateTimeField::class,
244        'datetime' => HTMLDateTimeField::class,
245        'expiry' => HTMLExpiryField::class,
246        'timezone' => HTMLTimezoneField::class,
247        // HTMLTextField will output the correct type="" attribute automagically.
248        // There are about four zillion other HTML5 input types, like range, but
249        // we don't use those at the moment, so no point in adding all of them.
250        'email' => HTMLTextField::class,
251        'password' => HTMLTextField::class,
252        'url' => HTMLTextField::class,
253        'title' => HTMLTitleTextField::class,
254        'user' => HTMLUserTextField::class,
255        'tagmultiselect' => HTMLTagMultiselectField::class,
256        'orderedmultiselect' => HTMLOrderedMultiselectField::class,
257        'usersmultiselect' => HTMLUsersMultiselectField::class,
258        'titlesmultiselect' => HTMLTitlesMultiselectField::class,
259        'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
260    ];
261
262    /** @var array */
263    public $mFieldData;
264
265    /** @var string */
266    protected $mMessagePrefix;
267
268    /** @var HTMLFormField[] */
269    protected $mFlatFields = [];
270    /** @var array */
271    protected $mFieldTree = [];
272    /** @var bool */
273    protected $mShowSubmit = true;
274    /** @var string[] */
275    protected $mSubmitFlags = [ 'primary', 'progressive' ];
276    /** @var bool */
277    protected $mShowCancel = false;
278    /** @var LinkTarget|string|null */
279    protected $mCancelTarget;
280
281    /** @var callable|null */
282    protected $mSubmitCallback;
283    /**
284     * @var array[]
285     * @phan-var non-empty-array[]
286     */
287    protected $mValidationErrorMessage;
288
289    /** @var string */
290    protected $mPre = '';
291    /** @var string */
292    protected $mHeader = '';
293    /** @var string */
294    protected $mFooter = '';
295    /** @var string[] */
296    protected $mSectionHeaders = [];
297    /** @var string[] */
298    protected $mSectionFooters = [];
299    /** @var string */
300    protected $mPost = '';
301    /** @var string|null */
302    protected $mId;
303    /** @var string|null */
304    protected $mName;
305    /** @var string */
306    protected $mTableId = '';
307
308    /** @var string|null */
309    protected $mSubmitID;
310    /** @var string|null */
311    protected $mSubmitName;
312    /** @var string|null */
313    protected $mSubmitText;
314    /** @var string|null */
315    protected $mSubmitTooltip;
316
317    /** @var string|null */
318    protected $mFormIdentifier;
319    /** @var bool */
320    protected $mSingleForm = false;
321
322    /** @var Title|null */
323    protected $mTitle;
324    /** @var string */
325    protected $mMethod = 'post';
326    /** @var bool */
327    protected $mWasSubmitted = false;
328
329    /**
330     * Form action URL. false means we will use the URL to set Title
331     * @since 1.19
332     * @var string|false
333     */
334    protected $mAction = false;
335
336    /**
337     * Whether the form can be collapsed
338     * @since 1.34
339     * @var bool
340     */
341    protected $mCollapsible = false;
342
343    /**
344     * Whether the form is collapsed by default
345     * @since 1.34
346     * @var bool
347     */
348    protected $mCollapsed = false;
349
350    /**
351     * Form attribute autocomplete. A typical value is "off". null does not set the attribute
352     * @since 1.27
353     * @var string|null
354     */
355    protected $mAutocomplete = null;
356
357    /** @var bool */
358    protected $mUseMultipart = false;
359    /**
360     * @var array[]
361     * @phan-var array<int,array{0:string,1:array}>
362     */
363    protected $mHiddenFields = [];
364    /**
365     * @var array[]
366     * @phan-var array<array{name:string,value:string,label-message?:string|array<string|MessageParam>|MessageSpecifier,label?:string,label-raw?:string,id?:string,attribs?:array,flags?:string|string[],framed?:bool}>
367     */
368    protected $mButtons = [];
369
370    /** @var string|false */
371    protected $mWrapperLegend = false;
372    /** @var array */
373    protected $mWrapperAttributes = [];
374
375    /**
376     * Salt for the edit token.
377     * @var string|array
378     */
379    protected $mTokenSalt = '';
380
381    /**
382     * Additional information about form sections. Only supported by CodexHTMLForm.
383     *
384     * Array is keyed on section name. Options per section include:
385     * 'description'               -- Description text placed below the section label.
386     * 'description-message'       -- The same, but a message key.
387     * 'description-message-parse' -- Whether to parse the 'description-message'
388     * 'optional'                  -- Whether the section should be marked as optional.
389     *
390     * @since 1.42
391     * @var array[]
392     */
393    protected $mSections = [];
394
395    /**
396     * If true, sections that contain both fields and subsections will
397     * render their subsections before their fields.
398     *
399     * Subclasses may set this to false to render subsections after fields
400     * instead.
401     * @var bool
402     */
403    protected $mSubSectionBeforeFields = true;
404
405    /**
406     * Format in which to display form. For viable options,
407     * @see $availableDisplayFormats
408     * @var string
409     */
410    protected $displayFormat = 'table';
411
412    /**
413     * Available formats in which to display the form
414     * @var array
415     */
416    protected $availableDisplayFormats = [
417        'table',
418        'div',
419        'raw',
420        'inline',
421    ];
422
423    /**
424     * Available formats in which to display the form
425     * @var array
426     */
427    protected $availableSubclassDisplayFormats = [
428        'vform',
429        'codex',
430        'ooui',
431    ];
432
433    /**
434     * Whether a hidden title field has been added to the form
435     * @var bool
436     */
437    private $hiddenTitleAddedToForm = false;
438
439    /**
440     * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
441     *
442     * @stable to call
443     *
444     * @param string $displayFormat
445     * @param array $descriptor Array of Field constructs, as described
446     *     in the class documentation
447     * @param IContextSource $context Context used to fetch submitted form fields and
448     *     generate localisation messages
449     * @param string $messagePrefix A prefix to go in front of default messages
450     * @return HTMLForm
451     */
452    public static function factory(
453        $displayFormat, $descriptor, IContextSource $context, $messagePrefix = ''
454    ) {
455        switch ( $displayFormat ) {
456            case 'codex':
457                return new CodexHTMLForm( $descriptor, $context, $messagePrefix );
458            case 'vform':
459                return new VFormHTMLForm( $descriptor, $context, $messagePrefix );
460            case 'ooui':
461                return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
462            default:
463                $form = new self( $descriptor, $context, $messagePrefix );
464                $form->setDisplayFormat( $displayFormat );
465                return $form;
466        }
467    }
468
469    /**
470     * Build a new HTMLForm from an array of field attributes
471     *
472     * @stable to call
473     *
474     * @param array $descriptor Array of Field constructs, as described
475     *     in the class documentation
476     * @param IContextSource $context Context used to fetch submitted form fields and
477     *     generate localisation messages
478     * @param string $messagePrefix A prefix to go in front of default messages
479     */
480    public function __construct(
481        $descriptor, IContextSource $context, $messagePrefix = ''
482    ) {
483        $this->setContext( $context );
484        $this->mMessagePrefix = $messagePrefix;
485        $this->addFields( $descriptor );
486    }
487
488    /**
489     * Add fields to the form
490     *
491     * @since 1.34
492     *
493     * @param array $descriptor Array of Field constructs, as described
494     *     in the class documentation
495     * @return HTMLForm
496     */
497    public function addFields( $descriptor ) {
498        $loadedDescriptor = [];
499
500        foreach ( $descriptor as $fieldname => $info ) {
501            $section = $info['section'] ?? '';
502
503            if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
504                $this->mUseMultipart = true;
505            }
506
507            $field = static::loadInputFromParameters( $fieldname, $info, $this );
508
509            $setSection =& $loadedDescriptor;
510            if ( $section ) {
511                foreach ( explode( '/', $section ) as $newName ) {
512                    $setSection[$newName] ??= [];
513                    $setSection =& $setSection[$newName];
514                }
515            }
516
517            $setSection[$fieldname] = $field;
518            $this->mFlatFields[$fieldname] = $field;
519        }
520
521        $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
522
523        return $this;
524    }
525
526    /**
527     * @param string $fieldname
528     * @return bool
529     */
530    public function hasField( $fieldname ) {
531        return isset( $this->mFlatFields[$fieldname] );
532    }
533
534    /**
535     * @param string $fieldname
536     * @return HTMLFormField
537     * @throws DomainException on invalid field name
538     */
539    public function getField( $fieldname ) {
540        if ( !$this->hasField( $fieldname ) ) {
541            throw new DomainException( __METHOD__ . ': no field named ' . $fieldname );
542        }
543        return $this->mFlatFields[$fieldname];
544    }
545
546    /**
547     * Set format in which to display the form
548     *
549     * @param string $format The name of the format to use, must be one of
550     *   $this->availableDisplayFormats
551     *
552     * @since 1.20
553     * @return HTMLForm $this for chaining calls (since 1.20)
554     */
555    public function setDisplayFormat( $format ) {
556        if (
557            in_array( $format, $this->availableSubclassDisplayFormats, true ) ||
558            in_array( $this->displayFormat, $this->availableSubclassDisplayFormats, true )
559        ) {
560            throw new LogicException( 'Cannot change display format after creation, ' .
561                'use HTMLForm::factory() instead' );
562        }
563
564        if ( !in_array( $format, $this->availableDisplayFormats, true ) ) {
565            throw new InvalidArgumentException( 'Display format must be one of ' .
566                print_r(
567                    array_merge(
568                        $this->availableDisplayFormats,
569                        $this->availableSubclassDisplayFormats
570                    ),
571                    true
572                ) );
573        }
574
575        $this->displayFormat = $format;
576
577        return $this;
578    }
579
580    /**
581     * Getter for displayFormat
582     * @since 1.20
583     * @return string
584     */
585    public function getDisplayFormat() {
586        return $this->displayFormat;
587    }
588
589    /**
590     * Get the HTMLFormField subclass for this descriptor.
591     *
592     * The descriptor can be passed either 'class' which is the name of
593     * a HTMLFormField subclass, or a shorter 'type' which is an alias.
594     * This makes sure the 'class' is always set, and also is returned by
595     * this function for ease.
596     *
597     * @since 1.23
598     *
599     * @param string $fieldname Name of the field
600     * @param array &$descriptor Input Descriptor, as described
601     *     in the class documentation
602     *
603     * @return string Name of a HTMLFormField subclass
604     */
605    public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
606        if ( isset( $descriptor['class'] ) ) {
607            $class = $descriptor['class'];
608        } elseif ( isset( $descriptor['type'] ) ) {
609            $class = static::$typeMappings[$descriptor['type']];
610            $descriptor['class'] = $class;
611        } else {
612            $class = null;
613        }
614
615        if ( !$class ) {
616            throw new InvalidArgumentException( "Descriptor with no class for $fieldname"
617                . print_r( $descriptor, true ) );
618        }
619
620        return $class;
621    }
622
623    /**
624     * Initialise a new Object for the field
625     * @stable to override
626     *
627     * @param string $fieldname Name of the field
628     * @param array $descriptor Input Descriptor, as described
629     *     in the class documentation
630     * @param HTMLForm|null $parent Parent instance of HTMLForm
631     *
632     * @warning Not passing (or passing null) for $parent is deprecated as of 1.40
633     * @return HTMLFormField Instance of a subclass of HTMLFormField
634     */
635    public static function loadInputFromParameters( $fieldname, $descriptor,
636        ?HTMLForm $parent = null
637    ) {
638        $class = static::getClassFromDescriptor( $fieldname, $descriptor );
639
640        $descriptor['fieldname'] = $fieldname;
641        if ( $parent ) {
642            $descriptor['parent'] = $parent;
643        }
644
645        # @todo This will throw a fatal error whenever someone try to use
646        # 'class' to feed a CSS class instead of 'cssclass'. Would be
647        # great to avoid the fatal error and show a nice error.
648        return new $class( $descriptor );
649    }
650
651    /**
652     * Prepare form for submission.
653     *
654     * @warning When doing method chaining, that should be the very last
655     * method call before displayForm().
656     *
657     * @return HTMLForm $this for chaining calls (since 1.20)
658     */
659    public function prepareForm() {
660        # Load data from the request.
661        if (
662            $this->mFormIdentifier === null ||
663            $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier ||
664            ( $this->mSingleForm && $this->getMethod() === 'get' )
665        ) {
666            $this->loadFieldData();
667        } else {
668            $this->mFieldData = [];
669        }
670
671        return $this;
672    }
673
674    /**
675     * Try submitting, with edit token check first
676     * @return bool|string|array|Status As documented for HTMLForm::trySubmit
677     */
678    public function tryAuthorizedSubmit() {
679        $result = false;
680
681        if ( $this->mFormIdentifier === null ) {
682            $identOkay = true;
683        } else {
684            $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier;
685        }
686
687        $tokenOkay = false;
688        if ( $this->getMethod() !== 'post' ) {
689            $tokenOkay = true; // no session check needed
690        } elseif ( $this->getRequest()->wasPosted() ) {
691            $editToken = $this->getRequest()->getVal( 'wpEditToken' );
692            if ( $this->getUser()->isRegistered() || $editToken !== null ) {
693                // Session tokens for logged-out users have no security value.
694                // However, if the user gave one, check it in order to give a nice
695                // "session expired" error instead of "permission denied" or such.
696                $tokenOkay = $this->getCsrfTokenSet()->matchTokenField(
697                    CsrfTokenSet::DEFAULT_FIELD_NAME, $this->mTokenSalt
698                );
699            } else {
700                $tokenOkay = true;
701            }
702        }
703
704        if ( $tokenOkay && $identOkay ) {
705            $this->mWasSubmitted = true;
706            $result = $this->trySubmit();
707        }
708
709        return $result;
710    }
711
712    /**
713     * The here's-one-I-made-earlier option: do the submission if
714     * posted, or display the form with or without funky validation
715     * errors
716     * @stable to override
717     * @return bool|Status Whether submission was successful.
718     */
719    public function show() {
720        $this->prepareForm();
721
722        $result = $this->tryAuthorizedSubmit();
723        if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
724            return $result;
725        }
726
727        $this->displayForm( $result );
728
729        return false;
730    }
731
732    /**
733     * Same as self::show with the difference, that the form will be
734     * added to the output, no matter, if the validation was good or not.
735     * @return bool|Status Whether submission was successful.
736     */
737    public function showAlways() {
738        $this->prepareForm();
739
740        $result = $this->tryAuthorizedSubmit();
741
742        $this->displayForm( $result );
743
744        return $result;
745    }
746
747    /**
748     * Validate all the fields, and call the submission callback
749     * function if everything is kosher.
750     * @stable to override
751     * @return bool|string|array|Status
752     *     - Bool true or a good Status object indicates success,
753     *     - Bool false indicates no submission was attempted,
754     *     - Anything else indicates failure. The value may be a fatal Status
755     *       object, an HTML string, or an array of arrays (message keys and
756     *       params) or strings (message keys)
757     */
758    public function trySubmit() {
759        $valid = true;
760        $hoistedErrors = Status::newGood();
761        if ( $this->mValidationErrorMessage ) {
762            foreach ( $this->mValidationErrorMessage as $error ) {
763                $hoistedErrors->fatal( ...$error );
764            }
765        } else {
766            $hoistedErrors->fatal( 'htmlform-invalid-input' );
767        }
768
769        $this->mWasSubmitted = true;
770
771        # Check for cancelled submission
772        foreach ( $this->mFlatFields as $fieldname => $field ) {
773            if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
774                continue;
775            }
776            if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
777                $this->mWasSubmitted = false;
778                return false;
779            }
780        }
781
782        # Check for validation
783        $hasNonDefault = false;
784        foreach ( $this->mFlatFields as $fieldname => $field ) {
785            if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
786                continue;
787            }
788            $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
789            if ( $field->isDisabled( $this->mFieldData ) ) {
790                continue;
791            }
792            $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
793            if ( $res !== true ) {
794                $valid = false;
795                if ( $res !== false && !$field->canDisplayErrors() ) {
796                    if ( is_string( $res ) ) {
797                        $hoistedErrors->fatal( 'rawmessage', $res );
798                    } else {
799                        $hoistedErrors->fatal( $res );
800                    }
801                }
802            }
803        }
804
805        if ( !$valid ) {
806            // Treat as not submitted if got nothing from the user on GET forms.
807            if ( !$hasNonDefault && $this->getMethod() === 'get' &&
808                ( $this->mFormIdentifier === null ||
809                    $this->getRequest()->getCheck( 'wpFormIdentifier' ) )
810            ) {
811                $this->mWasSubmitted = false;
812                return false;
813            }
814            return $hoistedErrors;
815        }
816
817        $callback = $this->mSubmitCallback;
818        if ( !is_callable( $callback ) ) {
819            throw new LogicException( 'HTMLForm: no submit callback provided. Use ' .
820                'setSubmitCallback() to set one.' );
821        }
822
823        $data = $this->filterDataForSubmit( $this->mFieldData );
824
825        $res = $callback( $data, $this );
826        if ( $res === false ) {
827            $this->mWasSubmitted = false;
828        } elseif ( $res instanceof StatusValue ) {
829            // DWIM - callbacks are not supposed to return a StatusValue but it's easy to mix up.
830            $res = Status::wrap( $res );
831        }
832
833        return $res;
834    }
835
836    /**
837     * Test whether the form was considered to have been submitted or not, i.e.
838     * whether the last call to tryAuthorizedSubmit or trySubmit returned
839     * non-false.
840     *
841     * This will return false until HTMLForm::tryAuthorizedSubmit or
842     * HTMLForm::trySubmit is called.
843     *
844     * @since 1.23
845     * @return bool
846     */
847    public function wasSubmitted() {
848        return $this->mWasSubmitted;
849    }
850
851    /**
852     * Set a callback to a function to do something with the form
853     * once it's been successfully validated.
854     *
855     * @param callable $cb The function will be passed the output from
856     *   HTMLForm::filterDataForSubmit and this HTMLForm object, and must
857     *   return as documented for HTMLForm::trySubmit
858     *
859     * @return HTMLForm $this for chaining calls (since 1.20)
860     */
861    public function setSubmitCallback( $cb ) {
862        $this->mSubmitCallback = $cb;
863
864        return $this;
865    }
866
867    /**
868     * Set a message to display on a validation error.
869     *
870     * @param array[] $msg Array of valid inputs to wfMessage()
871     *     (so each entry must itself be an array of arguments)
872     * @phan-param non-empty-array[] $msg
873     *
874     * @return HTMLForm $this for chaining calls (since 1.20)
875     */
876    public function setValidationErrorMessage( $msg ) {
877        $this->mValidationErrorMessage = $msg;
878
879        return $this;
880    }
881
882    /**
883     * Set the introductory message HTML, overwriting any existing message.
884     *
885     * @param string $html Complete HTML of message to display
886     *
887     * @since 1.38
888     * @return $this for chaining calls
889     */
890    public function setPreHtml( $html ) {
891        $this->mPre = $html;
892
893        return $this;
894    }
895
896    /**
897     * Add HTML to introductory message.
898     *
899     * @param string $html Complete HTML of message to display
900     *
901     * @since 1.38
902     * @return $this for chaining calls
903     */
904    public function addPreHtml( $html ) {
905        $this->mPre .= $html;
906
907        return $this;
908    }
909
910    /**
911     * Get the introductory message HTML.
912     *
913     * @since 1.38
914     * @return string
915     */
916    public function getPreHtml() {
917        return $this->mPre;
918    }
919
920    /**
921     * Add HTML to the header, inside the form.
922     *
923     * @param string $html Additional HTML to display in header
924     * @param string|null $section The section to add the header to
925     *
926     * @since 1.38
927     * @return $this for chaining calls
928     */
929    public function addHeaderHtml( $html, $section = null ) {
930        if ( $section === null ) {
931            $this->mHeader .= $html;
932        } else {
933            $this->mSectionHeaders[$section] ??= '';
934            $this->mSectionHeaders[$section] .= $html;
935        }
936
937        return $this;
938    }
939
940    /**
941     * Set header HTML, inside the form.
942     *
943     * @param string $html Complete HTML of header to display
944     * @param string|null $section The section to add the header to
945     *
946     * @since 1.38
947     * @return $this for chaining calls
948     */
949    public function setHeaderHtml( $html, $section = null ) {
950        if ( $section === null ) {
951            $this->mHeader = $html;
952        } else {
953            $this->mSectionHeaders[$section] = $html;
954        }
955
956        return $this;
957    }
958
959    /**
960     * Get header HTML.
961     * @stable to override
962     *
963     * @param string|null $section The section to get the header text for
964     * @since 1.38
965     * @return string HTML
966     */
967    public function getHeaderHtml( $section = null ) {
968        return $section ? $this->mSectionHeaders[$section] ?? '' : $this->mHeader;
969    }
970
971    /**
972     * Add footer HTML, inside the form.
973     *
974     * @param string $html Complete text of message to display
975     * @param string|null $section The section to add the footer text to
976     *
977     * @since 1.38
978     * @return $this for chaining calls
979     */
980    public function addFooterHtml( $html, $section = null ) {
981        if ( $section === null ) {
982            $this->mFooter .= $html;
983        } else {
984            $this->mSectionFooters[$section] ??= '';
985            $this->mSectionFooters[$section] .= $html;
986        }
987
988        return $this;
989    }
990
991    /**
992     * Set footer HTML, inside the form.
993     *
994     * @param string $html Complete text of message to display
995     * @param string|null $section The section to add the footer text to
996     *
997     * @since 1.38
998     * @return $this for chaining calls
999     */
1000    public function setFooterHtml( $html, $section = null ) {
1001        if ( $section === null ) {
1002            $this->mFooter = $html;
1003        } else {
1004            $this->mSectionFooters[$section] = $html;
1005        }
1006
1007        return $this;
1008    }
1009
1010    /**
1011     * Get footer HTML.
1012     *
1013     * @param string|null $section The section to get the footer text for
1014     * @since 1.38
1015     * @return string
1016     */
1017    public function getFooterHtml( $section = null ) {
1018        return $section ? $this->mSectionFooters[$section] ?? '' : $this->mFooter;
1019    }
1020
1021    /**
1022     * Add HTML to the end of the display.
1023     *
1024     * @param string $html Complete text of message to display
1025     *
1026     * @since 1.38
1027     * @return $this for chaining calls
1028     */
1029    public function addPostHtml( $html ) {
1030        $this->mPost .= $html;
1031
1032        return $this;
1033    }
1034
1035    /**
1036     * Set HTML at the end of the display.
1037     *
1038     * @param string $html Complete text of message to display
1039     *
1040     * @since 1.38
1041     * @return $this for chaining calls
1042     */
1043    public function setPostHtml( $html ) {
1044        $this->mPost = $html;
1045
1046        return $this;
1047    }
1048
1049    /**
1050     * Get HTML at the end of the display.
1051     *
1052     * @since 1.38
1053     * @return string HTML
1054     */
1055    public function getPostHtml() {
1056        return $this->mPost;
1057    }
1058
1059    /**
1060     * Set an array of information about sections.
1061     *
1062     * @since 1.42
1063     *
1064     * @param array[] $sections Array of section information, keyed on section name.
1065     *
1066     * @return HTMLForm $this for chaining calls
1067     */
1068    public function setSections( $sections ) {
1069        if ( $this->getDisplayFormat() !== 'codex' ) {
1070            throw new \InvalidArgumentException(
1071                "Non-Codex HTMLForms do not support additional section information."
1072            );
1073        }
1074
1075        $this->mSections = $sections;
1076
1077        return $this;
1078    }
1079
1080    /**
1081     * Add a hidden field to the output
1082     * Array values are discarded for security reasons (per WebRequest::getVal)
1083     *
1084     * @param string $name Field name.  This will be used exactly as entered
1085     * @param mixed $value Field value
1086     * @param array $attribs
1087     *
1088     * @return HTMLForm $this for chaining calls (since 1.20)
1089     */
1090    public function addHiddenField( $name, $value, array $attribs = [] ) {
1091        if ( !is_array( $value ) ) {
1092            // Per WebRequest::getVal: Array values are discarded for security reasons.
1093            $attribs += [ 'name' => $name ];
1094            $this->mHiddenFields[] = [ $value, $attribs ];
1095        }
1096
1097        return $this;
1098    }
1099
1100    /**
1101     * Add an array of hidden fields to the output
1102     * Array values are discarded for security reasons (per WebRequest::getVal)
1103     *
1104     * @since 1.22
1105     *
1106     * @param array $fields Associative array of fields to add;
1107     *        mapping names to their values
1108     *
1109     * @return HTMLForm $this for chaining calls
1110     */
1111    public function addHiddenFields( array $fields ) {
1112        foreach ( $fields as $name => $value ) {
1113            if ( is_array( $value ) ) {
1114                // Per WebRequest::getVal: Array values are discarded for security reasons.
1115                continue;
1116            }
1117            $this->mHiddenFields[] = [ $value, [ 'name' => $name ] ];
1118        }
1119
1120        return $this;
1121    }
1122
1123    /**
1124     * Add a button to the form
1125     *
1126     * @since 1.27 takes an array as shown. Earlier versions accepted
1127     *  'name', 'value', 'id', and 'attribs' as separate parameters in that
1128     *  order.
1129     * @param array $data Data to define the button:
1130     *  - name: (string) Button name.
1131     *  - value: (string) Button value.
1132     *  - label-message: (string|array<string|array>|MessageSpecifier, optional) Button label
1133     *    message key to use instead of 'value'. Overrides 'label' and 'label-raw'.
1134     *  - label: (string, optional) Button label text to use instead of
1135     *    'value'. Overrides 'label-raw'.
1136     *  - label-raw: (string, optional) Button label HTML to use instead of
1137     *    'value'.
1138     *  - id: (string, optional) DOM id for the button.
1139     *  - attribs: (array, optional) Additional HTML attributes.
1140     *  - flags: (string|string[], optional) OOUI flags.
1141     *  - framed: (boolean=true, optional) OOUI framed attribute.
1142     * @phpcs:ignore Generic.Files.LineLength
1143     * @phan-param array{name:string,value:string,label-message?:string|array<string|MessageParam>|MessageSpecifier,label?:string,label-raw?:string,id?:string,attribs?:array,flags?:string|string[],framed?:bool} $data
1144     * @return HTMLForm $this for chaining calls (since 1.20)
1145     */
1146    public function addButton( $data ) {
1147        if ( !is_array( $data ) ) {
1148            $args = func_get_args();
1149            if ( count( $args ) < 2 || count( $args ) > 4 ) {
1150                throw new InvalidArgumentException(
1151                    'Incorrect number of arguments for deprecated calling style'
1152                );
1153            }
1154            $data = [
1155                'name' => $args[0],
1156                'value' => $args[1],
1157                'id' => $args[2] ?? null,
1158                'attribs' => $args[3] ?? null,
1159            ];
1160        } else {
1161            if ( !isset( $data['name'] ) ) {
1162                throw new InvalidArgumentException( 'A name is required' );
1163            }
1164            if ( !isset( $data['value'] ) ) {
1165                throw new InvalidArgumentException( 'A value is required' );
1166            }
1167        }
1168        $this->mButtons[] = $data + [
1169            'id' => null,
1170            'attribs' => null,
1171            'flags' => null,
1172            'framed' => true,
1173        ];
1174
1175        return $this;
1176    }
1177
1178    /**
1179     * Set the salt for the edit token.
1180     *
1181     * Only useful when the method is "post".
1182     *
1183     * @since 1.24
1184     * @param string|array $salt Salt to use
1185     * @return HTMLForm $this For chaining calls
1186     */
1187    public function setTokenSalt( $salt ) {
1188        $this->mTokenSalt = $salt;
1189
1190        return $this;
1191    }
1192
1193    /**
1194     * Display the form (sending to the context's OutputPage object), with an
1195     * appropriate error message or stack of messages, and any validation errors, etc.
1196     *
1197     * @warning You should call prepareForm() before calling this function.
1198     * Moreover, when doing method chaining this should be the very last method
1199     * call just after prepareForm().
1200     *
1201     * @stable to override
1202     *
1203     * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1204     *
1205     * @return void Nothing, should be last call
1206     */
1207    public function displayForm( $submitResult ) {
1208        $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1209    }
1210
1211    /**
1212     * Get a hidden field for the title of the page if necessary (empty string otherwise)
1213     */
1214    private function getHiddenTitle(): string {
1215        if ( $this->hiddenTitleAddedToForm ) {
1216            return '';
1217        }
1218
1219        $html = '';
1220        if ( $this->getMethod() === 'post' ||
1221            $this->getAction() === $this->getConfig()->get( MainConfigNames::Script )
1222        ) {
1223            $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1224        }
1225        $this->hiddenTitleAddedToForm = true;
1226        return $html;
1227    }
1228
1229    /**
1230     * Returns the raw HTML generated by the form
1231     *
1232     * @stable to override
1233     *
1234     * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1235     *
1236     * @return string HTML
1237     * @return-taint escaped
1238     */
1239    public function getHTML( $submitResult ) {
1240        # For good measure (it is the default)
1241        $this->getOutput()->getMetadata()->setPreventClickjacking( true );
1242        $this->getOutput()->addModules( 'mediawiki.htmlform' );
1243        $this->getOutput()->addModuleStyles( [
1244            'mediawiki.htmlform.styles',
1245            // Html::errorBox and Html::warningBox used by HtmlFormField and HtmlForm::getErrorsOrWarnings
1246            'mediawiki.codex.messagebox.styles'
1247        ] );
1248
1249        if ( $this->mCollapsible ) {
1250            // Preload jquery.makeCollapsible for mediawiki.htmlform
1251            $this->getOutput()->addModules( 'jquery.makeCollapsible' );
1252        }
1253
1254        $headerHtml = $this->getHeaderHtml();
1255        $footerHtml = $this->getFooterHtml();
1256        $html = $this->getErrorsOrWarnings( $submitResult, 'error' )
1257            . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1258            . $headerHtml
1259            . $this->getHiddenTitle()
1260            . $this->getBody()
1261            . $this->getHiddenFields()
1262            . $this->getButtons()
1263            . $footerHtml;
1264
1265        return $this->mPre . $this->wrapForm( $html ) . $this->mPost;
1266    }
1267
1268    /**
1269     * Enable collapsible mode, and set whether the form is collapsed by default.
1270     *
1271     * @since 1.34
1272     * @param bool $collapsedByDefault Whether the form is collapsed by default (optional).
1273     * @return HTMLForm $this for chaining calls
1274     */
1275    public function setCollapsibleOptions( $collapsedByDefault = false ) {
1276        $this->mCollapsible = true;
1277        $this->mCollapsed = $collapsedByDefault;
1278        return $this;
1279    }
1280
1281    /**
1282     * Get HTML attributes for the `<form>` tag.
1283     * @stable to override
1284     * @return array
1285     */
1286    protected function getFormAttributes() {
1287        # Use multipart/form-data
1288        $encType = $this->mUseMultipart
1289            ? 'multipart/form-data'
1290            : 'application/x-www-form-urlencoded';
1291        # Attributes
1292        $attribs = [
1293            'class' => 'mw-htmlform',
1294            'action' => $this->getAction(),
1295            'method' => $this->getMethod(),
1296            'enctype' => $encType,
1297        ];
1298        if ( $this->mId ) {
1299            $attribs['id'] = $this->mId;
1300        }
1301        if ( is_string( $this->mAutocomplete ) ) {
1302            $attribs['autocomplete'] = $this->mAutocomplete;
1303        }
1304        if ( $this->mName ) {
1305            $attribs['name'] = $this->mName;
1306        }
1307        if ( $this->needsJSForHtml5FormValidation() ) {
1308            $attribs['novalidate'] = true;
1309        }
1310        return $attribs;
1311    }
1312
1313    /**
1314     * Wrap the form innards in an actual "<form>" element
1315     *
1316     * @stable to override
1317     * @param string $html HTML contents to wrap.
1318     * @return string|\OOUI\Tag Wrapped HTML.
1319     */
1320    public function wrapForm( $html ) {
1321        # Include a <fieldset> wrapper for style, if requested.
1322        if ( $this->mWrapperLegend !== false ) {
1323            $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend : false;
1324            $html = Html::rawElement(
1325                'fieldset',
1326                $this->mWrapperAttributes,
1327                ( $legend ? Html::element( 'legend', [], $legend ) : '' ) . $html
1328            );
1329        }
1330
1331        return Html::rawElement(
1332            'form',
1333            $this->getFormAttributes(),
1334            $html
1335        );
1336    }
1337
1338    /**
1339     * Get the hidden fields that should go inside the form.
1340     * @return string HTML.
1341     */
1342    public function getHiddenFields() {
1343        $html = '';
1344
1345        // add the title as a hidden file if it hasn't been added yet and if it is necessary
1346        // added for backward compatibility with the previous version of this public method
1347        $html .= $this->getHiddenTitle();
1348
1349        if ( $this->mFormIdentifier !== null ) {
1350            $html .= Html::hidden(
1351                'wpFormIdentifier',
1352                $this->mFormIdentifier
1353            ) . "\n";
1354        }
1355        if ( $this->getMethod() === 'post' ) {
1356            $html .= Html::hidden(
1357                'wpEditToken',
1358                $this->getUser()->getEditToken( $this->mTokenSalt ),
1359                [ 'id' => 'wpEditToken' ]
1360            ) . "\n";
1361        }
1362
1363        foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1364            $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
1365        }
1366
1367        return $html;
1368    }
1369
1370    /**
1371     * Get the submit and (potentially) reset buttons.
1372     * @stable to override
1373     * @return string HTML.
1374     */
1375    public function getButtons() {
1376        $buttons = '';
1377
1378        if ( $this->mShowSubmit ) {
1379            $attribs = [];
1380
1381            if ( $this->mSubmitID !== null ) {
1382                $attribs['id'] = $this->mSubmitID;
1383            }
1384
1385            if ( $this->mSubmitName !== null ) {
1386                $attribs['name'] = $this->mSubmitName;
1387            }
1388
1389            if ( $this->mSubmitTooltip !== null ) {
1390                $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1391            }
1392
1393            $attribs['class'] = [ 'mw-htmlform-submit' ];
1394
1395            $buttons .= Html::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1396        }
1397
1398        if ( $this->mShowCancel ) {
1399            $target = $this->getCancelTargetURL();
1400            $buttons .= Html::element(
1401                    'a',
1402                    [
1403                        'href' => $target,
1404                    ],
1405                    $this->msg( 'cancel' )->text()
1406                ) . "\n";
1407        }
1408
1409        foreach ( $this->mButtons as $button ) {
1410            $attrs = [
1411                'type' => 'submit',
1412                'name' => $button['name'],
1413                'value' => $button['value']
1414            ];
1415
1416            if ( isset( $button['label-message'] ) ) {
1417                $label = $this->getMessage( $button['label-message'] )->parse();
1418            } elseif ( isset( $button['label'] ) ) {
1419                $label = htmlspecialchars( $button['label'] );
1420            } elseif ( isset( $button['label-raw'] ) ) {
1421                $label = $button['label-raw'];
1422            } else {
1423                $label = htmlspecialchars( $button['value'] );
1424            }
1425
1426            // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in self::addButton
1427            if ( $button['attribs'] ) {
1428                // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in self::addButton
1429                $attrs += $button['attribs'];
1430            }
1431
1432            if ( isset( $button['id'] ) ) {
1433                $attrs['id'] = $button['id'];
1434            }
1435
1436            $buttons .= Html::rawElement( 'button', $attrs, $label ) . "\n";
1437        }
1438
1439        if ( !$buttons ) {
1440            return '';
1441        }
1442
1443        return Html::rawElement( 'span',
1444            [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1445    }
1446
1447    /**
1448     * Get the whole body of the form.
1449     * @stable to override
1450     * @return string
1451     */
1452    public function getBody() {
1453        return $this->displaySection( $this->mFieldTree, $this->mTableId );
1454    }
1455
1456    /**
1457     * Returns a formatted list of errors or warnings from the given elements.
1458     * @stable to override
1459     *
1460     * @param string|array|Status $elements The set of errors/warnings to process.
1461     * @param string $elementsType Should warnings or errors be returned.  This is meant
1462     *     for Status objects, all other valid types are always considered as errors.
1463     * @return string
1464     */
1465    public function getErrorsOrWarnings( $elements, $elementsType ) {
1466        if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1467            throw new DomainException( $elementsType . ' is not a valid type.' );
1468        }
1469        $elementstr = false;
1470        if ( $elements instanceof Status ) {
1471            [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1472            $status = $elementsType === 'error' ? $errorStatus : $warningStatus;
1473            if ( $status->isGood() ) {
1474                $elementstr = '';
1475            } else {
1476                $elementstr = $status
1477                    ->getMessage()
1478                    ->setContext( $this )
1479                    ->setInterfaceMessageFlag( true )
1480                    ->parse();
1481            }
1482        } elseif ( $elementsType === 'error' ) {
1483            if ( is_array( $elements ) ) {
1484                $elementstr = $this->formatErrors( $elements );
1485            } elseif ( $elements && $elements !== true ) {
1486                $elementstr = (string)$elements;
1487            }
1488        }
1489
1490        if ( !$elementstr ) {
1491            return '';
1492        } elseif ( $elementsType === 'error' ) {
1493            return Html::errorBox( $elementstr );
1494        } else { // $elementsType can only be 'warning'
1495            return Html::warningBox( $elementstr );
1496        }
1497    }
1498
1499    /**
1500     * Format a stack of error messages into a single HTML string
1501     *
1502     * @param array $errors Array of message keys/values
1503     *
1504     * @return string HTML, a "<ul>" list of errors
1505     */
1506    public function formatErrors( $errors ) {
1507        $errorstr = '';
1508
1509        foreach ( $errors as $error ) {
1510            $errorstr .= Html::rawElement(
1511                'li',
1512                [],
1513                $this->getMessage( $error )->parse()
1514            );
1515        }
1516
1517        return Html::rawElement( 'ul', [], $errorstr );
1518    }
1519
1520    /**
1521     * Set the text for the submit button
1522     *
1523     * @param string $t Plaintext
1524     *
1525     * @return HTMLForm $this for chaining calls (since 1.20)
1526     */
1527    public function setSubmitText( $t ) {
1528        $this->mSubmitText = $t;
1529
1530        return $this;
1531    }
1532
1533    /**
1534     * Identify that the submit button in the form has a destructive action
1535     * @since 1.24
1536     *
1537     * @return HTMLForm $this for chaining calls (since 1.28)
1538     */
1539    public function setSubmitDestructive() {
1540        $this->mSubmitFlags = [ 'destructive', 'primary' ];
1541
1542        return $this;
1543    }
1544
1545    /**
1546     * Set the text for the submit button to a message
1547     * @since 1.19
1548     *
1549     * @param string|Message $msg Message key or Message object
1550     *
1551     * @return HTMLForm $this for chaining calls (since 1.20)
1552     */
1553    public function setSubmitTextMsg( $msg ) {
1554        if ( !$msg instanceof Message ) {
1555            $msg = $this->msg( $msg );
1556        }
1557        $this->setSubmitText( $msg->text() );
1558
1559        return $this;
1560    }
1561
1562    /**
1563     * Get the text for the submit button, either customised or a default.
1564     * @return string
1565     */
1566    public function getSubmitText() {
1567        return $this->mSubmitText ?: $this->msg( 'htmlform-submit' )->text();
1568    }
1569
1570    /**
1571     * @param string $name Submit button name
1572     *
1573     * @return HTMLForm $this for chaining calls (since 1.20)
1574     */
1575    public function setSubmitName( $name ) {
1576        $this->mSubmitName = $name;
1577
1578        return $this;
1579    }
1580
1581    /**
1582     * @param string $name Tooltip for the submit button
1583     *
1584     * @return HTMLForm $this for chaining calls (since 1.20)
1585     */
1586    public function setSubmitTooltip( $name ) {
1587        $this->mSubmitTooltip = $name;
1588
1589        return $this;
1590    }
1591
1592    /**
1593     * Set the id for the submit button.
1594     *
1595     * @param string $t
1596     *
1597     * @todo FIXME: Integrity of $t is *not* validated
1598     * @return HTMLForm $this for chaining calls (since 1.20)
1599     */
1600    public function setSubmitID( $t ) {
1601        $this->mSubmitID = $t;
1602
1603        return $this;
1604    }
1605
1606    /**
1607     * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1608     * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1609     * two purposes:
1610     *
1611     * - If you use two or more forms on one page with the same submit target, it allows HTMLForm
1612     *   to identify which of the forms was submitted, and not attempt to validate the other ones.
1613     * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1614     *   HTMLForm to distinguish between the initial page view and a form submission with all
1615     *   checkboxes or select options unchecked. Set the second parameter to true if you are sure
1616     *   this is the only form on the page, which allows form fields to be prefilled with query
1617     *   params.
1618     *
1619     * @since 1.28
1620     * @param string $ident
1621     * @param bool $single Only work with GET form, see above. (since 1.41)
1622     * @return $this
1623     */
1624    public function setFormIdentifier( string $ident, bool $single = false ) {
1625        $this->mFormIdentifier = $ident;
1626        $this->mSingleForm = $single;
1627
1628        return $this;
1629    }
1630
1631    /**
1632     * Stop a default submit button being shown for this form. This implies that an
1633     * alternate submit method must be provided manually.
1634     *
1635     * @since 1.22
1636     *
1637     * @param bool $suppressSubmit Set to false to re-enable the button again
1638     *
1639     * @return HTMLForm $this for chaining calls
1640     */
1641    public function suppressDefaultSubmit( $suppressSubmit = true ) {
1642        $this->mShowSubmit = !$suppressSubmit;
1643
1644        return $this;
1645    }
1646
1647    /**
1648     * Show a cancel button (or prevent it). The button is not shown by default.
1649     * @param bool $show
1650     * @return HTMLForm $this for chaining calls
1651     * @since 1.27
1652     */
1653    public function showCancel( $show = true ) {
1654        $this->mShowCancel = $show;
1655        return $this;
1656    }
1657
1658    /**
1659     * Sets the target where the user is redirected to after clicking cancel.
1660     * @param LinkTarget|PageReference|string $target Target as an object or an URL
1661     * @return HTMLForm $this for chaining calls
1662     * @since 1.27
1663     */
1664    public function setCancelTarget( $target ) {
1665        if ( $target instanceof PageReference ) {
1666            $target = TitleValue::castPageToLinkTarget( $target );
1667        }
1668
1669        $this->mCancelTarget = $target;
1670        return $this;
1671    }
1672
1673    /**
1674     * @since 1.37
1675     * @return string
1676     */
1677    protected function getCancelTargetURL() {
1678        if ( is_string( $this->mCancelTarget ) ) {
1679            return $this->mCancelTarget;
1680        } else {
1681            // TODO: use a service to get the local URL for a LinkTarget, see T282283
1682            $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1683            return $target->getLocalURL();
1684        }
1685    }
1686
1687    /**
1688     * Set the id of the \<table\> or outermost \<div\> element.
1689     *
1690     * @since 1.22
1691     *
1692     * @param string $id New value of the id attribute, or "" to remove
1693     *
1694     * @return HTMLForm $this for chaining calls
1695     */
1696    public function setTableId( $id ) {
1697        $this->mTableId = $id;
1698
1699        return $this;
1700    }
1701
1702    /**
1703     * @param string $id DOM id for the form
1704     *
1705     * @return HTMLForm $this for chaining calls (since 1.20)
1706     */
1707    public function setId( $id ) {
1708        $this->mId = $id;
1709
1710        return $this;
1711    }
1712
1713    /**
1714     * @param string $name 'name' attribute for the form
1715     * @return HTMLForm $this for chaining calls
1716     */
1717    public function setName( $name ) {
1718        $this->mName = $name;
1719
1720        return $this;
1721    }
1722
1723    /**
1724     * Prompt the whole form to be wrapped in a "<fieldset>", with
1725     * this text as its "<legend>" element.
1726     *
1727     * @param string|bool $legend If false, no wrapper or legend will be displayed.
1728     *     If true, a wrapper will be displayed, but no legend.
1729     *     If a string, a wrapper will be displayed with that string as a legend.
1730     *     The string will be escaped before being output (this doesn't support HTML).
1731     *
1732     * @return HTMLForm $this for chaining calls (since 1.20)
1733     */
1734    public function setWrapperLegend( $legend ) {
1735        $this->mWrapperLegend = $legend;
1736
1737        return $this;
1738    }
1739
1740    /**
1741     * For internal use only. Use is discouraged, and should only be used where
1742     * support for gadgets/user scripts is warranted.
1743     * @param array $attributes
1744     * @internal
1745     * @return HTMLForm $this for chaining calls
1746     */
1747    public function setWrapperAttributes( $attributes ) {
1748        $this->mWrapperAttributes = $attributes;
1749
1750        return $this;
1751    }
1752
1753    /**
1754     * Prompt the whole form to be wrapped in a "<fieldset>", with
1755     * this message as its "<legend>" element.
1756     * @since 1.19
1757     *
1758     * @param string|Message $msg Message key or Message object
1759     *
1760     * @return HTMLForm $this for chaining calls (since 1.20)
1761     */
1762    public function setWrapperLegendMsg( $msg ) {
1763        if ( !$msg instanceof Message ) {
1764            $msg = $this->msg( $msg );
1765        }
1766        $this->setWrapperLegend( $msg->text() );
1767
1768        return $this;
1769    }
1770
1771    /**
1772     * Set the prefix for various default messages
1773     * @todo Currently only used for the "<fieldset>" legend on forms
1774     * with multiple sections; should be used elsewhere?
1775     *
1776     * @param string $p
1777     *
1778     * @return HTMLForm $this for chaining calls (since 1.20)
1779     */
1780    public function setMessagePrefix( $p ) {
1781        $this->mMessagePrefix = $p;
1782
1783        return $this;
1784    }
1785
1786    /**
1787     * Set the title for form submission
1788     *
1789     * @param PageReference $t The page the form is on/should be posted to
1790     *
1791     * @return HTMLForm $this for chaining calls (since 1.20)
1792     */
1793    public function setTitle( $t ) {
1794        // TODO: make mTitle a PageReference when we have a better way to get URLs, see T282283.
1795        $this->mTitle = Title::castFromPageReference( $t );
1796
1797        return $this;
1798    }
1799
1800    /**
1801     * @return Title
1802     */
1803    public function getTitle() {
1804        return $this->mTitle ?: $this->getContext()->getTitle();
1805    }
1806
1807    /**
1808     * Set the method used to submit the form
1809     *
1810     * @param string $method
1811     *
1812     * @return HTMLForm $this for chaining calls (since 1.20)
1813     */
1814    public function setMethod( $method = 'post' ) {
1815        $this->mMethod = strtolower( $method );
1816
1817        return $this;
1818    }
1819
1820    /**
1821     * @return string Always lowercase
1822     */
1823    public function getMethod() {
1824        return $this->mMethod;
1825    }
1826
1827    /**
1828     * Wraps the given $section into a user-visible fieldset.
1829     * @stable to override
1830     *
1831     * @param string $legend Legend text for the fieldset
1832     * @param string $section The section content in plain Html
1833     * @param array $attributes Additional attributes for the fieldset
1834     * @param bool $isRoot Section is at the root of the tree
1835     * @return string The fieldset's Html
1836     */
1837    protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1838        return Html::rawElement(
1839            'fieldset',
1840            $attributes,
1841            Html::element( 'legend', [], $legend ) . $section
1842        ) . "\n";
1843    }
1844
1845    /**
1846     * @todo Document
1847     * @stable to override
1848     *
1849     * Throws an exception when called on uninitialized field data, e.g. when
1850     * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1851     * first.
1852     *
1853     * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1854     *   objects).
1855     * @param string $sectionName ID attribute of the "<table>" tag for this
1856     *   section, ignored if empty.
1857     * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1858     *   each subsection, ignored if empty.
1859     * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1860     *
1861     * @return string
1862     */
1863    public function displaySection( $fields,
1864        $sectionName = '',
1865        $fieldsetIDPrefix = '',
1866        &$hasUserVisibleFields = false
1867    ) {
1868        if ( $this->mFieldData === null ) {
1869            throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1870                . 'You probably called displayForm() without calling prepareForm() first.' );
1871        }
1872
1873        $html = [];
1874        $subsectionHtml = '';
1875        $hasLabel = false;
1876
1877        foreach ( $fields as $key => $value ) {
1878            if ( $value instanceof HTMLFormField ) {
1879                $v = array_key_exists( $key, $this->mFieldData )
1880                    ? $this->mFieldData[$key]
1881                    : $value->getDefault();
1882
1883                $retval = $this->formatField( $value, $v ?? '' );
1884
1885                // check, if the form field should be added to
1886                // the output.
1887                if ( $value->hasVisibleOutput() ) {
1888                    $html[] = $retval;
1889
1890                    $labelValue = trim( $value->getLabel() );
1891                    if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
1892                        $hasLabel = true;
1893                    }
1894
1895                    $hasUserVisibleFields = true;
1896                }
1897            } elseif ( is_array( $value ) ) {
1898                $subsectionHasVisibleFields = false;
1899                $section =
1900                    $this->displaySection( $value,
1901                        "mw-htmlform-$key",
1902                        "$fieldsetIDPrefix$key-",
1903                        $subsectionHasVisibleFields );
1904
1905                if ( $subsectionHasVisibleFields === true ) {
1906                    // Display the section with various niceties.
1907                    $hasUserVisibleFields = true;
1908
1909                    $legend = $this->getLegend( $key );
1910
1911                    $headerHtml = $this->getHeaderHtml( $key );
1912                    $footerHtml = $this->getFooterHtml( $key );
1913                    $section = $headerHtml .
1914                        $section .
1915                        $footerHtml;
1916
1917                    $attributes = [];
1918                    if ( $fieldsetIDPrefix ) {
1919                        $attributes['id'] = Sanitizer::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1920                    }
1921                    $subsectionHtml .= $this->wrapFieldSetSection(
1922                        $legend, $section, $attributes, $fields === $this->mFieldTree
1923                    );
1924                } else {
1925                    // Just return the inputs, nothing fancy.
1926                    $subsectionHtml .= $section;
1927                }
1928            }
1929        }
1930
1931        $html = $this->formatSection( $html, $sectionName, $hasLabel );
1932
1933        if ( $subsectionHtml ) {
1934            if ( $this->mSubSectionBeforeFields ) {
1935                return $subsectionHtml . "\n" . $html;
1936            } else {
1937                return $html . "\n" . $subsectionHtml;
1938            }
1939        } else {
1940            return $html;
1941        }
1942    }
1943
1944    /**
1945     * Generate the HTML for an individual field in the current display format.
1946     * @since 1.41
1947     * @stable to override
1948     * @param HTMLFormField $field
1949     * @param mixed $value
1950     * @return string|Stringable HTML
1951     */
1952    protected function formatField( HTMLFormField $field, $value ) {
1953        $displayFormat = $this->getDisplayFormat();
1954        switch ( $displayFormat ) {
1955            case 'table':
1956                return $field->getTableRow( $value );
1957            case 'div':
1958                return $field->getDiv( $value );
1959            case 'raw':
1960                return $field->getRaw( $value );
1961            case 'inline':
1962                return $field->getInline( $value );
1963            default:
1964                throw new LogicException( 'Not implemented' );
1965        }
1966    }
1967
1968    /**
1969     * Put a form section together from the individual fields' HTML, merging it and wrapping.
1970     * @stable to override
1971     * @param array $fieldsHtml Array of outputs from formatField()
1972     * @param string $sectionName
1973     * @param bool $anyFieldHasLabel
1974     * @return string HTML
1975     */
1976    protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1977        if ( !$fieldsHtml ) {
1978            // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1979            // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1980            return '';
1981        }
1982
1983        $displayFormat = $this->getDisplayFormat();
1984        $html = implode( '', $fieldsHtml );
1985
1986        if ( $displayFormat === 'raw' ) {
1987            return $html;
1988        }
1989
1990        // Avoid strange spacing when no labels exist
1991        $attribs = $anyFieldHasLabel ? [] : [ 'class' => 'mw-htmlform-nolabel' ];
1992
1993        if ( $sectionName ) {
1994            $attribs['id'] = Sanitizer::escapeIdForAttribute( $sectionName );
1995        }
1996
1997        if ( $displayFormat === 'table' ) {
1998            return Html::rawElement( 'table',
1999                    $attribs,
2000                    Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
2001        } elseif ( $displayFormat === 'inline' ) {
2002            return Html::rawElement( 'span', $attribs, "\n$html\n" );
2003        } else {
2004            return Html::rawElement( 'div', $attribs, "\n$html\n" );
2005        }
2006    }
2007
2008    /**
2009     * @deprecated since 1.39, Use prepareForm() instead.
2010     */
2011    public function loadData() {
2012        $this->prepareForm();
2013    }
2014
2015    /**
2016     * Load data of form fields from the request
2017     */
2018    protected function loadFieldData() {
2019        $fieldData = [];
2020        $request = $this->getRequest();
2021
2022        foreach ( $this->mFlatFields as $fieldname => $field ) {
2023            if ( $field->skipLoadData( $request ) ) {
2024                continue;
2025            }
2026            if ( $field->mParams['disabled'] ?? false ) {
2027                $fieldData[$fieldname] = $field->getDefault();
2028            } else {
2029                $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
2030            }
2031        }
2032
2033        // Reset to default for fields that are supposed to be disabled.
2034        // FIXME: Handle dependency chains, fields that a field checks on may need a reset too.
2035        foreach ( $fieldData as $name => &$value ) {
2036            $field = $this->mFlatFields[$name];
2037            if ( $field->isDisabled( $fieldData ) ) {
2038                $value = $field->getDefault();
2039            }
2040        }
2041
2042        # Filter data.
2043        foreach ( $fieldData as $name => &$value ) {
2044            $field = $this->mFlatFields[$name];
2045            $value = $field->filter( $value, $fieldData );
2046        }
2047
2048        $this->mFieldData = $fieldData;
2049    }
2050
2051    /**
2052     * Overload this if you want to apply special filtration routines
2053     * to the form as a whole, after it's submitted but before it's
2054     * processed.
2055     * @stable to override
2056     *
2057     * @param array $data
2058     *
2059     * @return array
2060     */
2061    public function filterDataForSubmit( $data ) {
2062        return $data;
2063    }
2064
2065    /**
2066     * Get a string to go in the "<legend>" of a section fieldset.
2067     * Override this if you want something more complicated.
2068     * @stable to override
2069     *
2070     * @param string $key
2071     *
2072     * @return string Plain text (not HTML-escaped)
2073     */
2074    public function getLegend( $key ) {
2075        return $this->msg( $this->mMessagePrefix ? "{$this->mMessagePrefix}-$key" : $key )->text();
2076    }
2077
2078    /**
2079     * Set the value for the action attribute of the form.
2080     * When set to false (which is the default state), the set title is used.
2081     *
2082     * @since 1.19
2083     *
2084     * @param string|bool $action
2085     *
2086     * @return HTMLForm $this for chaining calls (since 1.20)
2087     */
2088    public function setAction( $action ) {
2089        $this->mAction = $action;
2090
2091        return $this;
2092    }
2093
2094    /**
2095     * Get the value for the action attribute of the form.
2096     *
2097     * @since 1.22
2098     *
2099     * @return string
2100     */
2101    public function getAction() {
2102        // If an action is already provided, return it
2103        if ( $this->mAction !== false ) {
2104            return $this->mAction;
2105        }
2106
2107        $articlePath = $this->getConfig()->get( MainConfigNames::ArticlePath );
2108        // Check whether we are in GET mode and the ArticlePath contains a "?"
2109        // meaning that getLocalURL() would return something like "index.php?title=...".
2110        // As browser remove the query string before submitting GET forms,
2111        // it means that the title would be lost. In such case use script path instead
2112        // and put title in a hidden field (see getHiddenFields()).
2113        if ( str_contains( $articlePath, '?' ) && $this->getMethod() === 'get' ) {
2114            return $this->getConfig()->get( MainConfigNames::Script );
2115        }
2116
2117        return $this->getTitle()->getLocalURL();
2118    }
2119
2120    /**
2121     * Set the value for the autocomplete attribute of the form. A typical value is "off".
2122     * When set to null (which is the default state), the attribute get not set.
2123     *
2124     * @since 1.27
2125     *
2126     * @param string|null $autocomplete
2127     *
2128     * @return HTMLForm $this for chaining calls
2129     */
2130    public function setAutocomplete( $autocomplete ) {
2131        $this->mAutocomplete = $autocomplete;
2132
2133        return $this;
2134    }
2135
2136    /**
2137     * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
2138     * name + parameters array) into a Message.
2139     * @param mixed $value
2140     * @return Message
2141     */
2142    protected function getMessage( $value ) {
2143        return Message::newFromSpecifier( $value )->setContext( $this );
2144    }
2145
2146    /**
2147     * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
2148     * for the client-side HTML5 form validation to work correctly. If this function returns true, a
2149     * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
2150     * agent has JavaScript support, in htmlform.js.
2151     *
2152     * @return bool
2153     * @since 1.29
2154     */
2155    public function needsJSForHtml5FormValidation() {
2156        foreach ( $this->mFlatFields as $field ) {
2157            if ( $field->needsJSForHtml5FormValidation() ) {
2158                return true;
2159            }
2160        }
2161        return false;
2162    }
2163}
2164
2165/** @deprecated class alias since 1.42 */
2166class_alias( HTMLForm::class, 'HTMLForm' );