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
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
64 * 'label' -- alternatively, a raw text message. Overridden by
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
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.
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.
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:
96 * [ 'NOT', array $expression ]
97 * To hide a field if a given expression is not true.
99 * [ '===', string $fieldName, string $value ]
100 * To hide a field if another field identified by
101 * $field has the value $value.
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
114 * Since 1.20, you can chain mutators to ease the form generation:
117 * $form = new HTMLForm( $someFields );
118 * $form->setMethod( 'get' )
119 * ->setWrapperLegendMsg( 'message-key' )
121 * ->displayForm( '' );
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 'submit' => 'HTMLSubmitField',
151 'hidden' => 'HTMLHiddenField',
152 'edittools' => 'HTMLEditTools',
153 'checkmatrix' => 'HTMLCheckMatrix',
154 'cloner' => 'HTMLFormFieldCloner',
155 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
156 // HTMLTextField will output the correct type="" attribute automagically.
157 // There are about four zillion other HTML5 input types, like range, but
158 // we don't use those at the moment, so no point in adding all of them.
159 'email' => 'HTMLTextField',
160 'password' => 'HTMLTextField',
161 'url' => 'HTMLTextField',
162 'title' => 'HTMLTitleTextField',
163 'user' => 'HTMLUserTextField',
168 protected $mMessagePrefix;
170 /** @var HTMLFormField[] */
171 protected $mFlatFields;
173 protected $mFieldTree;
174 protected $mShowReset = false;
175 protected $mShowSubmit = true;
176 protected $mSubmitFlags = [ 'constructive', 'primary' ];
177 protected $mShowCancel = false;
178 protected $mCancelTarget;
180 protected $mSubmitCallback;
181 protected $mValidationErrorMessage;
183 protected $mPre = '';
184 protected $mHeader = '';
185 protected $mFooter = '';
186 protected $mSectionHeaders = [];
187 protected $mSectionFooters = [];
188 protected $mPost = '';
191 protected $mTableId = '';
193 protected $mSubmitID;
194 protected $mSubmitName;
195 protected $mSubmitText;
196 protected $mSubmitTooltip;
198 protected $mFormIdentifier;
200 protected $mMethod = 'post';
201 protected $mWasSubmitted = false;
204 * Form action URL. false means we will use the URL to set Title
208 protected $mAction = false;
211 * Form attribute autocomplete. false does not set the attribute
215 protected $mAutocomplete = false;
217 protected $mUseMultipart = false;
218 protected $mHiddenFields = [];
219 protected $mButtons = [];
221 protected $mWrapperLegend = false;
224 * Salt for the edit token.
227 protected $mTokenSalt = '';
230 * If true, sections that contain both fields and subsections will
231 * render their subsections before their fields.
233 * Subclasses may set this to false to render subsections after fields
236 protected $mSubSectionBeforeFields = true;
239 * Format in which to display form. For viable options,
240 * @see $availableDisplayFormats
243 protected $displayFormat = 'table';
246 * Available formats in which to display the form
249 protected $availableDisplayFormats = [
257 * Available formats in which to display the form
260 protected $availableSubclassDisplayFormats = [
266 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
268 * @param string $displayFormat
269 * @param mixed $arguments... Additional arguments to pass to the constructor.
272 public static function factory( $displayFormat/*, $arguments...*/ ) {
273 $arguments = func_get_args();
274 array_shift( $arguments );
276 switch ( $displayFormat ) {
278 return ObjectFactory
::constructClassInstance( VFormHTMLForm
::class, $arguments );
280 return ObjectFactory
::constructClassInstance( OOUIHTMLForm
::class, $arguments );
282 /** @var HTMLForm $form */
283 $form = ObjectFactory
::constructClassInstance( HTMLForm
::class, $arguments );
284 $form->setDisplayFormat( $displayFormat );
290 * Build a new HTMLForm from an array of field attributes
292 * @param array $descriptor Array of Field constructs, as described above
293 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
294 * Obviates the need to call $form->setTitle()
295 * @param string $messagePrefix A prefix to go in front of default messages
297 public function __construct( $descriptor, /*IContextSource*/ $context = null,
300 if ( $context instanceof IContextSource
) {
301 $this->setContext( $context );
302 $this->mTitle
= false; // We don't need them to set a title
303 $this->mMessagePrefix
= $messagePrefix;
304 } elseif ( $context === null && $messagePrefix !== '' ) {
305 $this->mMessagePrefix
= $messagePrefix;
306 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
308 // it's actually $messagePrefix
309 $this->mMessagePrefix
= $context;
312 // Evil hack for mobile :(
314 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
315 && $this->displayFormat
=== 'table'
317 $this->displayFormat
= 'div';
320 // Expand out into a tree.
321 $loadedDescriptor = [];
322 $this->mFlatFields
= [];
324 foreach ( $descriptor as $fieldname => $info ) {
325 $section = isset( $info['section'] )
329 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
330 $this->mUseMultipart
= true;
333 $field = static::loadInputFromParameters( $fieldname, $info, $this );
335 $setSection =& $loadedDescriptor;
337 $sectionParts = explode( '/', $section );
339 while ( count( $sectionParts ) ) {
340 $newName = array_shift( $sectionParts );
342 if ( !isset( $setSection[$newName] ) ) {
343 $setSection[$newName] = [];
346 $setSection =& $setSection[$newName];
350 $setSection[$fieldname] = $field;
351 $this->mFlatFields
[$fieldname] = $field;
354 $this->mFieldTree
= $loadedDescriptor;
358 * Set format in which to display the form
360 * @param string $format The name of the format to use, must be one of
361 * $this->availableDisplayFormats
363 * @throws MWException
365 * @return HTMLForm $this for chaining calls (since 1.20)
367 public function setDisplayFormat( $format ) {
369 in_array( $format, $this->availableSubclassDisplayFormats
, true ) ||
370 in_array( $this->displayFormat
, $this->availableSubclassDisplayFormats
, true )
372 throw new MWException( 'Cannot change display format after creation, ' .
373 'use HTMLForm::factory() instead' );
376 if ( !in_array( $format, $this->availableDisplayFormats
, true ) ) {
377 throw new MWException( 'Display format must be one of ' .
378 print_r( $this->availableDisplayFormats
, true ) );
381 // Evil hack for mobile :(
382 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
386 $this->displayFormat
= $format;
392 * Getter for displayFormat
396 public function getDisplayFormat() {
397 return $this->displayFormat
;
401 * Test if displayFormat is 'vform'
403 * @deprecated since 1.25
406 public function isVForm() {
407 wfDeprecated( __METHOD__
, '1.25' );
412 * Get the HTMLFormField subclass for this descriptor.
414 * The descriptor can be passed either 'class' which is the name of
415 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
416 * This makes sure the 'class' is always set, and also is returned by
417 * this function for ease.
421 * @param string $fieldname Name of the field
422 * @param array $descriptor Input Descriptor, as described above
424 * @throws MWException
425 * @return string Name of a HTMLFormField subclass
427 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
428 if ( isset( $descriptor['class'] ) ) {
429 $class = $descriptor['class'];
430 } elseif ( isset( $descriptor['type'] ) ) {
431 $class = static::$typeMappings[$descriptor['type']];
432 $descriptor['class'] = $class;
438 throw new MWException( "Descriptor with no class for $fieldname: "
439 . print_r( $descriptor, true ) );
446 * Initialise a new Object for the field
448 * @param string $fieldname Name of the field
449 * @param array $descriptor Input Descriptor, as described above
450 * @param HTMLForm|null $parent Parent instance of HTMLForm
452 * @throws MWException
453 * @return HTMLFormField Instance of a subclass of HTMLFormField
455 public static function loadInputFromParameters( $fieldname, $descriptor,
456 HTMLForm
$parent = null
458 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
460 $descriptor['fieldname'] = $fieldname;
462 $descriptor['parent'] = $parent;
465 # @todo This will throw a fatal error whenever someone try to use
466 # 'class' to feed a CSS class instead of 'cssclass'. Would be
467 # great to avoid the fatal error and show a nice error.
468 return new $class( $descriptor );
472 * Prepare form for submission.
474 * @attention When doing method chaining, that should be the very last
475 * method call before displayForm().
477 * @throws MWException
478 * @return HTMLForm $this for chaining calls (since 1.20)
480 public function prepareForm() {
481 # Check if we have the info we need
482 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
483 throw new MWException( 'You must call setTitle() on an HTMLForm' );
486 # Load data from the request.
488 $this->mFormIdentifier
=== null ||
489 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
493 $this->mFieldData
= [];
500 * Try submitting, with edit token check first
501 * @return Status|bool
503 public function tryAuthorizedSubmit() {
507 if ( $this->mFormIdentifier
=== null ) {
510 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
;
514 if ( $this->getMethod() !== 'post' ) {
515 $tokenOkay = true; // no session check needed
516 } elseif ( $this->getRequest()->wasPosted() ) {
517 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
518 if ( $this->getUser()->isLoggedIn() ||
$editToken !== null ) {
519 // Session tokens for logged-out users have no security value.
520 // However, if the user gave one, check it in order to give a nice
521 // "session expired" error instead of "permission denied" or such.
522 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt
);
528 if ( $tokenOkay && $identOkay ) {
529 $this->mWasSubmitted
= true;
530 $result = $this->trySubmit();
537 * The here's-one-I-made-earlier option: do the submission if
538 * posted, or display the form with or without funky validation
540 * @return bool|Status Whether submission was successful.
542 public function show() {
543 $this->prepareForm();
545 $result = $this->tryAuthorizedSubmit();
546 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
550 $this->displayForm( $result );
556 * Same as self::show with the difference, that the form will be
557 * added to the output, no matter, if the validation was good or not.
558 * @return bool|Status Whether submission was successful.
560 public function showAlways() {
561 $this->prepareForm();
563 $result = $this->tryAuthorizedSubmit();
565 $this->displayForm( $result );
571 * Validate all the fields, and call the submission callback
572 * function if everything is kosher.
573 * @throws MWException
574 * @return bool|string|array|Status
575 * - Bool true or a good Status object indicates success,
576 * - Bool false indicates no submission was attempted,
577 * - Anything else indicates failure. The value may be a fatal Status
578 * object, an HTML string, or an array of arrays (message keys and
579 * params) or strings (message keys)
581 public function trySubmit() {
584 $hoistedErrors[] = isset( $this->mValidationErrorMessage
)
585 ?
$this->mValidationErrorMessage
586 : [ 'htmlform-invalid-input' ];
588 $this->mWasSubmitted
= true;
590 # Check for cancelled submission
591 foreach ( $this->mFlatFields
as $fieldname => $field ) {
592 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
595 if ( $field->cancelSubmit( $this->mFieldData
[$fieldname], $this->mFieldData
) ) {
596 $this->mWasSubmitted
= false;
601 # Check for validation
602 foreach ( $this->mFlatFields
as $fieldname => $field ) {
603 if ( !array_key_exists( $fieldname, $this->mFieldData
) ) {
606 if ( $field->isHidden( $this->mFieldData
) ) {
609 $res = $field->validate( $this->mFieldData
[$fieldname], $this->mFieldData
);
610 if ( $res !== true ) {
612 if ( $res !== false && !$field->canDisplayErrors() ) {
613 $hoistedErrors[] = [ 'rawmessage', $res ];
619 if ( count( $hoistedErrors ) === 1 ) {
620 $hoistedErrors = $hoistedErrors[0];
622 return $hoistedErrors;
625 $callback = $this->mSubmitCallback
;
626 if ( !is_callable( $callback ) ) {
627 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
628 'setSubmitCallback() to set one.' );
631 $data = $this->filterDataForSubmit( $this->mFieldData
);
633 $res = call_user_func( $callback, $data, $this );
634 if ( $res === false ) {
635 $this->mWasSubmitted
= false;
642 * Test whether the form was considered to have been submitted or not, i.e.
643 * whether the last call to tryAuthorizedSubmit or trySubmit returned
646 * This will return false until HTMLForm::tryAuthorizedSubmit or
647 * HTMLForm::trySubmit is called.
652 public function wasSubmitted() {
653 return $this->mWasSubmitted
;
657 * Set a callback to a function to do something with the form
658 * once it's been successfully validated.
660 * @param callable $cb The function will be passed the output from
661 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
662 * return as documented for HTMLForm::trySubmit
664 * @return HTMLForm $this for chaining calls (since 1.20)
666 public function setSubmitCallback( $cb ) {
667 $this->mSubmitCallback
= $cb;
673 * Set a message to display on a validation error.
675 * @param string|array $msg String or Array of valid inputs to wfMessage()
676 * (so each entry can be either a String or Array)
678 * @return HTMLForm $this for chaining calls (since 1.20)
680 public function setValidationErrorMessage( $msg ) {
681 $this->mValidationErrorMessage
= $msg;
687 * Set the introductory message, overwriting any existing message.
689 * @param string $msg Complete text of message to display
691 * @return HTMLForm $this for chaining calls (since 1.20)
693 public function setIntro( $msg ) {
694 $this->setPreText( $msg );
700 * Set the introductory message HTML, overwriting any existing message.
703 * @param string $msg Complete HTML of message to display
705 * @return HTMLForm $this for chaining calls (since 1.20)
707 public function setPreText( $msg ) {
714 * Add HTML to introductory message.
716 * @param string $msg Complete HTML of message to display
718 * @return HTMLForm $this for chaining calls (since 1.20)
720 public function addPreText( $msg ) {
727 * Add HTML to the header, inside the form.
729 * @param string $msg Additional HTML to display in header
730 * @param string|null $section The section to add the header to
732 * @return HTMLForm $this for chaining calls (since 1.20)
734 public function addHeaderText( $msg, $section = null ) {
735 if ( $section === null ) {
736 $this->mHeader
.= $msg;
738 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
739 $this->mSectionHeaders
[$section] = '';
741 $this->mSectionHeaders
[$section] .= $msg;
748 * Set header text, inside the form.
751 * @param string $msg Complete HTML of header to display
752 * @param string|null $section The section to add the header to
754 * @return HTMLForm $this for chaining calls (since 1.20)
756 public function setHeaderText( $msg, $section = null ) {
757 if ( $section === null ) {
758 $this->mHeader
= $msg;
760 $this->mSectionHeaders
[$section] = $msg;
769 * @param string|null $section The section to get the header text for
771 * @return string HTML
773 public function getHeaderText( $section = null ) {
774 if ( $section === null ) {
775 return $this->mHeader
;
777 return isset( $this->mSectionHeaders
[$section] ) ?
$this->mSectionHeaders
[$section] : '';
782 * Add footer text, inside the form.
784 * @param string $msg Complete text of message to display
785 * @param string|null $section The section to add the footer text to
787 * @return HTMLForm $this for chaining calls (since 1.20)
789 public function addFooterText( $msg, $section = null ) {
790 if ( $section === null ) {
791 $this->mFooter
.= $msg;
793 if ( !isset( $this->mSectionFooters
[$section] ) ) {
794 $this->mSectionFooters
[$section] = '';
796 $this->mSectionFooters
[$section] .= $msg;
803 * Set footer text, inside the form.
806 * @param string $msg Complete text of message to display
807 * @param string|null $section The section to add the footer text to
809 * @return HTMLForm $this for chaining calls (since 1.20)
811 public function setFooterText( $msg, $section = null ) {
812 if ( $section === null ) {
813 $this->mFooter
= $msg;
815 $this->mSectionFooters
[$section] = $msg;
824 * @param string|null $section The section to get the footer text for
828 public function getFooterText( $section = null ) {
829 if ( $section === null ) {
830 return $this->mFooter
;
832 return isset( $this->mSectionFooters
[$section] ) ?
$this->mSectionFooters
[$section] : '';
837 * Add text to the end of the display.
839 * @param string $msg Complete text of message to display
841 * @return HTMLForm $this for chaining calls (since 1.20)
843 public function addPostText( $msg ) {
844 $this->mPost
.= $msg;
850 * Set text at the end of the display.
852 * @param string $msg Complete text of message to display
854 * @return HTMLForm $this for chaining calls (since 1.20)
856 public function setPostText( $msg ) {
863 * Add a hidden field to the output
865 * @param string $name Field name. This will be used exactly as entered
866 * @param string $value Field value
867 * @param array $attribs
869 * @return HTMLForm $this for chaining calls (since 1.20)
871 public function addHiddenField( $name, $value, array $attribs = [] ) {
872 $attribs +
= [ 'name' => $name ];
873 $this->mHiddenFields
[] = [ $value, $attribs ];
879 * Add an array of hidden fields to the output
883 * @param array $fields Associative array of fields to add;
884 * mapping names to their values
886 * @return HTMLForm $this for chaining calls
888 public function addHiddenFields( array $fields ) {
889 foreach ( $fields as $name => $value ) {
890 $this->mHiddenFields
[] = [ $value, [ 'name' => $name ] ];
897 * Add a button to the form
899 * @since 1.27 takes an array as shown. Earlier versions accepted
900 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
902 * @note Custom labels ('label', 'label-message', 'label-raw') are not
903 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
904 * they will be served buttons using 'value' as the button label.
905 * @param array $data Data to define the button:
906 * - name: (string) Button name.
907 * - value: (string) Button value.
908 * - label-message: (string, optional) Button label message key to use
909 * instead of 'value'. Overrides 'label' and 'label-raw'.
910 * - label: (string, optional) Button label text to use instead of
911 * 'value'. Overrides 'label-raw'.
912 * - label-raw: (string, optional) Button label HTML to use instead of
914 * - id: (string, optional) DOM id for the button.
915 * - attribs: (array, optional) Additional HTML attributes.
916 * - flags: (string|string[], optional) OOUI flags.
917 * - framed: (boolean=true, optional) OOUI framed attribute.
918 * @return HTMLForm $this for chaining calls (since 1.20)
920 public function addButton( $data ) {
921 if ( !is_array( $data ) ) {
922 $args = func_get_args();
923 if ( count( $args ) < 2 ||
count( $args ) > 4 ) {
924 throw new InvalidArgumentException(
925 'Incorrect number of arguments for deprecated calling style'
931 'id' => isset( $args[2] ) ?
$args[2] : null,
932 'attribs' => isset( $args[3] ) ?
$args[3] : null,
935 if ( !isset( $data['name'] ) ) {
936 throw new InvalidArgumentException( 'A name is required' );
938 if ( !isset( $data['value'] ) ) {
939 throw new InvalidArgumentException( 'A value is required' );
942 $this->mButtons
[] = $data +
[
953 * Set the salt for the edit token.
955 * Only useful when the method is "post".
958 * @param string|array $salt Salt to use
959 * @return HTMLForm $this For chaining calls
961 public function setTokenSalt( $salt ) {
962 $this->mTokenSalt
= $salt;
968 * Display the form (sending to the context's OutputPage object), with an
969 * appropriate error message or stack of messages, and any validation errors, etc.
971 * @attention You should call prepareForm() before calling this function.
972 * Moreover, when doing method chaining this should be the very last method
973 * call just after prepareForm().
975 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
977 * @return void Nothing, should be last call
979 public function displayForm( $submitResult ) {
980 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
984 * Returns the raw HTML generated by the form
986 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
988 * @return string HTML
990 public function getHTML( $submitResult ) {
991 # For good measure (it is the default)
992 $this->getOutput()->preventClickjacking();
993 $this->getOutput()->addModules( 'mediawiki.htmlform' );
994 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
997 . $this->getErrors( $submitResult )
998 . $this->getHeaderText()
1000 . $this->getHiddenFields()
1001 . $this->getButtons()
1002 . $this->getFooterText();
1004 $html = $this->wrapForm( $html );
1006 return '' . $this->mPre
. $html . $this->mPost
;
1010 * Get HTML attributes for the `<form>` tag.
1013 protected function getFormAttributes() {
1014 # Use multipart/form-data
1015 $encType = $this->mUseMultipart
1016 ?
'multipart/form-data'
1017 : 'application/x-www-form-urlencoded';
1020 'action' => $this->getAction(),
1021 'method' => $this->getMethod(),
1022 'enctype' => $encType,
1025 $attribs['id'] = $this->mId
;
1027 if ( $this->mAutocomplete
) {
1028 $attribs['autocomplete'] = $this->mAutocomplete
;
1030 if ( $this->mName
) {
1031 $attribs['name'] = $this->mName
;
1037 * Wrap the form innards in an actual "<form>" element
1039 * @param string $html HTML contents to wrap.
1041 * @return string Wrapped HTML.
1043 public function wrapForm( $html ) {
1044 # Include a <fieldset> wrapper for style, if requested.
1045 if ( $this->mWrapperLegend
!== false ) {
1046 $legend = is_string( $this->mWrapperLegend
) ?
$this->mWrapperLegend
: false;
1047 $html = Xml
::fieldset( $legend, $html );
1050 return Html
::rawElement(
1052 $this->getFormAttributes() +
[ 'class' => 'visualClear' ],
1058 * Get the hidden fields that should go inside the form.
1059 * @return string HTML.
1061 public function getHiddenFields() {
1063 if ( $this->mFormIdentifier
!== null ) {
1064 $html .= Html
::hidden(
1066 $this->mFormIdentifier
1069 if ( $this->getMethod() === 'post' ) {
1070 $html .= Html
::hidden(
1072 $this->getUser()->getEditToken( $this->mTokenSalt
),
1073 [ 'id' => 'wpEditToken' ]
1075 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1078 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1079 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1080 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1083 foreach ( $this->mHiddenFields
as $data ) {
1084 list( $value, $attribs ) = $data;
1085 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
1092 * Get the submit and (potentially) reset buttons.
1093 * @return string HTML.
1095 public function getButtons() {
1097 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1099 if ( $this->mShowSubmit
) {
1102 if ( isset( $this->mSubmitID
) ) {
1103 $attribs['id'] = $this->mSubmitID
;
1106 if ( isset( $this->mSubmitName
) ) {
1107 $attribs['name'] = $this->mSubmitName
;
1110 if ( isset( $this->mSubmitTooltip
) ) {
1111 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
1114 $attribs['class'] = [ 'mw-htmlform-submit' ];
1116 if ( $useMediaWikiUIEverywhere ) {
1117 foreach ( $this->mSubmitFlags
as $flag ) {
1118 $attribs['class'][] = 'mw-ui-' . $flag;
1120 $attribs['class'][] = 'mw-ui-button';
1123 $buttons .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1126 if ( $this->mShowReset
) {
1127 $buttons .= Html
::element(
1131 'value' => $this->msg( 'htmlform-reset' )->text(),
1132 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1137 if ( $this->mShowCancel
) {
1138 $target = $this->mCancelTarget ?
: Title
::newMainPage();
1139 if ( $target instanceof Title
) {
1140 $target = $target->getLocalURL();
1142 $buttons .= Html
::element(
1145 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' : null,
1148 $this->msg( 'cancel' )->text()
1152 // IE<8 has bugs with <button>, so we'll need to avoid them.
1153 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1155 foreach ( $this->mButtons
as $button ) {
1158 'name' => $button['name'],
1159 'value' => $button['value']
1162 if ( isset( $button['label-message'] ) ) {
1163 $label = $this->getMessage( $button['label-message'] )->parse();
1164 } elseif ( isset( $button['label'] ) ) {
1165 $label = htmlspecialchars( $button['label'] );
1166 } elseif ( isset( $button['label-raw'] ) ) {
1167 $label = $button['label-raw'];
1169 $label = htmlspecialchars( $button['value'] );
1172 if ( $button['attribs'] ) {
1173 $attrs +
= $button['attribs'];
1176 if ( isset( $button['id'] ) ) {
1177 $attrs['id'] = $button['id'];
1180 if ( $useMediaWikiUIEverywhere ) {
1181 $attrs['class'] = isset( $attrs['class'] ) ?
(array)$attrs['class'] : [];
1182 $attrs['class'][] = 'mw-ui-button';
1186 $buttons .= Html
::element( 'input', $attrs ) . "\n";
1188 $buttons .= Html
::rawElement( 'button', $attrs, $label ) . "\n";
1196 return Html
::rawElement( 'span',
1197 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1201 * Get the whole body of the form.
1204 public function getBody() {
1205 return $this->displaySection( $this->mFieldTree
, $this->mTableId
);
1209 * Format and display an error message stack.
1211 * @param string|array|Status $errors
1215 public function getErrors( $errors ) {
1216 if ( $errors instanceof Status
) {
1217 if ( $errors->isOK() ) {
1220 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1222 } elseif ( is_array( $errors ) ) {
1223 $errorstr = $this->formatErrors( $errors );
1225 $errorstr = $errors;
1229 ? Html
::rawElement( 'div', [ 'class' => 'error' ], $errorstr )
1234 * Format a stack of error messages into a single HTML string
1236 * @param array $errors Array of message keys/values
1238 * @return string HTML, a "<ul>" list of errors
1240 public function formatErrors( $errors ) {
1243 foreach ( $errors as $error ) {
1244 $errorstr .= Html
::rawElement(
1247 $this->getMessage( $error )->parse()
1251 $errorstr = Html
::rawElement( 'ul', [], $errorstr );
1257 * Set the text for the submit button
1259 * @param string $t Plaintext
1261 * @return HTMLForm $this for chaining calls (since 1.20)
1263 public function setSubmitText( $t ) {
1264 $this->mSubmitText
= $t;
1270 * Identify that the submit button in the form has a destructive action
1273 * @return HTMLForm $this for chaining calls (since 1.28)
1275 public function setSubmitDestructive() {
1276 $this->mSubmitFlags
= [ 'destructive', 'primary' ];
1282 * Identify that the submit button in the form has a progressive action
1285 * @return HTMLForm $this for chaining calls (since 1.28)
1287 public function setSubmitProgressive() {
1288 $this->mSubmitFlags
= [ 'progressive', 'primary' ];
1294 * Set the text for the submit button to a message
1297 * @param string|Message $msg Message key or Message object
1299 * @return HTMLForm $this for chaining calls (since 1.20)
1301 public function setSubmitTextMsg( $msg ) {
1302 if ( !$msg instanceof Message
) {
1303 $msg = $this->msg( $msg );
1305 $this->setSubmitText( $msg->text() );
1311 * Get the text for the submit button, either customised or a default.
1314 public function getSubmitText() {
1315 return $this->mSubmitText ?
: $this->msg( 'htmlform-submit' )->text();
1319 * @param string $name Submit button name
1321 * @return HTMLForm $this for chaining calls (since 1.20)
1323 public function setSubmitName( $name ) {
1324 $this->mSubmitName
= $name;
1330 * @param string $name Tooltip for the submit button
1332 * @return HTMLForm $this for chaining calls (since 1.20)
1334 public function setSubmitTooltip( $name ) {
1335 $this->mSubmitTooltip
= $name;
1341 * Set the id for the submit button.
1345 * @todo FIXME: Integrity of $t is *not* validated
1346 * @return HTMLForm $this for chaining calls (since 1.20)
1348 public function setSubmitID( $t ) {
1349 $this->mSubmitID
= $t;
1355 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1356 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1359 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1360 * was submitted, and not attempt to validate the other ones.
1361 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1362 * HTMLForm to distinguish between the initial page view and a form submission with all
1363 * checkboxes or select options unchecked.
1366 * @param string $ident
1369 public function setFormIdentifier( $ident ) {
1370 $this->mFormIdentifier
= $ident;
1376 * Stop a default submit button being shown for this form. This implies that an
1377 * alternate submit method must be provided manually.
1381 * @param bool $suppressSubmit Set to false to re-enable the button again
1383 * @return HTMLForm $this for chaining calls
1385 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1386 $this->mShowSubmit
= !$suppressSubmit;
1392 * Show a cancel button (or prevent it). The button is not shown by default.
1394 * @return HTMLForm $this for chaining calls
1397 public function showCancel( $show = true ) {
1398 $this->mShowCancel
= $show;
1403 * Sets the target where the user is redirected to after clicking cancel.
1404 * @param Title|string $target Target as a Title object or an URL
1405 * @return HTMLForm $this for chaining calls
1408 public function setCancelTarget( $target ) {
1409 $this->mCancelTarget
= $target;
1414 * Set the id of the \<table\> or outermost \<div\> element.
1418 * @param string $id New value of the id attribute, or "" to remove
1420 * @return HTMLForm $this for chaining calls
1422 public function setTableId( $id ) {
1423 $this->mTableId
= $id;
1429 * @param string $id DOM id for the form
1431 * @return HTMLForm $this for chaining calls (since 1.20)
1433 public function setId( $id ) {
1440 * @param string $name 'name' attribute for the form
1441 * @return HTMLForm $this for chaining calls
1443 public function setName( $name ) {
1444 $this->mName
= $name;
1450 * Prompt the whole form to be wrapped in a "<fieldset>", with
1451 * this text as its "<legend>" element.
1453 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1454 * If true, a wrapper will be displayed, but no legend.
1455 * If a string, a wrapper will be displayed with that string as a legend.
1456 * The string will be escaped before being output (this doesn't support HTML).
1458 * @return HTMLForm $this for chaining calls (since 1.20)
1460 public function setWrapperLegend( $legend ) {
1461 $this->mWrapperLegend
= $legend;
1467 * Prompt the whole form to be wrapped in a "<fieldset>", with
1468 * this message as its "<legend>" element.
1471 * @param string|Message $msg Message key or Message object
1473 * @return HTMLForm $this for chaining calls (since 1.20)
1475 public function setWrapperLegendMsg( $msg ) {
1476 if ( !$msg instanceof Message
) {
1477 $msg = $this->msg( $msg );
1479 $this->setWrapperLegend( $msg->text() );
1485 * Set the prefix for various default messages
1486 * @todo Currently only used for the "<fieldset>" legend on forms
1487 * with multiple sections; should be used elsewhere?
1491 * @return HTMLForm $this for chaining calls (since 1.20)
1493 public function setMessagePrefix( $p ) {
1494 $this->mMessagePrefix
= $p;
1500 * Set the title for form submission
1502 * @param Title $t Title of page the form is on/should be posted to
1504 * @return HTMLForm $this for chaining calls (since 1.20)
1506 public function setTitle( $t ) {
1516 public function getTitle() {
1517 return $this->mTitle
=== false
1518 ?
$this->getContext()->getTitle()
1523 * Set the method used to submit the form
1525 * @param string $method
1527 * @return HTMLForm $this for chaining calls (since 1.20)
1529 public function setMethod( $method = 'post' ) {
1530 $this->mMethod
= strtolower( $method );
1536 * @return string Always lowercase
1538 public function getMethod() {
1539 return $this->mMethod
;
1543 * Wraps the given $section into an user-visible fieldset.
1545 * @param string $legend Legend text for the fieldset
1546 * @param string $section The section content in plain Html
1547 * @param array $attributes Additional attributes for the fieldset
1548 * @return string The fieldset's Html
1550 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1551 return Xml
::fieldset( $legend, $section, $attributes ) . "\n";
1557 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1559 * @param string $sectionName ID attribute of the "<table>" tag for this
1560 * section, ignored if empty.
1561 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1562 * each subsection, ignored if empty.
1563 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1564 * @throws LogicException When called on uninitialized field data, e.g. When
1565 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1570 public function displaySection( $fields,
1572 $fieldsetIDPrefix = '',
1573 &$hasUserVisibleFields = false
1575 if ( $this->mFieldData
=== null ) {
1576 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1577 . 'You probably called displayForm() without calling prepareForm() first.' );
1580 $displayFormat = $this->getDisplayFormat();
1583 $subsectionHtml = '';
1586 // Conveniently, PHP method names are case-insensitive.
1587 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1588 $getFieldHtmlMethod = $displayFormat === 'table' ?
'getTableRow' : ( 'get' . $displayFormat );
1590 foreach ( $fields as $key => $value ) {
1591 if ( $value instanceof HTMLFormField
) {
1592 $v = array_key_exists( $key, $this->mFieldData
)
1593 ?
$this->mFieldData
[$key]
1594 : $value->getDefault();
1596 $retval = $value->$getFieldHtmlMethod( $v );
1598 // check, if the form field should be added to
1600 if ( $value->hasVisibleOutput() ) {
1603 $labelValue = trim( $value->getLabel() );
1604 if ( $labelValue !== ' ' && $labelValue !== '' ) {
1608 $hasUserVisibleFields = true;
1610 } elseif ( is_array( $value ) ) {
1611 $subsectionHasVisibleFields = false;
1613 $this->displaySection( $value,
1615 "$fieldsetIDPrefix$key-",
1616 $subsectionHasVisibleFields );
1619 if ( $subsectionHasVisibleFields === true ) {
1620 // Display the section with various niceties.
1621 $hasUserVisibleFields = true;
1623 $legend = $this->getLegend( $key );
1625 $section = $this->getHeaderText( $key ) .
1627 $this->getFooterText( $key );
1630 if ( $fieldsetIDPrefix ) {
1631 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
1633 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1635 // Just return the inputs, nothing fancy.
1636 $subsectionHtml .= $section;
1641 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1643 if ( $subsectionHtml ) {
1644 if ( $this->mSubSectionBeforeFields
) {
1645 return $subsectionHtml . "\n" . $html;
1647 return $html . "\n" . $subsectionHtml;
1655 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1656 * @param array $fieldsHtml
1657 * @param string $sectionName
1658 * @param bool $anyFieldHasLabel
1659 * @return string HTML
1661 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1662 $displayFormat = $this->getDisplayFormat();
1663 $html = implode( '', $fieldsHtml );
1665 if ( $displayFormat === 'raw' ) {
1671 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1672 $classes[] = 'mw-htmlform-nolabel';
1676 'class' => implode( ' ', $classes ),
1679 if ( $sectionName ) {
1680 $attribs['id'] = Sanitizer
::escapeId( $sectionName );
1683 if ( $displayFormat === 'table' ) {
1684 return Html
::rawElement( 'table',
1686 Html
::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1687 } elseif ( $displayFormat === 'inline' ) {
1688 return Html
::rawElement( 'span', $attribs, "\n$html\n" );
1690 return Html
::rawElement( 'div', $attribs, "\n$html\n" );
1695 * Construct the form fields from the Descriptor array
1697 public function loadData() {
1700 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1701 $request = $this->getRequest();
1702 if ( $field->skipLoadData( $request ) ) {
1704 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1705 $fieldData[$fieldname] = $field->getDefault();
1707 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1712 foreach ( $fieldData as $name => &$value ) {
1713 $field = $this->mFlatFields
[$name];
1714 $value = $field->filter( $value, $this->mFlatFields
);
1717 $this->mFieldData
= $fieldData;
1721 * Stop a reset button being shown for this form
1723 * @param bool $suppressReset Set to false to re-enable the button again
1725 * @return HTMLForm $this for chaining calls (since 1.20)
1727 public function suppressReset( $suppressReset = true ) {
1728 $this->mShowReset
= !$suppressReset;
1734 * Overload this if you want to apply special filtration routines
1735 * to the form as a whole, after it's submitted but before it's
1738 * @param array $data
1742 public function filterDataForSubmit( $data ) {
1747 * Get a string to go in the "<legend>" of a section fieldset.
1748 * Override this if you want something more complicated.
1750 * @param string $key
1754 public function getLegend( $key ) {
1755 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1759 * Set the value for the action attribute of the form.
1760 * When set to false (which is the default state), the set title is used.
1764 * @param string|bool $action
1766 * @return HTMLForm $this for chaining calls (since 1.20)
1768 public function setAction( $action ) {
1769 $this->mAction
= $action;
1775 * Get the value for the action attribute of the form.
1781 public function getAction() {
1782 // If an action is alredy provided, return it
1783 if ( $this->mAction
!== false ) {
1784 return $this->mAction
;
1787 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1788 // Check whether we are in GET mode and the ArticlePath contains a "?"
1789 // meaning that getLocalURL() would return something like "index.php?title=...".
1790 // As browser remove the query string before submitting GET forms,
1791 // it means that the title would be lost. In such case use wfScript() instead
1792 // and put title in an hidden field (see getHiddenFields()).
1793 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1797 return $this->getTitle()->getLocalURL();
1801 * Set the value for the autocomplete attribute of the form.
1802 * When set to false (which is the default state), the attribute get not set.
1806 * @param string|bool $autocomplete
1808 * @return HTMLForm $this for chaining calls
1810 public function setAutocomplete( $autocomplete ) {
1811 $this->mAutocomplete
= $autocomplete;
1817 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1818 * name + parameters array) into a Message.
1819 * @param mixed $value
1822 protected function getMessage( $value ) {
1823 return Message
::newFromSpecifier( $value )->setContext( $this );