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