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