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;
1373 private function getHiddenTitle(): string {
1374 if ( $this->hiddenTitleAddedToForm ) {
1382 $html .= Html::hidden(
'title', $this->
getTitle()->getPrefixedText() ) .
"\n";
1384 $this->hiddenTitleAddedToForm =
true;
1399 # For good measure (it is the default)
1400 $this->getOutput()->getMetadata()->setPreventClickjacking(
true );
1401 $this->getOutput()->addModules(
'mediawiki.htmlform' );
1402 $this->getOutput()->addModuleStyles(
'mediawiki.htmlform.styles' );
1404 if ( $this->mCollapsible ) {
1406 $this->getOutput()->addModules(
'jquery.makeCollapsible' );
1409 $headerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getHeaderText',
'1.38' )
1410 ? $this->getHeaderText()
1411 : $this->getHeaderHtml();
1412 $footerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getFooterText',
'1.38' )
1413 ? $this->getFooterText()
1414 : $this->getFooterHtml();
1415 $html = $this->getErrorsOrWarnings( $submitResult,
'error' )
1416 . $this->getErrorsOrWarnings( $submitResult,
'warning' )
1418 . $this->getHiddenTitle()
1420 . $this->getHiddenFields()
1421 . $this->getButtons()
1424 return $this->mPre . $this->wrapForm( $html ) . $this->mPost;
1435 $this->mCollapsible =
true;
1436 $this->mCollapsed = $collapsedByDefault;
1446 # Use multipart/form-data
1447 $encType = $this->mUseMultipart
1448 ?
'multipart/form-data'
1449 :
'application/x-www-form-urlencoded';
1452 'class' =>
'mw-htmlform',
1453 'action' => $this->getAction(),
1454 'method' => $this->getMethod(),
1455 'enctype' => $encType,
1458 $attribs[
'id'] = $this->mId;
1460 if ( is_string( $this->mAutocomplete ) ) {
1461 $attribs[
'autocomplete'] = $this->mAutocomplete;
1463 if ( $this->mName ) {
1464 $attribs[
'name'] = $this->mName;
1466 if ( $this->needsJSForHtml5FormValidation() ) {
1467 $attribs[
'novalidate'] =
true;
1480 # Include a <fieldset> wrapper for style, if requested.
1481 if ( $this->mWrapperLegend !==
false ) {
1482 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1483 $html = Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1486 return Html::rawElement(
1488 $this->getFormAttributes(),
1502 $html .= $this->getHiddenTitle();
1504 if ( $this->mFormIdentifier !==
null ) {
1505 $html .= Html::hidden(
1507 $this->mFormIdentifier
1510 if ( $this->getMethod() ===
'post' ) {
1511 $html .= Html::hidden(
1513 $this->getUser()->getEditToken( $this->mTokenSalt ),
1514 [
'id' =>
'wpEditToken' ]
1518 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1519 $html .= Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1533 if ( $this->mShowSubmit ) {
1536 if ( $this->mSubmitID !==
null ) {
1537 $attribs[
'id'] = $this->mSubmitID;
1540 if ( $this->mSubmitName !==
null ) {
1541 $attribs[
'name'] = $this->mSubmitName;
1544 if ( $this->mSubmitTooltip !==
null ) {
1545 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1548 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1553 if ( $this->mShowCancel ) {
1554 $target = $this->getCancelTargetURL();
1560 $this->msg(
'cancel' )->text()
1564 foreach ( $this->mButtons as $button ) {
1567 'name' => $button[
'name'],
1568 'value' => $button[
'value']
1571 if ( isset( $button[
'label-message'] ) ) {
1572 $label = $this->getMessage( $button[
'label-message'] )->parse();
1573 } elseif ( isset( $button[
'label'] ) ) {
1574 $label = htmlspecialchars( $button[
'label'] );
1575 } elseif ( isset( $button[
'label-raw'] ) ) {
1576 $label = $button[
'label-raw'];
1578 $label = htmlspecialchars( $button[
'value'] );
1582 if ( $button[
'attribs'] ) {
1584 $attrs += $button[
'attribs'];
1587 if ( isset( $button[
'id'] ) ) {
1588 $attrs[
'id'] = $button[
'id'];
1591 $buttons .= Html::rawElement(
'button', $attrs, $label ) .
"\n";
1598 return Html::rawElement(
'span',
1599 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1608 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1621 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1622 throw new DomainException( $elementsType .
' is not a valid type.' );
1624 $elementstr =
false;
1625 if ( $elements instanceof
Status ) {
1626 [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1627 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1628 if ( $status->isGood() ) {
1631 $elementstr = $status
1633 ->setContext( $this )
1634 ->setInterfaceMessageFlag(
true )
1637 } elseif ( $elementsType ===
'error' ) {
1638 if ( is_array( $elements ) ) {
1639 $elementstr = $this->formatErrors( $elements );
1640 } elseif ( $elements && $elements !==
true ) {
1641 $elementstr = (string)$elements;
1645 if ( !$elementstr ) {
1647 } elseif ( $elementsType ===
'error' ) {
1648 return Html::errorBox( $elementstr );
1650 return Html::warningBox( $elementstr );
1664 foreach ( $errors as $error ) {
1665 $errorstr .= Html::rawElement(
1668 $this->getMessage( $error )->parse()
1672 return Html::rawElement(
'ul', [], $errorstr );
1683 $this->mSubmitText = $t;
1695 $this->mSubmitFlags = [
'destructive',
'primary' ];
1709 if ( !$msg instanceof
Message ) {
1710 $msg = $this->msg( $msg );
1712 $this->setSubmitText( $msg->text() );
1722 return $this->mSubmitText ?: $this->msg(
'htmlform-submit' )->text();
1731 $this->mSubmitName = $name;
1742 $this->mSubmitTooltip = $name;
1756 $this->mSubmitID = $t;
1780 $this->mFormIdentifier = $ident;
1781 $this->mSingleForm = $single;
1797 $this->mShowSubmit = !$suppressSubmit;
1809 $this->mShowCancel = $show;
1821 $target = TitleValue::castPageToLinkTarget( $target );
1824 $this->mCancelTarget = $target;
1833 if ( is_string( $this->mCancelTarget ) ) {
1834 return $this->mCancelTarget;
1837 $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1838 return $target->getLocalURL();
1852 $this->mTableId = $id;
1873 $this->mName = $name;
1890 $this->mWrapperLegend = $legend;
1903 $this->mWrapperAttributes = $attributes;
1918 if ( !$msg instanceof
Message ) {
1919 $msg = $this->msg( $msg );
1921 $this->setWrapperLegend( $msg->text() );
1936 $this->mMessagePrefix = $p;
1950 $this->mTitle = Title::castFromPageReference( $t );
1959 return $this->mTitle ?: $this->getContext()->getTitle();
1970 $this->mMethod = strtolower( $method );
1979 return $this->mMethod;
1993 return Xml::fieldset( $legend, $section, $attributes ) .
"\n";
2016 $fieldsetIDPrefix =
'',
2017 &$hasUserVisibleFields =
false
2019 if ( $this->mFieldData ===
null ) {
2020 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
2021 .
'You probably called displayForm() without calling prepareForm() first.' );
2025 $subsectionHtml =
'';
2028 foreach ( $fields as $key => $value ) {
2030 $v = array_key_exists( $key, $this->mFieldData )
2031 ? $this->mFieldData[$key]
2032 : $value->getDefault();
2034 $retval = $this->formatField( $value, $v ??
'' );
2038 if ( $value->hasVisibleOutput() ) {
2041 $labelValue = trim( $value->getLabel() );
2042 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
2046 $hasUserVisibleFields =
true;
2048 } elseif ( is_array( $value ) ) {
2049 $subsectionHasVisibleFields =
false;
2051 $this->displaySection( $value,
2053 "$fieldsetIDPrefix$key-",
2054 $subsectionHasVisibleFields );
2056 if ( $subsectionHasVisibleFields ===
true ) {
2058 $hasUserVisibleFields =
true;
2060 $legend = $this->getLegend( $key );
2062 $headerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getHeaderText',
'1.38' )
2063 ? $this->getHeaderText( $key )
2064 : $this->getHeaderHtml( $key );
2065 $footerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getFooterText',
'1.38' )
2066 ? $this->getFooterText( $key )
2067 : $this->getFooterHtml( $key );
2068 $section = $headerHtml .
2073 if ( $fieldsetIDPrefix ) {
2074 $attributes[
'id'] = Sanitizer::escapeIdForAttribute(
"$fieldsetIDPrefix$key" );
2076 $subsectionHtml .= $this->wrapFieldSetSection(
2077 $legend, $section, $attributes, $fields === $this->mFieldTree
2081 $subsectionHtml .= $section;
2086 $html = $this->formatSection( $html, $sectionName, $hasLabel );
2088 if ( $subsectionHtml ) {
2089 if ( $this->mSubSectionBeforeFields ) {
2090 return $subsectionHtml .
"\n" . $html;
2092 return $html .
"\n" . $subsectionHtml;
2108 $displayFormat = $this->getDisplayFormat();
2109 switch ( $displayFormat ) {
2113 return $field->
getDiv( $value );
2115 return $field->
getRaw( $value );
2119 throw new LogicException(
'Not implemented' );
2131 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
2132 if ( !$fieldsHtml ) {
2138 $displayFormat = $this->getDisplayFormat();
2139 $html = implode(
'', $fieldsHtml );
2141 if ( $displayFormat ===
'raw' ) {
2146 $attribs = $anyFieldHasLabel ? [] : [
'class' =>
'mw-htmlform-nolabel' ];
2148 if ( $sectionName ) {
2149 $attribs[
'id'] = Sanitizer::escapeIdForAttribute( $sectionName );
2152 if ( $displayFormat ===
'table' ) {
2153 return Html::rawElement(
'table',
2155 Html::rawElement(
'tbody', [],
"\n$html\n" ) ) .
"\n";
2156 } elseif ( $displayFormat ===
'inline' ) {
2157 return Html::rawElement(
'span', $attribs,
"\n$html\n" );
2159 return Html::rawElement(
'div', $attribs,
"\n$html\n" );
2167 $this->prepareForm();
2175 $request = $this->getRequest();
2177 foreach ( $this->mFlatFields as $fieldname => $field ) {
2178 if ( $field->skipLoadData( $request ) ) {
2181 if ( $field->mParams[
'disabled'] ??
false ) {
2182 $fieldData[$fieldname] = $field->getDefault();
2184 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
2190 foreach ( $fieldData as $name => &$value ) {
2191 $field = $this->mFlatFields[$name];
2192 if ( $field->isDisabled( $fieldData ) ) {
2193 $value = $field->getDefault();
2198 foreach ( $fieldData as $name => &$value ) {
2199 $field = $this->mFlatFields[$name];
2200 $value = $field->filter( $value, $fieldData );
2203 $this->mFieldData = $fieldData;
2230 return $this->msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
2244 $this->mAction = $action;
2258 if ( $this->mAction !==
false ) {
2259 return $this->mAction;
2268 if ( str_contains( $articlePath,
'?' ) && $this->getMethod() ===
'get' ) {
2272 return $this->
getTitle()->getLocalURL();
2286 $this->mAutocomplete = $autocomplete;
2311 foreach ( $this->mFlatFields as $field ) {
2312 if ( $field->needsJSForHtml5FormValidation() ) {
2321class_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.