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