27use InvalidArgumentException;
32use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
210 use ProtectedHookAccessorTrait;
214 'api' => HTMLApiField::class,
215 'text' => HTMLTextField::class,
216 'textwithbutton' => HTMLTextFieldWithButton::class,
217 'textarea' => HTMLTextAreaField::class,
218 'select' => HTMLSelectField::class,
219 'combobox' => HTMLComboboxField::class,
220 'radio' => HTMLRadioField::class,
221 'multiselect' => HTMLMultiSelectField::class,
222 'limitselect' => HTMLSelectLimitField::class,
223 'check' => HTMLCheckField::class,
224 'toggle' => HTMLCheckField::class,
225 'int' => HTMLIntField::class,
226 'file' => HTMLFileField::class,
227 'float' => HTMLFloatField::class,
228 'info' => HTMLInfoField::class,
229 'selectorother' => HTMLSelectOrOtherField::class,
230 'selectandother' => HTMLSelectAndOtherField::class,
231 'namespaceselect' => HTMLSelectNamespace::class,
232 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
233 'tagfilter' => HTMLTagFilter::class,
234 'sizefilter' => HTMLSizeFilterField::class,
235 'submit' => HTMLSubmitField::class,
236 'hidden' => HTMLHiddenField::class,
237 'edittools' => HTMLEditTools::class,
238 'checkmatrix' => HTMLCheckMatrix::class,
239 'cloner' => HTMLFormFieldCloner::class,
240 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
241 'language' => HTMLSelectLanguageField::class,
242 'date' => HTMLDateTimeField::class,
243 'time' => HTMLDateTimeField::class,
244 'datetime' => HTMLDateTimeField::class,
245 'expiry' => HTMLExpiryField::class,
246 'timezone' => HTMLTimezoneField::class,
250 'email' => HTMLTextField::class,
251 'password' => HTMLTextField::class,
252 'url' => HTMLTextField::class,
253 'title' => HTMLTitleTextField::class,
254 'user' => HTMLUserTextField::class,
255 'tagmultiselect' => HTMLTagMultiselectField::class,
256 'usersmultiselect' => HTMLUsersMultiselectField::class,
257 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
258 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
436 private $hiddenTitleAddedToForm =
false;
456 return new CodexHTMLForm( $descriptor, $context, $messagePrefix );
458 return new VFormHTMLForm( $descriptor, $context, $messagePrefix );
460 return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
462 $form =
new self( $descriptor, $context, $messagePrefix );
483 $this->mMessagePrefix = $messagePrefix;
497 $loadedDescriptor = [];
499 foreach ( $descriptor as $fieldname => $info ) {
500 $section = $info[
'section'] ??
'';
502 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
503 $this->mUseMultipart =
true;
506 $field = static::loadInputFromParameters( $fieldname, $info, $this );
508 $setSection =& $loadedDescriptor;
510 foreach ( explode(
'/', $section ) as $newName ) {
511 $setSection[$newName] ??= [];
512 $setSection =& $setSection[$newName];
516 $setSection[$fieldname] = $field;
517 $this->mFlatFields[$fieldname] = $field;
520 $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
530 return isset( $this->mFlatFields[$fieldname] );
539 if ( !$this->
hasField( $fieldname ) ) {
540 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
542 return $this->mFlatFields[$fieldname];
556 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
557 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
559 throw new LogicException(
'Cannot change display format after creation, ' .
560 'use HTMLForm::factory() instead' );
563 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
564 throw new InvalidArgumentException(
'Display format must be one of ' .
567 $this->availableDisplayFormats,
568 $this->availableSubclassDisplayFormats
574 $this->displayFormat = $format;
605 if ( isset( $descriptor[
'class'] ) ) {
606 $class = $descriptor[
'class'];
607 } elseif ( isset( $descriptor[
'type'] ) ) {
608 $class = static::$typeMappings[$descriptor[
'type']];
609 $descriptor[
'class'] = $class;
615 throw new InvalidArgumentException(
"Descriptor with no class for $fieldname: "
616 . print_r( $descriptor,
true ) );
637 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
639 $descriptor[
'fieldname'] = $fieldname;
641 $descriptor[
'parent'] = $parent;
644 # @todo This will throw a fatal error whenever someone try to use
645 # 'class' to feed a CSS class instead of 'cssclass'. Would be
646 # great to avoid the fatal error and show a nice error.
647 return new $class( $descriptor );
659 # Load data from the request.
661 $this->mFormIdentifier ===
null ||
662 $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier ||
663 ( $this->mSingleForm && $this->
getMethod() ===
'get' )
667 $this->mFieldData = [];
680 if ( $this->mFormIdentifier ===
null ) {
689 } elseif ( $this->
getRequest()->wasPosted() ) {
690 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
691 if ( $this->
getUser()->isRegistered() || $editToken !==
null ) {
695 $tokenOkay = $this->
getUser()->matchEditToken( $editToken, $this->mTokenSalt );
701 if ( $tokenOkay && $identOkay ) {
702 $this->mWasSubmitted =
true;
720 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
757 $hoistedErrors = Status::newGood();
758 if ( $this->mValidationErrorMessage ) {
759 foreach ( $this->mValidationErrorMessage as $error ) {
760 $hoistedErrors->fatal( ...$error );
763 $hoistedErrors->fatal(
'htmlform-invalid-input' );
766 $this->mWasSubmitted =
true;
768 # Check for cancelled submission
769 foreach ( $this->mFlatFields as $fieldname => $field ) {
770 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
773 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
774 $this->mWasSubmitted =
false;
779 # Check for validation
780 $hasNonDefault =
false;
781 foreach ( $this->mFlatFields as $fieldname => $field ) {
782 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
785 $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
786 if ( $field->isDisabled( $this->mFieldData ) ) {
789 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
790 if ( $res !==
true ) {
792 if ( $res !==
false && !$field->canDisplayErrors() ) {
793 if ( is_string( $res ) ) {
794 $hoistedErrors->fatal(
'rawmessage', $res );
796 $hoistedErrors->fatal( $res );
804 if ( !$hasNonDefault && $this->
getMethod() ===
'get' &&
805 ( $this->mFormIdentifier ===
null ||
806 $this->
getRequest()->getCheck(
'wpFormIdentifier' ) )
808 $this->mWasSubmitted =
false;
811 return $hoistedErrors;
815 if ( !is_callable( $callback ) ) {
816 throw new LogicException(
'HTMLForm: no submit callback provided. Use ' .
817 'setSubmitCallback() to set one.' );
822 $res = call_user_func( $callback, $data, $this );
823 if ( $res ===
false ) {
824 $this->mWasSubmitted =
false;
827 $res = Status::wrap( $res );
859 $this->mSubmitCallback = $cb;
874 $this->mValidationErrorMessage = $msg;
915 $this->mPre .= $html;
978 if ( $section ===
null ) {
979 $this->mHeader .= $html;
981 $this->mSectionHeaders[$section] ??=
'';
982 $this->mSectionHeaders[$section] .= $html;
998 if ( $section ===
null ) {
999 $this->mHeader = $html;
1001 $this->mSectionHeaders[$section] = $html;
1016 return $section ? $this->mSectionHeaders[$section] ??
'' :
$this->mHeader;
1072 if ( $section ===
null ) {
1073 $this->mFooter .= $html;
1075 $this->mSectionFooters[$section] ??=
'';
1076 $this->mSectionFooters[$section] .= $html;
1092 if ( $section ===
null ) {
1093 $this->mFooter = $html;
1095 $this->mSectionFooters[$section] = $html;
1109 return $section ? $this->mSectionFooters[$section] ??
'' :
$this->mFooter;
1163 $this->mPost .= $html;
1177 $this->mPost = $html;
1229 throw new \InvalidArgumentException(
1230 "Non-Codex HTMLForms do not support additional section information."
1234 $this->mSections = $sections;
1250 if ( !is_array( $value ) ) {
1252 $attribs += [
'name' => $name ];
1253 $this->mHiddenFields[] = [ $value, $attribs ];
1271 foreach ( $fields as $name => $value ) {
1272 if ( is_array( $value ) ) {
1276 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1306 if ( !is_array( $data ) ) {
1307 $args = func_get_args();
1308 if ( count( $args ) < 2 || count( $args ) > 4 ) {
1309 throw new InvalidArgumentException(
1310 'Incorrect number of arguments for deprecated calling style'
1315 'value' => $args[1],
1316 'id' => $args[2] ??
null,
1317 'attribs' => $args[3] ??
null,
1320 if ( !isset( $data[
'name'] ) ) {
1321 throw new InvalidArgumentException(
'A name is required' );
1323 if ( !isset( $data[
'value'] ) ) {
1324 throw new InvalidArgumentException(
'A value is required' );
1327 $this->mButtons[] = $data + [
1347 $this->mTokenSalt = $salt;
1374 private function getHiddenTitle(): string {
1375 if ( $this->hiddenTitleAddedToForm ) {
1383 $html .= Html::hidden(
'title', $this->
getTitle()->getPrefixedText() ) .
"\n";
1385 $this->hiddenTitleAddedToForm =
true;
1400 # For good measure (it is the default)
1401 $this->getOutput()->getMetadata()->setPreventClickjacking(
true );
1402 $this->getOutput()->addModules(
'mediawiki.htmlform' );
1403 $this->getOutput()->addModuleStyles(
'mediawiki.htmlform.styles' );
1405 if ( $this->mCollapsible ) {
1407 $this->getOutput()->addModules(
'jquery.makeCollapsible' );
1410 $headerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getHeaderText',
'1.38' )
1411 ? $this->getHeaderText()
1412 : $this->getHeaderHtml();
1413 $footerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getFooterText',
'1.38' )
1414 ? $this->getFooterText()
1415 : $this->getFooterHtml();
1416 $html = $this->getErrorsOrWarnings( $submitResult,
'error' )
1417 . $this->getErrorsOrWarnings( $submitResult,
'warning' )
1419 . $this->getHiddenTitle()
1421 . $this->getHiddenFields()
1422 . $this->getButtons()
1425 return $this->mPre . $this->wrapForm( $html ) . $this->mPost;
1436 $this->mCollapsible =
true;
1437 $this->mCollapsed = $collapsedByDefault;
1447 # Use multipart/form-data
1448 $encType = $this->mUseMultipart
1449 ?
'multipart/form-data'
1450 :
'application/x-www-form-urlencoded';
1453 'class' =>
'mw-htmlform',
1454 'action' => $this->getAction(),
1455 'method' => $this->getMethod(),
1456 'enctype' => $encType,
1459 $attribs[
'id'] = $this->mId;
1461 if ( is_string( $this->mAutocomplete ) ) {
1462 $attribs[
'autocomplete'] = $this->mAutocomplete;
1464 if ( $this->mName ) {
1465 $attribs[
'name'] = $this->mName;
1467 if ( $this->needsJSForHtml5FormValidation() ) {
1468 $attribs[
'novalidate'] =
true;
1481 # Include a <fieldset> wrapper for style, if requested.
1482 if ( $this->mWrapperLegend !==
false ) {
1483 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1484 $html = Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1487 return Html::rawElement(
1489 $this->getFormAttributes(),
1503 $html .= $this->getHiddenTitle();
1505 if ( $this->mFormIdentifier !==
null ) {
1506 $html .= Html::hidden(
1508 $this->mFormIdentifier
1511 if ( $this->getMethod() ===
'post' ) {
1512 $html .= Html::hidden(
1514 $this->getUser()->getEditToken( $this->mTokenSalt ),
1515 [
'id' =>
'wpEditToken' ]
1519 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1520 $html .= Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1534 if ( $this->mShowSubmit ) {
1537 if ( isset( $this->mSubmitID ) ) {
1538 $attribs[
'id'] = $this->mSubmitID;
1541 if ( isset( $this->mSubmitName ) ) {
1542 $attribs[
'name'] = $this->mSubmitName;
1545 if ( isset( $this->mSubmitTooltip ) ) {
1546 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1549 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1554 if ( $this->mShowCancel ) {
1555 $target = $this->getCancelTargetURL();
1561 $this->msg(
'cancel' )->text()
1565 foreach ( $this->mButtons as $button ) {
1568 'name' => $button[
'name'],
1569 'value' => $button[
'value']
1572 if ( isset( $button[
'label-message'] ) ) {
1573 $label = $this->getMessage( $button[
'label-message'] )->parse();
1574 } elseif ( isset( $button[
'label'] ) ) {
1575 $label = htmlspecialchars( $button[
'label'] );
1576 } elseif ( isset( $button[
'label-raw'] ) ) {
1577 $label = $button[
'label-raw'];
1579 $label = htmlspecialchars( $button[
'value'] );
1583 if ( $button[
'attribs'] ) {
1585 $attrs += $button[
'attribs'];
1588 if ( isset( $button[
'id'] ) ) {
1589 $attrs[
'id'] = $button[
'id'];
1592 $buttons .= Html::rawElement(
'button', $attrs, $label ) .
"\n";
1599 return Html::rawElement(
'span',
1600 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1609 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1622 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1623 throw new DomainException( $elementsType .
' is not a valid type.' );
1625 $elementstr =
false;
1626 if ( $elements instanceof
Status ) {
1627 [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1628 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1629 if ( $status->isGood() ) {
1632 $elementstr = $status
1634 ->setContext( $this )
1635 ->setInterfaceMessageFlag(
true )
1638 } elseif ( $elementsType ===
'error' ) {
1639 if ( is_array( $elements ) ) {
1640 $elementstr = $this->formatErrors( $elements );
1641 } elseif ( $elements && $elements !==
true ) {
1642 $elementstr = (string)$elements;
1646 if ( !$elementstr ) {
1648 } elseif ( $elementsType ===
'error' ) {
1649 return Html::errorBox( $elementstr );
1651 return Html::warningBox( $elementstr );
1665 foreach ( $errors as $error ) {
1666 $errorstr .= Html::rawElement(
1669 $this->getMessage( $error )->parse()
1673 return Html::rawElement(
'ul', [], $errorstr );
1684 $this->mSubmitText = $t;
1696 $this->mSubmitFlags = [
'destructive',
'primary' ];
1710 if ( !$msg instanceof
Message ) {
1711 $msg = $this->msg( $msg );
1713 $this->setSubmitText( $msg->text() );
1723 return $this->mSubmitText ?: $this->msg(
'htmlform-submit' )->text();
1732 $this->mSubmitName = $name;
1743 $this->mSubmitTooltip = $name;
1757 $this->mSubmitID = $t;
1781 $this->mFormIdentifier = $ident;
1782 $this->mSingleForm = $single;
1798 $this->mShowSubmit = !$suppressSubmit;
1810 $this->mShowCancel = $show;
1822 $target = TitleValue::castPageToLinkTarget( $target );
1825 $this->mCancelTarget = $target;
1834 if ( is_string( $this->mCancelTarget ) ) {
1835 return $this->mCancelTarget;
1838 $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1839 return $target->getLocalURL();
1853 $this->mTableId = $id;
1874 $this->mName = $name;
1891 $this->mWrapperLegend = $legend;
1904 $this->mWrapperAttributes = $attributes;
1919 if ( !$msg instanceof
Message ) {
1920 $msg = $this->msg( $msg );
1922 $this->setWrapperLegend( $msg->text() );
1937 $this->mMessagePrefix = $p;
1951 $this->mTitle = Title::castFromPageReference( $t );
1960 return $this->mTitle ?: $this->getContext()->getTitle();
1971 $this->mMethod = strtolower( $method );
1980 return $this->mMethod;
1994 return Xml::fieldset( $legend, $section, $attributes ) .
"\n";
2017 $fieldsetIDPrefix =
'',
2018 &$hasUserVisibleFields =
false
2020 if ( $this->mFieldData ===
null ) {
2021 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
2022 .
'You probably called displayForm() without calling prepareForm() first.' );
2026 $subsectionHtml =
'';
2029 foreach ( $fields as $key => $value ) {
2031 $v = array_key_exists( $key, $this->mFieldData )
2032 ? $this->mFieldData[$key]
2033 : $value->getDefault();
2035 $retval = $this->formatField( $value, $v ??
'' );
2039 if ( $value->hasVisibleOutput() ) {
2042 $labelValue = trim( $value->getLabel() );
2043 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
2047 $hasUserVisibleFields =
true;
2049 } elseif ( is_array( $value ) ) {
2050 $subsectionHasVisibleFields =
false;
2052 $this->displaySection( $value,
2054 "$fieldsetIDPrefix$key-",
2055 $subsectionHasVisibleFields );
2057 if ( $subsectionHasVisibleFields ===
true ) {
2059 $hasUserVisibleFields =
true;
2061 $legend = $this->getLegend( $key );
2063 $headerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getHeaderText',
'1.38' )
2064 ? $this->getHeaderText( $key )
2065 : $this->getHeaderHtml( $key );
2066 $footerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getFooterText',
'1.38' )
2067 ? $this->getFooterText( $key )
2068 : $this->getFooterHtml( $key );
2069 $section = $headerHtml .
2074 if ( $fieldsetIDPrefix ) {
2075 $attributes[
'id'] = Sanitizer::escapeIdForAttribute(
"$fieldsetIDPrefix$key" );
2077 $subsectionHtml .= $this->wrapFieldSetSection(
2078 $legend, $section, $attributes, $fields === $this->mFieldTree
2082 $subsectionHtml .= $section;
2087 $html = $this->formatSection( $html, $sectionName, $hasLabel );
2089 if ( $subsectionHtml ) {
2090 if ( $this->mSubSectionBeforeFields ) {
2091 return $subsectionHtml .
"\n" . $html;
2093 return $html .
"\n" . $subsectionHtml;
2109 $displayFormat = $this->getDisplayFormat();
2110 switch ( $displayFormat ) {
2114 return $field->
getDiv( $value );
2116 return $field->
getRaw( $value );
2120 throw new LogicException(
'Not implemented' );
2132 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
2133 if ( !$fieldsHtml ) {
2139 $displayFormat = $this->getDisplayFormat();
2140 $html = implode(
'', $fieldsHtml );
2142 if ( $displayFormat ===
'raw' ) {
2147 $attribs = $anyFieldHasLabel ? [] : [
'class' =>
'mw-htmlform-nolabel' ];
2149 if ( $sectionName ) {
2150 $attribs[
'id'] = Sanitizer::escapeIdForAttribute( $sectionName );
2153 if ( $displayFormat ===
'table' ) {
2154 return Html::rawElement(
'table',
2156 Html::rawElement(
'tbody', [],
"\n$html\n" ) ) .
"\n";
2157 } elseif ( $displayFormat ===
'inline' ) {
2158 return Html::rawElement(
'span', $attribs,
"\n$html\n" );
2160 return Html::rawElement(
'div', $attribs,
"\n$html\n" );
2168 $this->prepareForm();
2176 $request = $this->getRequest();
2178 foreach ( $this->mFlatFields as $fieldname => $field ) {
2179 if ( $field->skipLoadData( $request ) ) {
2182 if ( $field->mParams[
'disabled'] ??
false ) {
2183 $fieldData[$fieldname] = $field->getDefault();
2185 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
2191 foreach ( $fieldData as $name => &$value ) {
2192 $field = $this->mFlatFields[$name];
2193 if ( $field->isDisabled( $fieldData ) ) {
2194 $value = $field->getDefault();
2199 foreach ( $fieldData as $name => &$value ) {
2200 $field = $this->mFlatFields[$name];
2201 $value = $field->filter( $value, $fieldData );
2204 $this->mFieldData = $fieldData;
2231 return $this->msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
2245 $this->mAction = $action;
2259 if ( $this->mAction !==
false ) {
2260 return $this->mAction;
2269 if ( str_contains( $articlePath,
'?' ) && $this->getMethod() ===
'get' ) {
2273 return $this->
getTitle()->getLocalURL();
2287 $this->mAutocomplete = $autocomplete;
2312 foreach ( $this->mFlatFields as $field ) {
2313 if ( $field->needsJSForHtml5FormValidation() ) {
2322class_alias( HTMLForm::class,
'HTMLForm' );
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined('MW_SETUP_CALLBACK'))
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
setContext(IContextSource $context)
Creates a text input field with a button assigned to the input field.
Implements a text input field for page titles.
Implements a text input field for user names.
A class containing constants representing the names of configuration variables.
const ArticlePath
Name constant for the ArticlePath setting, for use with Config::get()
const Script
Name constant for the Script setting, for use with Config::get()
Generic operation result class Has warning/error list, boolean status and arbitrary value.
isGood()
Returns whether the operation completed and didn't have any error or warnings.
Interface for objects which can provide a MediaWiki context on request.