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