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