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