rdbms: Avoid selectDB() call in LoadMonitor new connections
[mediawiki.git] / includes / htmlform / HTMLForm.php
blob7293b99e383a84693299ff8dbe8a81c4748e645c
1 <?php
3 /**
4 * HTML form generation and submission handling.
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.
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.
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
21 * @file
24 /**
25 * Object handling generic submission, CSRF protection, layout and
26 * other logic for UI forms. in a reusable manner.
28 * In order to generate the form, the HTMLForm object takes an array
29 * structure detailing the form fields available. Each element of the
30 * array is a basic property-list, including the type of field, the
31 * label it is to be given in the form, callbacks for validation and
32 * 'filtering', and other pertinent information.
34 * Field types are implemented as subclasses of the generic HTMLFormField
35 * object, and typically implement at least getInputHTML, which generates
36 * the HTML for the input field to be placed in the table.
38 * You can find extensive documentation on the www.mediawiki.org wiki:
39 * - https://www.mediawiki.org/wiki/HTMLForm
40 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
42 * The constructor input is an associative array of $fieldname => $info,
43 * where $info is an Associative Array with any of the following:
45 * 'class' -- the subclass of HTMLFormField that will be used
46 * to create the object. *NOT* the CSS class!
47 * 'type' -- roughly translates into the <select> type attribute.
48 * if 'class' is not specified, this is used as a map
49 * through HTMLForm::$typeMappings to get the class name.
50 * 'default' -- default value when the form is displayed
51 * 'id' -- HTML id attribute
52 * 'cssclass' -- CSS class
53 * 'csshelpclass' -- CSS class used to style help text
54 * 'dir' -- Direction of the element.
55 * 'options' -- associative array mapping labels to values.
56 * Some field types support multi-level arrays.
57 * 'options-messages' -- associative array mapping message keys to values.
58 * Some field types support multi-level arrays.
59 * 'options-message' -- message key or object to be parsed to extract the list of
60 * options (like 'ipbreason-dropdown').
61 * 'label-message' -- message key or object for a message to use as the label.
62 * can be an array of msg key and then parameters to
63 * the message.
64 * 'label' -- alternatively, a raw text message. Overridden by
65 * label-message
66 * 'help' -- message text for a message to use as a help text.
67 * 'help-message' -- message key or object for a message to use as a help text.
68 * can be an array of msg key and then parameters to
69 * the message.
70 * Overwrites 'help-messages' and 'help'.
71 * 'help-messages' -- array of message keys/objects. As above, each item can
72 * be an array of msg key and then parameters.
73 * Overwrites 'help'.
74 * 'notice' -- message text for a message to use as a notice in the field.
75 * Currently used by OOUI form fields only.
76 * 'notice-messages' -- array of message keys/objects to use for notice.
77 * Overrides 'notice'.
78 * 'notice-message' -- message key or object to use as a notice.
79 * 'required' -- passed through to the object, indicating that it
80 * is a required field.
81 * 'size' -- the length of text fields
82 * 'filter-callback' -- a function name to give you the chance to
83 * massage the inputted value before it's processed.
84 * @see HTMLFormField::filter()
85 * 'validation-callback' -- a function name to give you the chance
86 * to impose extra validation on the field input.
87 * @see HTMLFormField::validate()
88 * 'name' -- By default, the 'name' attribute of the input field
89 * is "wp{$fieldname}". If you want a different name
90 * (eg one without the "wp" prefix), specify it here and
91 * it will be used without modification.
92 * 'hide-if' -- expression given as an array stating when the field
93 * should be hidden. The first array value has to be the
94 * expression's logic operator. Supported expressions:
95 * 'NOT'
96 * [ 'NOT', array $expression ]
97 * To hide a field if a given expression is not true.
98 * '==='
99 * [ '===', string $fieldName, string $value ]
100 * To hide a field if another field identified by
101 * $field has the value $value.
102 * '!=='
103 * [ '!==', string $fieldName, string $value ]
104 * Same as [ 'NOT', [ '===', $fieldName, $value ]
105 * 'OR', 'AND', 'NOR', 'NAND'
106 * [ 'XXX', array $expression1, ..., array $expressionN ]
107 * To hide a field if one or more (OR), all (AND),
108 * neither (NOR) or not all (NAND) given expressions
109 * are evaluated as true.
110 * The expressions will be given to a JavaScript frontend
111 * module which will continually update the field's
112 * visibility.
114 * Since 1.20, you can chain mutators to ease the form generation:
115 * @par Example:
116 * @code
117 * $form = new HTMLForm( $someFields );
118 * $form->setMethod( 'get' )
119 * ->setWrapperLegendMsg( 'message-key' )
120 * ->prepareForm()
121 * ->displayForm( '' );
122 * @endcode
123 * Note that you will have prepareForm and displayForm at the end. Other
124 * methods call done after that would simply not be part of the form :(
126 * @todo Document 'section' / 'subsection' stuff
128 class HTMLForm extends ContextSource {
129 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
130 public static $typeMappings = [
131 'api' => 'HTMLApiField',
132 'text' => 'HTMLTextField',
133 'textwithbutton' => 'HTMLTextFieldWithButton',
134 'textarea' => 'HTMLTextAreaField',
135 'select' => 'HTMLSelectField',
136 'combobox' => 'HTMLComboboxField',
137 'radio' => 'HTMLRadioField',
138 'multiselect' => 'HTMLMultiSelectField',
139 'limitselect' => 'HTMLSelectLimitField',
140 'check' => 'HTMLCheckField',
141 'toggle' => 'HTMLCheckField',
142 'int' => 'HTMLIntField',
143 'float' => 'HTMLFloatField',
144 'info' => 'HTMLInfoField',
145 'selectorother' => 'HTMLSelectOrOtherField',
146 'selectandother' => 'HTMLSelectAndOtherField',
147 'namespaceselect' => 'HTMLSelectNamespace',
148 'namespaceselectwithbutton' => 'HTMLSelectNamespaceWithButton',
149 'tagfilter' => 'HTMLTagFilter',
150 'sizefilter' => 'HTMLSizeFilterField',
151 'submit' => 'HTMLSubmitField',
152 'hidden' => 'HTMLHiddenField',
153 'edittools' => 'HTMLEditTools',
154 'checkmatrix' => 'HTMLCheckMatrix',
155 'cloner' => 'HTMLFormFieldCloner',
156 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
157 'date' => 'HTMLDateTimeField',
158 'time' => 'HTMLDateTimeField',
159 'datetime' => 'HTMLDateTimeField',
160 // HTMLTextField will output the correct type="" attribute automagically.
161 // There are about four zillion other HTML5 input types, like range, but
162 // we don't use those at the moment, so no point in adding all of them.
163 'email' => 'HTMLTextField',
164 'password' => 'HTMLTextField',
165 'url' => 'HTMLTextField',
166 'title' => 'HTMLTitleTextField',
167 'user' => 'HTMLUserTextField',
168 'usersmultiselect' => 'HTMLUsersMultiselectField',
171 public $mFieldData;
173 protected $mMessagePrefix;
175 /** @var HTMLFormField[] */
176 protected $mFlatFields;
178 protected $mFieldTree;
179 protected $mShowReset = false;
180 protected $mShowSubmit = true;
181 protected $mSubmitFlags = [ 'primary', 'progressive' ];
182 protected $mShowCancel = false;
183 protected $mCancelTarget;
185 protected $mSubmitCallback;
186 protected $mValidationErrorMessage;
188 protected $mPre = '';
189 protected $mHeader = '';
190 protected $mFooter = '';
191 protected $mSectionHeaders = [];
192 protected $mSectionFooters = [];
193 protected $mPost = '';
194 protected $mId;
195 protected $mName;
196 protected $mTableId = '';
198 protected $mSubmitID;
199 protected $mSubmitName;
200 protected $mSubmitText;
201 protected $mSubmitTooltip;
203 protected $mFormIdentifier;
204 protected $mTitle;
205 protected $mMethod = 'post';
206 protected $mWasSubmitted = false;
209 * Form action URL. false means we will use the URL to set Title
210 * @since 1.19
211 * @var bool|string
213 protected $mAction = false;
216 * Form attribute autocomplete. false does not set the attribute
217 * @since 1.27
218 * @var bool|string
220 protected $mAutocomplete = false;
222 protected $mUseMultipart = false;
223 protected $mHiddenFields = [];
224 protected $mButtons = [];
226 protected $mWrapperLegend = false;
229 * Salt for the edit token.
230 * @var string|array
232 protected $mTokenSalt = '';
235 * If true, sections that contain both fields and subsections will
236 * render their subsections before their fields.
238 * Subclasses may set this to false to render subsections after fields
239 * instead.
241 protected $mSubSectionBeforeFields = true;
244 * Format in which to display form. For viable options,
245 * @see $availableDisplayFormats
246 * @var string
248 protected $displayFormat = 'table';
251 * Available formats in which to display the form
252 * @var array
254 protected $availableDisplayFormats = [
255 'table',
256 'div',
257 'raw',
258 'inline',
262 * Available formats in which to display the form
263 * @var array
265 protected $availableSubclassDisplayFormats = [
266 'vform',
267 'ooui',
271 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
273 * @param string $displayFormat
274 * @param mixed $arguments,... Additional arguments to pass to the constructor.
275 * @return HTMLForm
277 public static function factory( $displayFormat/*, $arguments...*/ ) {
278 $arguments = func_get_args();
279 array_shift( $arguments );
281 switch ( $displayFormat ) {
282 case 'vform':
283 return ObjectFactory::constructClassInstance( VFormHTMLForm::class, $arguments );
284 case 'ooui':
285 return ObjectFactory::constructClassInstance( OOUIHTMLForm::class, $arguments );
286 default:
287 /** @var HTMLForm $form */
288 $form = ObjectFactory::constructClassInstance( self::class, $arguments );
289 $form->setDisplayFormat( $displayFormat );
290 return $form;
295 * Build a new HTMLForm from an array of field attributes
297 * @param array $descriptor Array of Field constructs, as described above
298 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
299 * Obviates the need to call $form->setTitle()
300 * @param string $messagePrefix A prefix to go in front of default messages
302 public function __construct( $descriptor, /*IContextSource*/ $context = null,
303 $messagePrefix = ''
305 if ( $context instanceof IContextSource ) {
306 $this->setContext( $context );
307 $this->mTitle = false; // We don't need them to set a title
308 $this->mMessagePrefix = $messagePrefix;
309 } elseif ( $context === null && $messagePrefix !== '' ) {
310 $this->mMessagePrefix = $messagePrefix;
311 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
312 // B/C since 1.18
313 // it's actually $messagePrefix
314 $this->mMessagePrefix = $context;
317 // Evil hack for mobile :(
318 if (
319 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
320 && $this->displayFormat === 'table'
322 $this->displayFormat = 'div';
325 // Expand out into a tree.
326 $loadedDescriptor = [];
327 $this->mFlatFields = [];
329 foreach ( $descriptor as $fieldname => $info ) {
330 $section = isset( $info['section'] )
331 ? $info['section']
332 : '';
334 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
335 $this->mUseMultipart = true;
338 $field = static::loadInputFromParameters( $fieldname, $info, $this );
340 $setSection =& $loadedDescriptor;
341 if ( $section ) {
342 $sectionParts = explode( '/', $section );
344 while ( count( $sectionParts ) ) {
345 $newName = array_shift( $sectionParts );
347 if ( !isset( $setSection[$newName] ) ) {
348 $setSection[$newName] = [];
351 $setSection =& $setSection[$newName];
355 $setSection[$fieldname] = $field;
356 $this->mFlatFields[$fieldname] = $field;
359 $this->mFieldTree = $loadedDescriptor;
363 * @param string $fieldname
364 * @return bool
366 public function hasField( $fieldname ) {
367 return isset( $this->mFlatFields[$fieldname] );
371 * @param string $fieldname
372 * @return HTMLFormField
373 * @throws DomainException on invalid field name
375 public function getField( $fieldname ) {
376 if ( !$this->hasField( $fieldname ) ) {
377 throw new DomainException( __METHOD__ . ': no field named ' . $fieldname );
379 return $this->mFlatFields[$fieldname];
383 * Set format in which to display the form
385 * @param string $format The name of the format to use, must be one of
386 * $this->availableDisplayFormats
388 * @throws MWException
389 * @since 1.20
390 * @return HTMLForm $this for chaining calls (since 1.20)
392 public function setDisplayFormat( $format ) {
393 if (
394 in_array( $format, $this->availableSubclassDisplayFormats, true ) ||
395 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats, true )
397 throw new MWException( 'Cannot change display format after creation, ' .
398 'use HTMLForm::factory() instead' );
401 if ( !in_array( $format, $this->availableDisplayFormats, true ) ) {
402 throw new MWException( 'Display format must be one of ' .
403 print_r(
404 array_merge(
405 $this->availableDisplayFormats,
406 $this->availableSubclassDisplayFormats
408 true
409 ) );
412 // Evil hack for mobile :(
413 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
414 $format = 'div';
417 $this->displayFormat = $format;
419 return $this;
423 * Getter for displayFormat
424 * @since 1.20
425 * @return string
427 public function getDisplayFormat() {
428 return $this->displayFormat;
432 * Test if displayFormat is 'vform'
433 * @since 1.22
434 * @deprecated since 1.25
435 * @return bool
437 public function isVForm() {
438 wfDeprecated( __METHOD__, '1.25' );
439 return false;
443 * Get the HTMLFormField subclass for this descriptor.
445 * The descriptor can be passed either 'class' which is the name of
446 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
447 * This makes sure the 'class' is always set, and also is returned by
448 * this function for ease.
450 * @since 1.23
452 * @param string $fieldname Name of the field
453 * @param array &$descriptor Input Descriptor, as described above
455 * @throws MWException
456 * @return string Name of a HTMLFormField subclass
458 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
459 if ( isset( $descriptor['class'] ) ) {
460 $class = $descriptor['class'];
461 } elseif ( isset( $descriptor['type'] ) ) {
462 $class = static::$typeMappings[$descriptor['type']];
463 $descriptor['class'] = $class;
464 } else {
465 $class = null;
468 if ( !$class ) {
469 throw new MWException( "Descriptor with no class for $fieldname: "
470 . print_r( $descriptor, true ) );
473 return $class;
477 * Initialise a new Object for the field
479 * @param string $fieldname Name of the field
480 * @param array $descriptor Input Descriptor, as described above
481 * @param HTMLForm|null $parent Parent instance of HTMLForm
483 * @throws MWException
484 * @return HTMLFormField Instance of a subclass of HTMLFormField
486 public static function loadInputFromParameters( $fieldname, $descriptor,
487 HTMLForm $parent = null
489 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
491 $descriptor['fieldname'] = $fieldname;
492 if ( $parent ) {
493 $descriptor['parent'] = $parent;
496 # @todo This will throw a fatal error whenever someone try to use
497 # 'class' to feed a CSS class instead of 'cssclass'. Would be
498 # great to avoid the fatal error and show a nice error.
499 return new $class( $descriptor );
503 * Prepare form for submission.
505 * @attention When doing method chaining, that should be the very last
506 * method call before displayForm().
508 * @throws MWException
509 * @return HTMLForm $this for chaining calls (since 1.20)
511 public function prepareForm() {
512 # Check if we have the info we need
513 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
514 throw new MWException( 'You must call setTitle() on an HTMLForm' );
517 # Load data from the request.
518 if (
519 $this->mFormIdentifier === null ||
520 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
522 $this->loadData();
523 } else {
524 $this->mFieldData = [];
527 return $this;
531 * Try submitting, with edit token check first
532 * @return Status|bool
534 public function tryAuthorizedSubmit() {
535 $result = false;
537 $identOkay = false;
538 if ( $this->mFormIdentifier === null ) {
539 $identOkay = true;
540 } else {
541 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier;
544 $tokenOkay = false;
545 if ( $this->getMethod() !== 'post' ) {
546 $tokenOkay = true; // no session check needed
547 } elseif ( $this->getRequest()->wasPosted() ) {
548 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
549 if ( $this->getUser()->isLoggedIn() || $editToken !== null ) {
550 // Session tokens for logged-out users have no security value.
551 // However, if the user gave one, check it in order to give a nice
552 // "session expired" error instead of "permission denied" or such.
553 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
554 } else {
555 $tokenOkay = true;
559 if ( $tokenOkay && $identOkay ) {
560 $this->mWasSubmitted = true;
561 $result = $this->trySubmit();
564 return $result;
568 * The here's-one-I-made-earlier option: do the submission if
569 * posted, or display the form with or without funky validation
570 * errors
571 * @return bool|Status Whether submission was successful.
573 public function show() {
574 $this->prepareForm();
576 $result = $this->tryAuthorizedSubmit();
577 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
578 return $result;
581 $this->displayForm( $result );
583 return false;
587 * Same as self::show with the difference, that the form will be
588 * added to the output, no matter, if the validation was good or not.
589 * @return bool|Status Whether submission was successful.
591 public function showAlways() {
592 $this->prepareForm();
594 $result = $this->tryAuthorizedSubmit();
596 $this->displayForm( $result );
598 return $result;
602 * Validate all the fields, and call the submission callback
603 * function if everything is kosher.
604 * @throws MWException
605 * @return bool|string|array|Status
606 * - Bool true or a good Status object indicates success,
607 * - Bool false indicates no submission was attempted,
608 * - Anything else indicates failure. The value may be a fatal Status
609 * object, an HTML string, or an array of arrays (message keys and
610 * params) or strings (message keys)
612 public function trySubmit() {
613 $valid = true;
614 $hoistedErrors = Status::newGood();
615 if ( $this->mValidationErrorMessage ) {
616 foreach ( (array)$this->mValidationErrorMessage as $error ) {
617 call_user_func_array( [ $hoistedErrors, 'fatal' ], $error );
619 } else {
620 $hoistedErrors->fatal( 'htmlform-invalid-input' );
623 $this->mWasSubmitted = true;
625 # Check for cancelled submission
626 foreach ( $this->mFlatFields as $fieldname => $field ) {
627 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
628 continue;
630 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
631 $this->mWasSubmitted = false;
632 return false;
636 # Check for validation
637 foreach ( $this->mFlatFields as $fieldname => $field ) {
638 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
639 continue;
641 if ( $field->isHidden( $this->mFieldData ) ) {
642 continue;
644 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
645 if ( $res !== true ) {
646 $valid = false;
647 if ( $res !== false && !$field->canDisplayErrors() ) {
648 if ( is_string( $res ) ) {
649 $hoistedErrors->fatal( 'rawmessage', $res );
650 } else {
651 $hoistedErrors->fatal( $res );
657 if ( !$valid ) {
658 return $hoistedErrors;
661 $callback = $this->mSubmitCallback;
662 if ( !is_callable( $callback ) ) {
663 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
664 'setSubmitCallback() to set one.' );
667 $data = $this->filterDataForSubmit( $this->mFieldData );
669 $res = call_user_func( $callback, $data, $this );
670 if ( $res === false ) {
671 $this->mWasSubmitted = false;
674 return $res;
678 * Test whether the form was considered to have been submitted or not, i.e.
679 * whether the last call to tryAuthorizedSubmit or trySubmit returned
680 * non-false.
682 * This will return false until HTMLForm::tryAuthorizedSubmit or
683 * HTMLForm::trySubmit is called.
685 * @since 1.23
686 * @return bool
688 public function wasSubmitted() {
689 return $this->mWasSubmitted;
693 * Set a callback to a function to do something with the form
694 * once it's been successfully validated.
696 * @param callable $cb The function will be passed the output from
697 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
698 * return as documented for HTMLForm::trySubmit
700 * @return HTMLForm $this for chaining calls (since 1.20)
702 public function setSubmitCallback( $cb ) {
703 $this->mSubmitCallback = $cb;
705 return $this;
709 * Set a message to display on a validation error.
711 * @param string|array $msg String or Array of valid inputs to wfMessage()
712 * (so each entry can be either a String or Array)
714 * @return HTMLForm $this for chaining calls (since 1.20)
716 public function setValidationErrorMessage( $msg ) {
717 $this->mValidationErrorMessage = $msg;
719 return $this;
723 * Set the introductory message, overwriting any existing message.
725 * @param string $msg Complete text of message to display
727 * @return HTMLForm $this for chaining calls (since 1.20)
729 public function setIntro( $msg ) {
730 $this->setPreText( $msg );
732 return $this;
736 * Set the introductory message HTML, overwriting any existing message.
737 * @since 1.19
739 * @param string $msg Complete HTML of message to display
741 * @return HTMLForm $this for chaining calls (since 1.20)
743 public function setPreText( $msg ) {
744 $this->mPre = $msg;
746 return $this;
750 * Add HTML to introductory message.
752 * @param string $msg Complete HTML of message to display
754 * @return HTMLForm $this for chaining calls (since 1.20)
756 public function addPreText( $msg ) {
757 $this->mPre .= $msg;
759 return $this;
763 * Add HTML to the header, inside the form.
765 * @param string $msg Additional HTML to display in header
766 * @param string|null $section The section to add the header to
768 * @return HTMLForm $this for chaining calls (since 1.20)
770 public function addHeaderText( $msg, $section = null ) {
771 if ( $section === null ) {
772 $this->mHeader .= $msg;
773 } else {
774 if ( !isset( $this->mSectionHeaders[$section] ) ) {
775 $this->mSectionHeaders[$section] = '';
777 $this->mSectionHeaders[$section] .= $msg;
780 return $this;
784 * Set header text, inside the form.
785 * @since 1.19
787 * @param string $msg Complete HTML of header to display
788 * @param string|null $section The section to add the header to
790 * @return HTMLForm $this for chaining calls (since 1.20)
792 public function setHeaderText( $msg, $section = null ) {
793 if ( $section === null ) {
794 $this->mHeader = $msg;
795 } else {
796 $this->mSectionHeaders[$section] = $msg;
799 return $this;
803 * Get header text.
805 * @param string|null $section The section to get the header text for
806 * @since 1.26
807 * @return string HTML
809 public function getHeaderText( $section = null ) {
810 if ( $section === null ) {
811 return $this->mHeader;
812 } else {
813 return isset( $this->mSectionHeaders[$section] ) ? $this->mSectionHeaders[$section] : '';
818 * Add footer text, inside the form.
820 * @param string $msg Complete text of message to display
821 * @param string|null $section The section to add the footer text to
823 * @return HTMLForm $this for chaining calls (since 1.20)
825 public function addFooterText( $msg, $section = null ) {
826 if ( $section === null ) {
827 $this->mFooter .= $msg;
828 } else {
829 if ( !isset( $this->mSectionFooters[$section] ) ) {
830 $this->mSectionFooters[$section] = '';
832 $this->mSectionFooters[$section] .= $msg;
835 return $this;
839 * Set footer text, inside the form.
840 * @since 1.19
842 * @param string $msg Complete text of message to display
843 * @param string|null $section The section to add the footer text to
845 * @return HTMLForm $this for chaining calls (since 1.20)
847 public function setFooterText( $msg, $section = null ) {
848 if ( $section === null ) {
849 $this->mFooter = $msg;
850 } else {
851 $this->mSectionFooters[$section] = $msg;
854 return $this;
858 * Get footer text.
860 * @param string|null $section The section to get the footer text for
861 * @since 1.26
862 * @return string
864 public function getFooterText( $section = null ) {
865 if ( $section === null ) {
866 return $this->mFooter;
867 } else {
868 return isset( $this->mSectionFooters[$section] ) ? $this->mSectionFooters[$section] : '';
873 * Add text to the end of the display.
875 * @param string $msg Complete text of message to display
877 * @return HTMLForm $this for chaining calls (since 1.20)
879 public function addPostText( $msg ) {
880 $this->mPost .= $msg;
882 return $this;
886 * Set text at the end of the display.
888 * @param string $msg Complete text of message to display
890 * @return HTMLForm $this for chaining calls (since 1.20)
892 public function setPostText( $msg ) {
893 $this->mPost = $msg;
895 return $this;
899 * Add a hidden field to the output
901 * @param string $name Field name. This will be used exactly as entered
902 * @param string $value Field value
903 * @param array $attribs
905 * @return HTMLForm $this for chaining calls (since 1.20)
907 public function addHiddenField( $name, $value, array $attribs = [] ) {
908 $attribs += [ 'name' => $name ];
909 $this->mHiddenFields[] = [ $value, $attribs ];
911 return $this;
915 * Add an array of hidden fields to the output
917 * @since 1.22
919 * @param array $fields Associative array of fields to add;
920 * mapping names to their values
922 * @return HTMLForm $this for chaining calls
924 public function addHiddenFields( array $fields ) {
925 foreach ( $fields as $name => $value ) {
926 $this->mHiddenFields[] = [ $value, [ 'name' => $name ] ];
929 return $this;
933 * Add a button to the form
935 * @since 1.27 takes an array as shown. Earlier versions accepted
936 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
937 * order.
938 * @note Custom labels ('label', 'label-message', 'label-raw') are not
939 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
940 * they will be served buttons using 'value' as the button label.
941 * @param array $data Data to define the button:
942 * - name: (string) Button name.
943 * - value: (string) Button value.
944 * - label-message: (string, optional) Button label message key to use
945 * instead of 'value'. Overrides 'label' and 'label-raw'.
946 * - label: (string, optional) Button label text to use instead of
947 * 'value'. Overrides 'label-raw'.
948 * - label-raw: (string, optional) Button label HTML to use instead of
949 * 'value'.
950 * - id: (string, optional) DOM id for the button.
951 * - attribs: (array, optional) Additional HTML attributes.
952 * - flags: (string|string[], optional) OOUI flags.
953 * - framed: (boolean=true, optional) OOUI framed attribute.
954 * @return HTMLForm $this for chaining calls (since 1.20)
956 public function addButton( $data ) {
957 if ( !is_array( $data ) ) {
958 $args = func_get_args();
959 if ( count( $args ) < 2 || count( $args ) > 4 ) {
960 throw new InvalidArgumentException(
961 'Incorrect number of arguments for deprecated calling style'
964 $data = [
965 'name' => $args[0],
966 'value' => $args[1],
967 'id' => isset( $args[2] ) ? $args[2] : null,
968 'attribs' => isset( $args[3] ) ? $args[3] : null,
970 } else {
971 if ( !isset( $data['name'] ) ) {
972 throw new InvalidArgumentException( 'A name is required' );
974 if ( !isset( $data['value'] ) ) {
975 throw new InvalidArgumentException( 'A value is required' );
978 $this->mButtons[] = $data + [
979 'id' => null,
980 'attribs' => null,
981 'flags' => null,
982 'framed' => true,
985 return $this;
989 * Set the salt for the edit token.
991 * Only useful when the method is "post".
993 * @since 1.24
994 * @param string|array $salt Salt to use
995 * @return HTMLForm $this For chaining calls
997 public function setTokenSalt( $salt ) {
998 $this->mTokenSalt = $salt;
1000 return $this;
1004 * Display the form (sending to the context's OutputPage object), with an
1005 * appropriate error message or stack of messages, and any validation errors, etc.
1007 * @attention You should call prepareForm() before calling this function.
1008 * Moreover, when doing method chaining this should be the very last method
1009 * call just after prepareForm().
1011 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1013 * @return void Nothing, should be last call
1015 public function displayForm( $submitResult ) {
1016 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1020 * Returns the raw HTML generated by the form
1022 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1024 * @return string HTML
1026 public function getHTML( $submitResult ) {
1027 # For good measure (it is the default)
1028 $this->getOutput()->preventClickjacking();
1029 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1030 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1032 $html = ''
1033 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1034 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1035 . $this->getHeaderText()
1036 . $this->getBody()
1037 . $this->getHiddenFields()
1038 . $this->getButtons()
1039 . $this->getFooterText();
1041 $html = $this->wrapForm( $html );
1043 return '' . $this->mPre . $html . $this->mPost;
1047 * Get HTML attributes for the `<form>` tag.
1048 * @return array
1050 protected function getFormAttributes() {
1051 # Use multipart/form-data
1052 $encType = $this->mUseMultipart
1053 ? 'multipart/form-data'
1054 : 'application/x-www-form-urlencoded';
1055 # Attributes
1056 $attribs = [
1057 'class' => 'mw-htmlform',
1058 'action' => $this->getAction(),
1059 'method' => $this->getMethod(),
1060 'enctype' => $encType,
1062 if ( $this->mId ) {
1063 $attribs['id'] = $this->mId;
1065 if ( $this->mAutocomplete ) {
1066 $attribs['autocomplete'] = $this->mAutocomplete;
1068 if ( $this->mName ) {
1069 $attribs['name'] = $this->mName;
1071 if ( $this->needsJSForHtml5FormValidation() ) {
1072 $attribs['novalidate'] = true;
1074 return $attribs;
1078 * Wrap the form innards in an actual "<form>" element
1080 * @param string $html HTML contents to wrap.
1082 * @return string Wrapped HTML.
1084 public function wrapForm( $html ) {
1085 # Include a <fieldset> wrapper for style, if requested.
1086 if ( $this->mWrapperLegend !== false ) {
1087 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend : false;
1088 $html = Xml::fieldset( $legend, $html );
1091 return Html::rawElement(
1092 'form',
1093 $this->getFormAttributes(),
1094 $html
1099 * Get the hidden fields that should go inside the form.
1100 * @return string HTML.
1102 public function getHiddenFields() {
1103 $html = '';
1104 if ( $this->mFormIdentifier !== null ) {
1105 $html .= Html::hidden(
1106 'wpFormIdentifier',
1107 $this->mFormIdentifier
1108 ) . "\n";
1110 if ( $this->getMethod() === 'post' ) {
1111 $html .= Html::hidden(
1112 'wpEditToken',
1113 $this->getUser()->getEditToken( $this->mTokenSalt ),
1114 [ 'id' => 'wpEditToken' ]
1115 ) . "\n";
1116 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1119 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1120 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1121 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1124 foreach ( $this->mHiddenFields as $data ) {
1125 list( $value, $attribs ) = $data;
1126 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
1129 return $html;
1133 * Get the submit and (potentially) reset buttons.
1134 * @return string HTML.
1136 public function getButtons() {
1137 $buttons = '';
1138 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1140 if ( $this->mShowSubmit ) {
1141 $attribs = [];
1143 if ( isset( $this->mSubmitID ) ) {
1144 $attribs['id'] = $this->mSubmitID;
1147 if ( isset( $this->mSubmitName ) ) {
1148 $attribs['name'] = $this->mSubmitName;
1151 if ( isset( $this->mSubmitTooltip ) ) {
1152 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1155 $attribs['class'] = [ 'mw-htmlform-submit' ];
1157 if ( $useMediaWikiUIEverywhere ) {
1158 foreach ( $this->mSubmitFlags as $flag ) {
1159 $attribs['class'][] = 'mw-ui-' . $flag;
1161 $attribs['class'][] = 'mw-ui-button';
1164 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1167 if ( $this->mShowReset ) {
1168 $buttons .= Html::element(
1169 'input',
1171 'type' => 'reset',
1172 'value' => $this->msg( 'htmlform-reset' )->text(),
1173 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1175 ) . "\n";
1178 if ( $this->mShowCancel ) {
1179 $target = $this->mCancelTarget ?: Title::newMainPage();
1180 if ( $target instanceof Title ) {
1181 $target = $target->getLocalURL();
1183 $buttons .= Html::element(
1184 'a',
1186 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1187 'href' => $target,
1189 $this->msg( 'cancel' )->text()
1190 ) . "\n";
1193 // IE<8 has bugs with <button>, so we'll need to avoid them.
1194 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1196 foreach ( $this->mButtons as $button ) {
1197 $attrs = [
1198 'type' => 'submit',
1199 'name' => $button['name'],
1200 'value' => $button['value']
1203 if ( isset( $button['label-message'] ) ) {
1204 $label = $this->getMessage( $button['label-message'] )->parse();
1205 } elseif ( isset( $button['label'] ) ) {
1206 $label = htmlspecialchars( $button['label'] );
1207 } elseif ( isset( $button['label-raw'] ) ) {
1208 $label = $button['label-raw'];
1209 } else {
1210 $label = htmlspecialchars( $button['value'] );
1213 if ( $button['attribs'] ) {
1214 $attrs += $button['attribs'];
1217 if ( isset( $button['id'] ) ) {
1218 $attrs['id'] = $button['id'];
1221 if ( $useMediaWikiUIEverywhere ) {
1222 $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : [];
1223 $attrs['class'][] = 'mw-ui-button';
1226 if ( $isBadIE ) {
1227 $buttons .= Html::element( 'input', $attrs ) . "\n";
1228 } else {
1229 $buttons .= Html::rawElement( 'button', $attrs, $label ) . "\n";
1233 if ( !$buttons ) {
1234 return '';
1237 return Html::rawElement( 'span',
1238 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1242 * Get the whole body of the form.
1243 * @return string
1245 public function getBody() {
1246 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1250 * Format and display an error message stack.
1252 * @param string|array|Status $errors
1254 * @deprecated since 1.28, use getErrorsOrWarnings() instead
1256 * @return string
1258 public function getErrors( $errors ) {
1259 wfDeprecated( __METHOD__ );
1260 return $this->getErrorsOrWarnings( $errors, 'error' );
1264 * Returns a formatted list of errors or warnings from the given elements.
1266 * @param string|array|Status $elements The set of errors/warnings to process.
1267 * @param string $elementsType Should warnings or errors be returned. This is meant
1268 * for Status objects, all other valid types are always considered as errors.
1269 * @return string
1271 public function getErrorsOrWarnings( $elements, $elementsType ) {
1272 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1273 throw new DomainException( $elementsType . ' is not a valid type.' );
1275 $elementstr = false;
1276 if ( $elements instanceof Status ) {
1277 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1278 $status = $elementsType === 'error' ? $errorStatus : $warningStatus;
1279 if ( $status->isGood() ) {
1280 $elementstr = '';
1281 } else {
1282 $elementstr = $this->getOutput()->parse(
1283 $status->getWikiText()
1286 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1287 $elementstr = $this->formatErrors( $elements );
1288 } elseif ( $elementsType === 'error' ) {
1289 $elementstr = $elements;
1292 return $elementstr
1293 ? Html::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1294 : '';
1298 * Format a stack of error messages into a single HTML string
1300 * @param array $errors Array of message keys/values
1302 * @return string HTML, a "<ul>" list of errors
1304 public function formatErrors( $errors ) {
1305 $errorstr = '';
1307 foreach ( $errors as $error ) {
1308 $errorstr .= Html::rawElement(
1309 'li',
1311 $this->getMessage( $error )->parse()
1315 $errorstr = Html::rawElement( 'ul', [], $errorstr );
1317 return $errorstr;
1321 * Set the text for the submit button
1323 * @param string $t Plaintext
1325 * @return HTMLForm $this for chaining calls (since 1.20)
1327 public function setSubmitText( $t ) {
1328 $this->mSubmitText = $t;
1330 return $this;
1334 * Identify that the submit button in the form has a destructive action
1335 * @since 1.24
1337 * @return HTMLForm $this for chaining calls (since 1.28)
1339 public function setSubmitDestructive() {
1340 $this->mSubmitFlags = [ 'destructive', 'primary' ];
1342 return $this;
1346 * Identify that the submit button in the form has a progressive action
1347 * @since 1.25
1349 * @return HTMLForm $this for chaining calls (since 1.28)
1351 public function setSubmitProgressive() {
1352 $this->mSubmitFlags = [ 'progressive', 'primary' ];
1354 return $this;
1358 * Set the text for the submit button to a message
1359 * @since 1.19
1361 * @param string|Message $msg Message key or Message object
1363 * @return HTMLForm $this for chaining calls (since 1.20)
1365 public function setSubmitTextMsg( $msg ) {
1366 if ( !$msg instanceof Message ) {
1367 $msg = $this->msg( $msg );
1369 $this->setSubmitText( $msg->text() );
1371 return $this;
1375 * Get the text for the submit button, either customised or a default.
1376 * @return string
1378 public function getSubmitText() {
1379 return $this->mSubmitText ?: $this->msg( 'htmlform-submit' )->text();
1383 * @param string $name Submit button name
1385 * @return HTMLForm $this for chaining calls (since 1.20)
1387 public function setSubmitName( $name ) {
1388 $this->mSubmitName = $name;
1390 return $this;
1394 * @param string $name Tooltip for the submit button
1396 * @return HTMLForm $this for chaining calls (since 1.20)
1398 public function setSubmitTooltip( $name ) {
1399 $this->mSubmitTooltip = $name;
1401 return $this;
1405 * Set the id for the submit button.
1407 * @param string $t
1409 * @todo FIXME: Integrity of $t is *not* validated
1410 * @return HTMLForm $this for chaining calls (since 1.20)
1412 public function setSubmitID( $t ) {
1413 $this->mSubmitID = $t;
1415 return $this;
1419 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1420 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1421 * two purposes:
1423 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1424 * was submitted, and not attempt to validate the other ones.
1425 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1426 * HTMLForm to distinguish between the initial page view and a form submission with all
1427 * checkboxes or select options unchecked.
1429 * @since 1.28
1430 * @param string $ident
1431 * @return $this
1433 public function setFormIdentifier( $ident ) {
1434 $this->mFormIdentifier = $ident;
1436 return $this;
1440 * Stop a default submit button being shown for this form. This implies that an
1441 * alternate submit method must be provided manually.
1443 * @since 1.22
1445 * @param bool $suppressSubmit Set to false to re-enable the button again
1447 * @return HTMLForm $this for chaining calls
1449 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1450 $this->mShowSubmit = !$suppressSubmit;
1452 return $this;
1456 * Show a cancel button (or prevent it). The button is not shown by default.
1457 * @param bool $show
1458 * @return HTMLForm $this for chaining calls
1459 * @since 1.27
1461 public function showCancel( $show = true ) {
1462 $this->mShowCancel = $show;
1463 return $this;
1467 * Sets the target where the user is redirected to after clicking cancel.
1468 * @param Title|string $target Target as a Title object or an URL
1469 * @return HTMLForm $this for chaining calls
1470 * @since 1.27
1472 public function setCancelTarget( $target ) {
1473 $this->mCancelTarget = $target;
1474 return $this;
1478 * Set the id of the \<table\> or outermost \<div\> element.
1480 * @since 1.22
1482 * @param string $id New value of the id attribute, or "" to remove
1484 * @return HTMLForm $this for chaining calls
1486 public function setTableId( $id ) {
1487 $this->mTableId = $id;
1489 return $this;
1493 * @param string $id DOM id for the form
1495 * @return HTMLForm $this for chaining calls (since 1.20)
1497 public function setId( $id ) {
1498 $this->mId = $id;
1500 return $this;
1504 * @param string $name 'name' attribute for the form
1505 * @return HTMLForm $this for chaining calls
1507 public function setName( $name ) {
1508 $this->mName = $name;
1510 return $this;
1514 * Prompt the whole form to be wrapped in a "<fieldset>", with
1515 * this text as its "<legend>" element.
1517 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1518 * If true, a wrapper will be displayed, but no legend.
1519 * If a string, a wrapper will be displayed with that string as a legend.
1520 * The string will be escaped before being output (this doesn't support HTML).
1522 * @return HTMLForm $this for chaining calls (since 1.20)
1524 public function setWrapperLegend( $legend ) {
1525 $this->mWrapperLegend = $legend;
1527 return $this;
1531 * Prompt the whole form to be wrapped in a "<fieldset>", with
1532 * this message as its "<legend>" element.
1533 * @since 1.19
1535 * @param string|Message $msg Message key or Message object
1537 * @return HTMLForm $this for chaining calls (since 1.20)
1539 public function setWrapperLegendMsg( $msg ) {
1540 if ( !$msg instanceof Message ) {
1541 $msg = $this->msg( $msg );
1543 $this->setWrapperLegend( $msg->text() );
1545 return $this;
1549 * Set the prefix for various default messages
1550 * @todo Currently only used for the "<fieldset>" legend on forms
1551 * with multiple sections; should be used elsewhere?
1553 * @param string $p
1555 * @return HTMLForm $this for chaining calls (since 1.20)
1557 public function setMessagePrefix( $p ) {
1558 $this->mMessagePrefix = $p;
1560 return $this;
1564 * Set the title for form submission
1566 * @param Title $t Title of page the form is on/should be posted to
1568 * @return HTMLForm $this for chaining calls (since 1.20)
1570 public function setTitle( $t ) {
1571 $this->mTitle = $t;
1573 return $this;
1577 * Get the title
1578 * @return Title
1580 public function getTitle() {
1581 return $this->mTitle === false
1582 ? $this->getContext()->getTitle()
1583 : $this->mTitle;
1587 * Set the method used to submit the form
1589 * @param string $method
1591 * @return HTMLForm $this for chaining calls (since 1.20)
1593 public function setMethod( $method = 'post' ) {
1594 $this->mMethod = strtolower( $method );
1596 return $this;
1600 * @return string Always lowercase
1602 public function getMethod() {
1603 return $this->mMethod;
1607 * Wraps the given $section into an user-visible fieldset.
1609 * @param string $legend Legend text for the fieldset
1610 * @param string $section The section content in plain Html
1611 * @param array $attributes Additional attributes for the fieldset
1612 * @return string The fieldset's Html
1614 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1615 return Xml::fieldset( $legend, $section, $attributes ) . "\n";
1619 * @todo Document
1621 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1622 * objects).
1623 * @param string $sectionName ID attribute of the "<table>" tag for this
1624 * section, ignored if empty.
1625 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1626 * each subsection, ignored if empty.
1627 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1628 * @throws LogicException When called on uninitialized field data, e.g. When
1629 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1630 * first.
1632 * @return string
1634 public function displaySection( $fields,
1635 $sectionName = '',
1636 $fieldsetIDPrefix = '',
1637 &$hasUserVisibleFields = false
1639 if ( $this->mFieldData === null ) {
1640 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1641 . 'You probably called displayForm() without calling prepareForm() first.' );
1644 $displayFormat = $this->getDisplayFormat();
1646 $html = [];
1647 $subsectionHtml = '';
1648 $hasLabel = false;
1650 // Conveniently, PHP method names are case-insensitive.
1651 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1652 $getFieldHtmlMethod = $displayFormat === 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1654 foreach ( $fields as $key => $value ) {
1655 if ( $value instanceof HTMLFormField ) {
1656 $v = array_key_exists( $key, $this->mFieldData )
1657 ? $this->mFieldData[$key]
1658 : $value->getDefault();
1660 $retval = $value->$getFieldHtmlMethod( $v );
1662 // check, if the form field should be added to
1663 // the output.
1664 if ( $value->hasVisibleOutput() ) {
1665 $html[] = $retval;
1667 $labelValue = trim( $value->getLabel() );
1668 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
1669 $hasLabel = true;
1672 $hasUserVisibleFields = true;
1674 } elseif ( is_array( $value ) ) {
1675 $subsectionHasVisibleFields = false;
1676 $section =
1677 $this->displaySection( $value,
1678 "mw-htmlform-$key",
1679 "$fieldsetIDPrefix$key-",
1680 $subsectionHasVisibleFields );
1681 $legend = null;
1683 if ( $subsectionHasVisibleFields === true ) {
1684 // Display the section with various niceties.
1685 $hasUserVisibleFields = true;
1687 $legend = $this->getLegend( $key );
1689 $section = $this->getHeaderText( $key ) .
1690 $section .
1691 $this->getFooterText( $key );
1693 $attributes = [];
1694 if ( $fieldsetIDPrefix ) {
1695 $attributes['id'] = Sanitizer::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1697 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1698 } else {
1699 // Just return the inputs, nothing fancy.
1700 $subsectionHtml .= $section;
1705 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1707 if ( $subsectionHtml ) {
1708 if ( $this->mSubSectionBeforeFields ) {
1709 return $subsectionHtml . "\n" . $html;
1710 } else {
1711 return $html . "\n" . $subsectionHtml;
1713 } else {
1714 return $html;
1719 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1720 * @param array $fieldsHtml
1721 * @param string $sectionName
1722 * @param bool $anyFieldHasLabel
1723 * @return string HTML
1725 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1726 $displayFormat = $this->getDisplayFormat();
1727 $html = implode( '', $fieldsHtml );
1729 if ( $displayFormat === 'raw' ) {
1730 return $html;
1733 $classes = [];
1735 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1736 $classes[] = 'mw-htmlform-nolabel';
1739 $attribs = [
1740 'class' => implode( ' ', $classes ),
1743 if ( $sectionName ) {
1744 $attribs['id'] = Sanitizer::escapeIdForAttribute( $sectionName );
1747 if ( $displayFormat === 'table' ) {
1748 return Html::rawElement( 'table',
1749 $attribs,
1750 Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1751 } elseif ( $displayFormat === 'inline' ) {
1752 return Html::rawElement( 'span', $attribs, "\n$html\n" );
1753 } else {
1754 return Html::rawElement( 'div', $attribs, "\n$html\n" );
1759 * Construct the form fields from the Descriptor array
1761 public function loadData() {
1762 $fieldData = [];
1764 foreach ( $this->mFlatFields as $fieldname => $field ) {
1765 $request = $this->getRequest();
1766 if ( $field->skipLoadData( $request ) ) {
1767 continue;
1768 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1769 $fieldData[$fieldname] = $field->getDefault();
1770 } else {
1771 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1775 # Filter data.
1776 foreach ( $fieldData as $name => &$value ) {
1777 $field = $this->mFlatFields[$name];
1778 $value = $field->filter( $value, $this->mFlatFields );
1781 $this->mFieldData = $fieldData;
1785 * Stop a reset button being shown for this form
1787 * @param bool $suppressReset Set to false to re-enable the button again
1789 * @return HTMLForm $this for chaining calls (since 1.20)
1791 public function suppressReset( $suppressReset = true ) {
1792 $this->mShowReset = !$suppressReset;
1794 return $this;
1798 * Overload this if you want to apply special filtration routines
1799 * to the form as a whole, after it's submitted but before it's
1800 * processed.
1802 * @param array $data
1804 * @return array
1806 public function filterDataForSubmit( $data ) {
1807 return $data;
1811 * Get a string to go in the "<legend>" of a section fieldset.
1812 * Override this if you want something more complicated.
1814 * @param string $key
1816 * @return string
1818 public function getLegend( $key ) {
1819 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1823 * Set the value for the action attribute of the form.
1824 * When set to false (which is the default state), the set title is used.
1826 * @since 1.19
1828 * @param string|bool $action
1830 * @return HTMLForm $this for chaining calls (since 1.20)
1832 public function setAction( $action ) {
1833 $this->mAction = $action;
1835 return $this;
1839 * Get the value for the action attribute of the form.
1841 * @since 1.22
1843 * @return string
1845 public function getAction() {
1846 // If an action is alredy provided, return it
1847 if ( $this->mAction !== false ) {
1848 return $this->mAction;
1851 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1852 // Check whether we are in GET mode and the ArticlePath contains a "?"
1853 // meaning that getLocalURL() would return something like "index.php?title=...".
1854 // As browser remove the query string before submitting GET forms,
1855 // it means that the title would be lost. In such case use wfScript() instead
1856 // and put title in an hidden field (see getHiddenFields()).
1857 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1858 return wfScript();
1861 return $this->getTitle()->getLocalURL();
1865 * Set the value for the autocomplete attribute of the form.
1866 * When set to false (which is the default state), the attribute get not set.
1868 * @since 1.27
1870 * @param string|bool $autocomplete
1872 * @return HTMLForm $this for chaining calls
1874 public function setAutocomplete( $autocomplete ) {
1875 $this->mAutocomplete = $autocomplete;
1877 return $this;
1881 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1882 * name + parameters array) into a Message.
1883 * @param mixed $value
1884 * @return Message
1886 protected function getMessage( $value ) {
1887 return Message::newFromSpecifier( $value )->setContext( $this );
1891 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1892 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1893 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1894 * agent has JavaScript support, in htmlform.js.
1896 * @return boolean
1897 * @since 1.29
1899 public function needsJSForHtml5FormValidation() {
1900 foreach ( $this->mFlatFields as $fieldname => $field ) {
1901 if ( $field->needsJSForHtml5FormValidation() ) {
1902 return true;
1905 return false;