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