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