27use InvalidArgumentException;
32use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
209 use ProtectedHookAccessorTrait;
213 'api' => HTMLApiField::class,
214 'text' => HTMLTextField::class,
215 'textwithbutton' => HTMLTextFieldWithButton::class,
216 'textarea' => HTMLTextAreaField::class,
217 'select' => HTMLSelectField::class,
218 'combobox' => HTMLComboboxField::class,
219 'radio' => HTMLRadioField::class,
220 'multiselect' => HTMLMultiSelectField::class,
221 'limitselect' => HTMLSelectLimitField::class,
222 'check' => HTMLCheckField::class,
223 'toggle' => HTMLCheckField::class,
224 'int' => HTMLIntField::class,
225 'file' => HTMLFileField::class,
226 'float' => HTMLFloatField::class,
227 'info' => HTMLInfoField::class,
228 'selectorother' => HTMLSelectOrOtherField::class,
229 'selectandother' => HTMLSelectAndOtherField::class,
230 'namespaceselect' => HTMLSelectNamespace::class,
231 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
232 'tagfilter' => HTMLTagFilter::class,
233 'sizefilter' => HTMLSizeFilterField::class,
234 'submit' => HTMLSubmitField::class,
235 'hidden' => HTMLHiddenField::class,
236 'edittools' => HTMLEditTools::class,
237 'checkmatrix' => HTMLCheckMatrix::class,
238 'cloner' => HTMLFormFieldCloner::class,
239 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
240 'language' => HTMLSelectLanguageField::class,
241 'date' => HTMLDateTimeField::class,
242 'time' => HTMLDateTimeField::class,
243 'datetime' => HTMLDateTimeField::class,
244 'expiry' => HTMLExpiryField::class,
245 'timezone' => HTMLTimezoneField::class,
249 'email' => HTMLTextField::class,
250 'password' => HTMLTextField::class,
251 'url' => HTMLTextField::class,
252 'title' => HTMLTitleTextField::class,
253 'user' => HTMLUserTextField::class,
254 'tagmultiselect' => HTMLTagMultiselectField::class,
255 'usersmultiselect' => HTMLUsersMultiselectField::class,
256 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
257 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
435 private $hiddenTitleAddedToForm =
false;
455 return new CodexHTMLForm( $descriptor, $context, $messagePrefix );
457 return new VFormHTMLForm( $descriptor, $context, $messagePrefix );
459 return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
461 $form =
new self( $descriptor, $context, $messagePrefix );
482 $this->mMessagePrefix = $messagePrefix;
496 $loadedDescriptor = [];
498 foreach ( $descriptor as $fieldname => $info ) {
499 $section = $info[
'section'] ??
'';
501 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
502 $this->mUseMultipart =
true;
505 $field = static::loadInputFromParameters( $fieldname, $info, $this );
507 $setSection =& $loadedDescriptor;
509 foreach ( explode(
'/', $section ) as $newName ) {
510 $setSection[$newName] ??= [];
511 $setSection =& $setSection[$newName];
515 $setSection[$fieldname] = $field;
516 $this->mFlatFields[$fieldname] = $field;
519 $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
529 return isset( $this->mFlatFields[$fieldname] );
538 if ( !$this->
hasField( $fieldname ) ) {
539 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
541 return $this->mFlatFields[$fieldname];
555 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
556 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
558 throw new LogicException(
'Cannot change display format after creation, ' .
559 'use HTMLForm::factory() instead' );
562 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
563 throw new InvalidArgumentException(
'Display format must be one of ' .
566 $this->availableDisplayFormats,
567 $this->availableSubclassDisplayFormats
573 $this->displayFormat = $format;
604 if ( isset( $descriptor[
'class'] ) ) {
605 $class = $descriptor[
'class'];
606 } elseif ( isset( $descriptor[
'type'] ) ) {
607 $class = static::$typeMappings[$descriptor[
'type']];
608 $descriptor[
'class'] = $class;
614 throw new InvalidArgumentException(
"Descriptor with no class for $fieldname: "
615 . print_r( $descriptor,
true ) );
636 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
638 $descriptor[
'fieldname'] = $fieldname;
640 $descriptor[
'parent'] = $parent;
643 # @todo This will throw a fatal error whenever someone try to use
644 # 'class' to feed a CSS class instead of 'cssclass'. Would be
645 # great to avoid the fatal error and show a nice error.
646 return new $class( $descriptor );
658 # Load data from the request.
660 $this->mFormIdentifier ===
null ||
661 $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier ||
662 ( $this->mSingleForm && $this->
getMethod() ===
'get' )
666 $this->mFieldData = [];
679 if ( $this->mFormIdentifier ===
null ) {
688 } elseif ( $this->
getRequest()->wasPosted() ) {
689 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
690 if ( $this->
getUser()->isRegistered() || $editToken !==
null ) {
694 $tokenOkay = $this->
getUser()->matchEditToken( $editToken, $this->mTokenSalt );
700 if ( $tokenOkay && $identOkay ) {
701 $this->mWasSubmitted =
true;
719 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
756 $hoistedErrors = Status::newGood();
757 if ( $this->mValidationErrorMessage ) {
758 foreach ( $this->mValidationErrorMessage as $error ) {
759 $hoistedErrors->fatal( ...$error );
762 $hoistedErrors->fatal(
'htmlform-invalid-input' );
765 $this->mWasSubmitted =
true;
767 # Check for cancelled submission
768 foreach ( $this->mFlatFields as $fieldname => $field ) {
769 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
772 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
773 $this->mWasSubmitted =
false;
778 # Check for validation
779 $hasNonDefault =
false;
780 foreach ( $this->mFlatFields as $fieldname => $field ) {
781 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
784 $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
785 if ( $field->isDisabled( $this->mFieldData ) ) {
788 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
789 if ( $res !==
true ) {
791 if ( $res !==
false && !$field->canDisplayErrors() ) {
792 if ( is_string( $res ) ) {
793 $hoistedErrors->fatal(
'rawmessage', $res );
795 $hoistedErrors->fatal( $res );
803 if ( !$hasNonDefault && $this->
getMethod() ===
'get' &&
804 ( $this->mFormIdentifier ===
null ||
805 $this->
getRequest()->getCheck(
'wpFormIdentifier' ) )
807 $this->mWasSubmitted =
false;
810 return $hoistedErrors;
814 if ( !is_callable( $callback ) ) {
815 throw new LogicException(
'HTMLForm: no submit callback provided. Use ' .
816 'setSubmitCallback() to set one.' );
821 $res = call_user_func( $callback, $data, $this );
822 if ( $res ===
false ) {
823 $this->mWasSubmitted =
false;
826 $res = Status::wrap( $res );
858 $this->mSubmitCallback = $cb;
873 $this->mValidationErrorMessage = $msg;
914 $this->mPre .= $html;
977 if ( $section ===
null ) {
978 $this->mHeader .= $html;
980 $this->mSectionHeaders[$section] ??=
'';
981 $this->mSectionHeaders[$section] .= $html;
997 if ( $section ===
null ) {
998 $this->mHeader = $html;
1000 $this->mSectionHeaders[$section] = $html;
1015 return $section ? $this->mSectionHeaders[$section] ??
'' :
$this->mHeader;
1071 if ( $section ===
null ) {
1072 $this->mFooter .= $html;
1074 $this->mSectionFooters[$section] ??=
'';
1075 $this->mSectionFooters[$section] .= $html;
1091 if ( $section ===
null ) {
1092 $this->mFooter = $html;
1094 $this->mSectionFooters[$section] = $html;
1108 return $section ? $this->mSectionFooters[$section] ??
'' :
$this->mFooter;
1162 $this->mPost .= $html;
1176 $this->mPost = $html;
1228 throw new \InvalidArgumentException(
1229 "Non-Codex HTMLForms do not support additional section information."
1233 $this->mSections = $sections;
1249 if ( !is_array( $value ) ) {
1251 $attribs += [
'name' => $name ];
1252 $this->mHiddenFields[] = [ $value, $attribs ];
1270 foreach ( $fields as $name => $value ) {
1271 if ( is_array( $value ) ) {
1275 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1305 if ( !is_array( $data ) ) {
1306 $args = func_get_args();
1307 if ( count( $args ) < 2 || count( $args ) > 4 ) {
1308 throw new InvalidArgumentException(
1309 'Incorrect number of arguments for deprecated calling style'
1314 'value' => $args[1],
1315 'id' => $args[2] ??
null,
1316 'attribs' => $args[3] ??
null,
1319 if ( !isset( $data[
'name'] ) ) {
1320 throw new InvalidArgumentException(
'A name is required' );
1322 if ( !isset( $data[
'value'] ) ) {
1323 throw new InvalidArgumentException(
'A value is required' );
1326 $this->mButtons[] = $data + [
1346 $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()->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 ( isset( $this->mSubmitID ) ) {
1537 $attribs[
'id'] = $this->mSubmitID;
1540 if ( isset( $this->mSubmitName ) ) {
1541 $attribs[
'name'] = $this->mSubmitName;
1544 if ( isset( $this->mSubmitTooltip ) ) {
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.