Debian Codegraph @

includes/htmlform/HTMLForm.php

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