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