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