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,
408 private $hiddenTitleAddedToForm =
false;
428 return new CodexHTMLForm( $descriptor, $context, $messagePrefix );
430 return new VFormHTMLForm( $descriptor, $context, $messagePrefix );
432 return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
434 $form =
new self( $descriptor, $context, $messagePrefix );
455 $this->mMessagePrefix = $messagePrefix;
469 $loadedDescriptor = [];
471 foreach ( $descriptor as $fieldname => $info ) {
472 $section = $info[
'section'] ??
'';
474 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
475 $this->mUseMultipart =
true;
478 $field = static::loadInputFromParameters( $fieldname, $info, $this );
480 $setSection =& $loadedDescriptor;
482 foreach ( explode(
'/', $section ) as $newName ) {
483 $setSection[$newName] ??= [];
484 $setSection =& $setSection[$newName];
488 $setSection[$fieldname] = $field;
489 $this->mFlatFields[$fieldname] = $field;
492 $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
502 return isset( $this->mFlatFields[$fieldname] );
511 if ( !$this->
hasField( $fieldname ) ) {
512 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
514 return $this->mFlatFields[$fieldname];
528 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
529 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
531 throw new LogicException(
'Cannot change display format after creation, ' .
532 'use HTMLForm::factory() instead' );
535 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
536 throw new InvalidArgumentException(
'Display format must be one of ' .
539 $this->availableDisplayFormats,
540 $this->availableSubclassDisplayFormats
546 $this->displayFormat = $format;
577 if ( isset( $descriptor[
'class'] ) ) {
578 $class = $descriptor[
'class'];
579 } elseif ( isset( $descriptor[
'type'] ) ) {
580 $class = static::$typeMappings[$descriptor[
'type']];
581 $descriptor[
'class'] = $class;
587 throw new InvalidArgumentException(
"Descriptor with no class for $fieldname: "
588 . print_r( $descriptor,
true ) );
609 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
611 $descriptor[
'fieldname'] = $fieldname;
613 $descriptor[
'parent'] = $parent;
616 # @todo This will throw a fatal error whenever someone try to use
617 # 'class' to feed a CSS class instead of 'cssclass'. Would be
618 # great to avoid the fatal error and show a nice error.
619 return new $class( $descriptor );
631 # Load data from the request.
633 $this->mFormIdentifier ===
null ||
634 $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier ||
635 ( $this->mSingleForm && $this->
getMethod() ===
'get' )
639 $this->mFieldData = [];
652 if ( $this->mFormIdentifier ===
null ) {
661 } elseif ( $this->
getRequest()->wasPosted() ) {
662 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
663 if ( $this->
getUser()->isRegistered() || $editToken !==
null ) {
667 $tokenOkay = $this->
getUser()->matchEditToken( $editToken, $this->mTokenSalt );
673 if ( $tokenOkay && $identOkay ) {
674 $this->mWasSubmitted =
true;
692 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
729 $hoistedErrors = Status::newGood();
730 if ( $this->mValidationErrorMessage ) {
731 foreach ( $this->mValidationErrorMessage as $error ) {
732 $hoistedErrors->fatal( ...$error );
735 $hoistedErrors->fatal(
'htmlform-invalid-input' );
738 $this->mWasSubmitted =
true;
740 # Check for cancelled submission
741 foreach ( $this->mFlatFields as $fieldname => $field ) {
742 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
745 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
746 $this->mWasSubmitted =
false;
751 # Check for validation
752 $hasNonDefault =
false;
753 foreach ( $this->mFlatFields as $fieldname => $field ) {
754 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
757 $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
758 if ( $field->isDisabled( $this->mFieldData ) ) {
761 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
762 if ( $res !==
true ) {
764 if ( $res !==
false && !$field->canDisplayErrors() ) {
765 if ( is_string( $res ) ) {
766 $hoistedErrors->fatal(
'rawmessage', $res );
768 $hoistedErrors->fatal( $res );
776 if ( !$hasNonDefault && $this->
getMethod() ===
'get' &&
777 ( $this->mFormIdentifier ===
null ||
778 $this->
getRequest()->getCheck(
'wpFormIdentifier' ) )
780 $this->mWasSubmitted =
false;
783 return $hoistedErrors;
787 if ( !is_callable( $callback ) ) {
788 throw new LogicException(
'HTMLForm: no submit callback provided. Use ' .
789 'setSubmitCallback() to set one.' );
794 $res = call_user_func( $callback, $data, $this );
795 if ( $res ===
false ) {
796 $this->mWasSubmitted =
false;
799 $res = Status::wrap( $res );
831 $this->mSubmitCallback = $cb;
846 $this->mValidationErrorMessage = $msg;
887 $this->mPre .= $html;
950 if ( $section ===
null ) {
951 $this->mHeader .= $html;
953 $this->mSectionHeaders[$section] ??=
'';
954 $this->mSectionHeaders[$section] .= $html;
970 if ( $section ===
null ) {
971 $this->mHeader = $html;
973 $this->mSectionHeaders[$section] = $html;
988 return $section ? $this->mSectionHeaders[$section] ??
'' :
$this->mHeader;
1044 if ( $section ===
null ) {
1045 $this->mFooter .= $html;
1047 $this->mSectionFooters[$section] ??=
'';
1048 $this->mSectionFooters[$section] .= $html;
1064 if ( $section ===
null ) {
1065 $this->mFooter = $html;
1067 $this->mSectionFooters[$section] = $html;
1081 return $section ? $this->mSectionFooters[$section] ??
'' :
$this->mFooter;
1135 $this->mPost .= $html;
1149 $this->mPost = $html;
1201 throw new \InvalidArgumentException(
1202 "Non-Codex HTMLForms do not support additional section information."
1206 $this->mSections = $sections;
1222 if ( !is_array( $value ) ) {
1224 $attribs += [
'name' => $name ];
1225 $this->mHiddenFields[] = [ $value, $attribs ];
1243 foreach ( $fields as $name => $value ) {
1244 if ( is_array( $value ) ) {
1248 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1278 if ( !is_array( $data ) ) {
1279 $args = func_get_args();
1280 if ( count( $args ) < 2 || count( $args ) > 4 ) {
1281 throw new InvalidArgumentException(
1282 'Incorrect number of arguments for deprecated calling style'
1287 'value' => $args[1],
1288 'id' => $args[2] ??
null,
1289 'attribs' => $args[3] ??
null,
1292 if ( !isset( $data[
'name'] ) ) {
1293 throw new InvalidArgumentException(
'A name is required' );
1295 if ( !isset( $data[
'value'] ) ) {
1296 throw new InvalidArgumentException(
'A value is required' );
1299 $this->mButtons[] = $data + [
1319 $this->mTokenSalt = $salt;
1346 private function getHiddenTitle(): string {
1347 if ( $this->hiddenTitleAddedToForm ) {
1355 $html .= Html::hidden(
'title', $this->
getTitle()->getPrefixedText() ) .
"\n";
1357 $this->hiddenTitleAddedToForm =
true;
1372 # For good measure (it is the default)
1373 $this->getOutput()->setPreventClickjacking(
true );
1374 $this->getOutput()->addModules(
'mediawiki.htmlform' );
1375 $this->getOutput()->addModuleStyles(
'mediawiki.htmlform.styles' );
1377 if ( $this->mCollapsible ) {
1379 $this->getOutput()->addModules(
'jquery.makeCollapsible' );
1382 $headerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getHeaderText',
'1.38' )
1383 ? $this->getHeaderText()
1384 : $this->getHeaderHtml();
1385 $footerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getFooterText',
'1.38' )
1386 ? $this->getFooterText()
1387 : $this->getFooterHtml();
1388 $html = $this->getErrorsOrWarnings( $submitResult,
'error' )
1389 . $this->getErrorsOrWarnings( $submitResult,
'warning' )
1391 . $this->getHiddenTitle()
1393 . $this->getHiddenFields()
1394 . $this->getButtons()
1397 return $this->mPre . $this->wrapForm( $html ) . $this->mPost;
1408 $this->mCollapsible =
true;
1409 $this->mCollapsed = $collapsedByDefault;
1419 # Use multipart/form-data
1420 $encType = $this->mUseMultipart
1421 ?
'multipart/form-data'
1422 :
'application/x-www-form-urlencoded';
1425 'class' =>
'mw-htmlform',
1426 'action' => $this->getAction(),
1427 'method' => $this->getMethod(),
1428 'enctype' => $encType,
1431 $attribs[
'id'] = $this->mId;
1433 if ( is_string( $this->mAutocomplete ) ) {
1434 $attribs[
'autocomplete'] = $this->mAutocomplete;
1436 if ( $this->mName ) {
1437 $attribs[
'name'] = $this->mName;
1439 if ( $this->needsJSForHtml5FormValidation() ) {
1440 $attribs[
'novalidate'] =
true;
1453 # Include a <fieldset> wrapper for style, if requested.
1454 if ( $this->mWrapperLegend !==
false ) {
1455 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1456 $html = Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1459 return Html::rawElement(
1461 $this->getFormAttributes(),
1475 $html .= $this->getHiddenTitle();
1477 if ( $this->mFormIdentifier !==
null ) {
1478 $html .= Html::hidden(
1480 $this->mFormIdentifier
1483 if ( $this->getMethod() ===
'post' ) {
1484 $html .= Html::hidden(
1486 $this->
getUser()->getEditToken( $this->mTokenSalt ),
1487 [
'id' =>
'wpEditToken' ]
1491 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1492 $html .= Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1506 if ( $this->mShowSubmit ) {
1509 if ( isset( $this->mSubmitID ) ) {
1510 $attribs[
'id'] = $this->mSubmitID;
1513 if ( isset( $this->mSubmitName ) ) {
1514 $attribs[
'name'] = $this->mSubmitName;
1517 if ( isset( $this->mSubmitTooltip ) ) {
1518 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1521 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1526 if ( $this->mShowCancel ) {
1527 $target = $this->getCancelTargetURL();
1533 $this->msg(
'cancel' )->text()
1537 foreach ( $this->mButtons as $button ) {
1540 'name' => $button[
'name'],
1541 'value' => $button[
'value']
1544 if ( isset( $button[
'label-message'] ) ) {
1545 $label = $this->getMessage( $button[
'label-message'] )->parse();
1546 } elseif ( isset( $button[
'label'] ) ) {
1547 $label = htmlspecialchars( $button[
'label'] );
1548 } elseif ( isset( $button[
'label-raw'] ) ) {
1549 $label = $button[
'label-raw'];
1551 $label = htmlspecialchars( $button[
'value'] );
1555 if ( $button[
'attribs'] ) {
1557 $attrs += $button[
'attribs'];
1560 if ( isset( $button[
'id'] ) ) {
1561 $attrs[
'id'] = $button[
'id'];
1564 $buttons .= Html::rawElement(
'button', $attrs, $label ) .
"\n";
1571 return Html::rawElement(
'span',
1572 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1581 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1594 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1595 throw new DomainException( $elementsType .
' is not a valid type.' );
1597 $elementstr =
false;
1598 if ( $elements instanceof
Status ) {
1599 [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1600 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1601 if ( $status->isGood() ) {
1604 $elementstr = $status
1606 ->setContext( $this )
1607 ->setInterfaceMessageFlag(
true )
1610 } elseif ( $elementsType ===
'error' ) {
1611 if ( is_array( $elements ) ) {
1612 $elementstr = $this->formatErrors( $elements );
1613 } elseif ( $elements && $elements !==
true ) {
1614 $elementstr = (string)$elements;
1618 if ( !$elementstr ) {
1620 } elseif ( $elementsType ===
'error' ) {
1621 return Html::errorBox( $elementstr );
1623 return Html::warningBox( $elementstr );
1637 foreach ( $errors as $error ) {
1638 $errorstr .= Html::rawElement(
1641 $this->getMessage( $error )->parse()
1645 return Html::rawElement(
'ul', [], $errorstr );
1656 $this->mSubmitText = $t;
1668 $this->mSubmitFlags = [
'destructive',
'primary' ];
1682 if ( !$msg instanceof
Message ) {
1683 $msg = $this->msg( $msg );
1685 $this->setSubmitText( $msg->text() );
1695 return $this->mSubmitText ?: $this->msg(
'htmlform-submit' )->text();
1704 $this->mSubmitName = $name;
1715 $this->mSubmitTooltip = $name;
1729 $this->mSubmitID = $t;
1753 $this->mFormIdentifier = $ident;
1754 $this->mSingleForm = $single;
1770 $this->mShowSubmit = !$suppressSubmit;
1782 $this->mShowCancel = $show;
1794 $target = TitleValue::castPageToLinkTarget( $target );
1797 $this->mCancelTarget = $target;
1806 if ( is_string( $this->mCancelTarget ) ) {
1807 return $this->mCancelTarget;
1810 $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1811 return $target->getLocalURL();
1825 $this->mTableId = $id;
1846 $this->mName = $name;
1863 $this->mWrapperLegend = $legend;
1876 $this->mWrapperAttributes = $attributes;
1891 if ( !$msg instanceof
Message ) {
1892 $msg = $this->msg( $msg );
1894 $this->setWrapperLegend( $msg->text() );
1909 $this->mMessagePrefix = $p;
1923 $this->mTitle = Title::castFromPageReference( $t );
1932 return $this->mTitle ?: $this->
getContext()->getTitle();
1943 $this->mMethod = strtolower( $method );
1952 return $this->mMethod;
1966 return Xml::fieldset( $legend, $section, $attributes ) .
"\n";
1988 $fieldsetIDPrefix =
'',
1989 &$hasUserVisibleFields =
false
1991 if ( $this->mFieldData ===
null ) {
1992 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
1993 .
'You probably called displayForm() without calling prepareForm() first.' );
1997 $subsectionHtml =
'';
2000 foreach ( $fields as $key => $value ) {
2002 $v = array_key_exists( $key, $this->mFieldData )
2003 ? $this->mFieldData[$key]
2004 : $value->getDefault();
2006 $retval = $this->formatField( $value, $v ??
'' );
2010 if ( $value->hasVisibleOutput() ) {
2013 $labelValue = trim( $value->getLabel() );
2014 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
2018 $hasUserVisibleFields =
true;
2020 } elseif ( is_array( $value ) ) {
2021 $subsectionHasVisibleFields =
false;
2023 $this->displaySection( $value,
2025 "$fieldsetIDPrefix$key-",
2026 $subsectionHasVisibleFields );
2028 if ( $subsectionHasVisibleFields ===
true ) {
2030 $hasUserVisibleFields =
true;
2032 $legend = $this->getLegend( $key );
2034 $headerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getHeaderText',
'1.38' )
2035 ? $this->getHeaderText( $key )
2036 : $this->getHeaderHtml( $key );
2037 $footerHtml = MWDebug::detectDeprecatedOverride( $this, __CLASS__,
'getFooterText',
'1.38' )
2038 ? $this->getFooterText( $key )
2039 : $this->getFooterHtml( $key );
2040 $section = $headerHtml .
2045 if ( $fieldsetIDPrefix ) {
2046 $attributes[
'id'] = Sanitizer::escapeIdForAttribute(
"$fieldsetIDPrefix$key" );
2048 $subsectionHtml .= $this->wrapFieldSetSection(
2049 $legend, $section, $attributes, $fields === $this->mFieldTree
2053 $subsectionHtml .= $section;
2058 $html = $this->formatSection( $html, $sectionName, $hasLabel );
2060 if ( $subsectionHtml ) {
2061 if ( $this->mSubSectionBeforeFields ) {
2062 return $subsectionHtml .
"\n" . $html;
2064 return $html .
"\n" . $subsectionHtml;
2080 $displayFormat = $this->getDisplayFormat();
2081 switch ( $displayFormat ) {
2085 return $field->
getDiv( $value );
2087 return $field->
getRaw( $value );
2091 throw new LogicException(
'Not implemented' );
2103 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
2104 if ( !$fieldsHtml ) {
2110 $displayFormat = $this->getDisplayFormat();
2111 $html = implode(
'', $fieldsHtml );
2113 if ( $displayFormat ===
'raw' ) {
2118 $attribs = $anyFieldHasLabel ? [] : [
'class' =>
'mw-htmlform-nolabel' ];
2120 if ( $sectionName ) {
2121 $attribs[
'id'] = Sanitizer::escapeIdForAttribute( $sectionName );
2124 if ( $displayFormat ===
'table' ) {
2125 return Html::rawElement(
'table',
2127 Html::rawElement(
'tbody', [],
"\n$html\n" ) ) .
"\n";
2128 } elseif ( $displayFormat ===
'inline' ) {
2129 return Html::rawElement(
'span', $attribs,
"\n$html\n" );
2131 return Html::rawElement(
'div', $attribs,
"\n$html\n" );
2139 $this->prepareForm();
2149 foreach ( $this->mFlatFields as $fieldname => $field ) {
2150 if ( $field->skipLoadData( $request ) ) {
2153 if ( $field->mParams[
'disabled'] ??
false ) {
2154 $fieldData[$fieldname] = $field->getDefault();
2156 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
2162 foreach ( $fieldData as $name => &$value ) {
2163 $field = $this->mFlatFields[$name];
2164 if ( $field->isDisabled( $fieldData ) ) {
2165 $value = $field->getDefault();
2170 foreach ( $fieldData as $name => &$value ) {
2171 $field = $this->mFlatFields[$name];
2172 $value = $field->filter( $value, $fieldData );
2175 $this->mFieldData = $fieldData;
2202 return $this->msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
2216 $this->mAction = $action;
2230 if ( $this->mAction !==
false ) {
2231 return $this->mAction;
2240 if ( str_contains( $articlePath,
'?' ) && $this->getMethod() ===
'get' ) {
2244 return $this->
getTitle()->getLocalURL();
2258 $this->mAutocomplete = $autocomplete;
2283 foreach ( $this->mFlatFields as $field ) {
2284 if ( $field->needsJSForHtml5FormValidation() ) {
2293class_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.