24 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
152 use ProtectedHookAccessorTrait;
156 'api' => HTMLApiField::class,
157 'text' => HTMLTextField::class,
158 'textwithbutton' => HTMLTextFieldWithButton::class,
159 'textarea' => HTMLTextAreaField::class,
160 'select' => HTMLSelectField::class,
161 'combobox' => HTMLComboboxField::class,
162 'radio' => HTMLRadioField::class,
163 'multiselect' => HTMLMultiSelectField::class,
164 'limitselect' => HTMLSelectLimitField::class,
165 'check' => HTMLCheckField::class,
166 'toggle' => HTMLCheckField::class,
167 'int' => HTMLIntField::class,
168 'file' => HTMLFileField::class,
169 'float' => HTMLFloatField::class,
170 'info' => HTMLInfoField::class,
171 'selectorother' => HTMLSelectOrOtherField::class,
172 'selectandother' => HTMLSelectAndOtherField::class,
173 'namespaceselect' => HTMLSelectNamespace::class,
174 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
175 'tagfilter' => HTMLTagFilter::class,
176 'sizefilter' => HTMLSizeFilterField::class,
177 'submit' => HTMLSubmitField::class,
178 'hidden' => HTMLHiddenField::class,
179 'edittools' => HTMLEditTools::class,
180 'checkmatrix' => HTMLCheckMatrix::class,
181 'cloner' => HTMLFormFieldCloner::class,
182 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
183 'language' => HTMLSelectLanguageField::class,
184 'date' => HTMLDateTimeField::class,
185 'time' => HTMLDateTimeField::class,
186 'datetime' => HTMLDateTimeField::class,
187 'expiry' => HTMLExpiryField::class,
188 'timezone' => HTMLTimezoneField::class,
192 'email' => HTMLTextField::class,
193 'password' => HTMLTextField::class,
194 'url' => HTMLTextField::class,
195 'title' => HTMLTitleTextField::class,
196 'user' => HTMLUserTextField::class,
197 'tagmultiselect' => HTMLTagMultiselectField::class,
198 'usersmultiselect' => HTMLUsersMultiselectField::class,
199 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
200 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
335 private $hiddenTitleAddedToForm =
false;
355 return new VFormHTMLForm( $descriptor, $context, $messagePrefix );
357 return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
359 $form =
new self( $descriptor, $context, $messagePrefix );
380 $this->mMessagePrefix = $messagePrefix;
384 !$this->
getConfig()->
get( MainConfigNames::HTMLFormAllowTableFormat )
385 && $this->displayFormat ===
'table'
387 $this->displayFormat =
'div';
403 $loadedDescriptor = [];
405 foreach ( $descriptor as $fieldname => $info ) {
407 $section = $info[
'section'] ??
'';
409 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
410 $this->mUseMultipart =
true;
413 $field = static::loadInputFromParameters( $fieldname, $info, $this );
415 $setSection =& $loadedDescriptor;
417 foreach ( explode(
'/', $section ) as $newName ) {
418 if ( !isset( $setSection[$newName] ) ) {
419 $setSection[$newName] = [];
422 $setSection =& $setSection[$newName];
426 $setSection[$fieldname] = $field;
427 $this->mFlatFields[$fieldname] = $field;
430 $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
440 return isset( $this->mFlatFields[$fieldname] );
449 if ( !$this->
hasField( $fieldname ) ) {
450 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
452 return $this->mFlatFields[$fieldname];
467 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
468 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
470 throw new MWException(
'Cannot change display format after creation, ' .
471 'use HTMLForm::factory() instead' );
474 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
475 throw new MWException(
'Display format must be one of ' .
478 $this->availableDisplayFormats,
479 $this->availableSubclassDisplayFormats
486 if ( !$this->
getConfig()->
get( MainConfigNames::HTMLFormAllowTableFormat ) &&
487 $format ===
'table' ) {
491 $this->displayFormat = $format;
523 if ( isset( $descriptor[
'class'] ) ) {
524 $class = $descriptor[
'class'];
525 } elseif ( isset( $descriptor[
'type'] ) ) {
526 $class = static::$typeMappings[$descriptor[
'type']];
527 $descriptor[
'class'] = $class;
533 throw new MWException(
"Descriptor with no class for $fieldname: "
534 . print_r( $descriptor,
true ) );
556 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
558 $descriptor[
'fieldname'] = $fieldname;
560 $descriptor[
'parent'] = $parent;
563 # @todo This will throw a fatal error whenever someone try to use
564 # 'class' to feed a CSS class instead of 'cssclass'. Would be
565 # great to avoid the fatal error and show a nice error.
566 return new $class( $descriptor );
579 # Load data from the request.
581 $this->mFormIdentifier ===
null ||
582 $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier
586 $this->mFieldData = [];
599 if ( $this->mFormIdentifier ===
null ) {
608 } elseif ( $this->
getRequest()->wasPosted() ) {
609 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
610 if ( $this->
getUser()->isRegistered() || $editToken !==
null ) {
614 $tokenOkay = $this->
getUser()->matchEditToken( $editToken, $this->mTokenSalt );
620 if ( $tokenOkay && $identOkay ) {
621 $this->mWasSubmitted =
true;
639 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
678 if ( $this->mValidationErrorMessage ) {
679 foreach ( $this->mValidationErrorMessage as $error ) {
680 $hoistedErrors->fatal( ...$error );
683 $hoistedErrors->fatal(
'htmlform-invalid-input' );
686 $this->mWasSubmitted =
true;
688 # Check for cancelled submission
689 foreach ( $this->mFlatFields as $fieldname => $field ) {
690 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
693 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
694 $this->mWasSubmitted =
false;
699 # Check for validation
700 $hasNonDefault =
false;
701 foreach ( $this->mFlatFields as $fieldname => $field ) {
702 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
705 $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
706 if ( $field->isDisabled( $this->mFieldData ) ) {
709 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
710 if (
$res !==
true ) {
712 if (
$res !==
false && !$field->canDisplayErrors() ) {
713 if ( is_string(
$res ) ) {
714 $hoistedErrors->fatal(
'rawmessage',
$res );
716 $hoistedErrors->fatal(
$res );
724 if ( !$hasNonDefault && $this->
getMethod() ===
'get' &&
725 ( $this->mFormIdentifier ===
null ||
726 $this->
getRequest()->getCheck(
'wpFormIdentifier' ) )
728 $this->mWasSubmitted =
false;
731 return $hoistedErrors;
735 if ( !is_callable( $callback ) ) {
736 throw new MWException(
'HTMLForm: no submit callback provided. Use ' .
737 'setSubmitCallback() to set one.' );
742 $res = call_user_func( $callback, $data, $this );
743 if (
$res ===
false ) {
744 $this->mWasSubmitted =
false;
779 $this->mSubmitCallback = $cb;
794 $this->mValidationErrorMessage = $msg;
834 $this->mPre .= $html;
894 if ( $section ===
null ) {
895 $this->mHeader .= $html;
897 if ( !isset( $this->mSectionHeaders[$section] ) ) {
898 $this->mSectionHeaders[$section] =
'';
900 $this->mSectionHeaders[$section] .= $html;
916 if ( $section ===
null ) {
917 $this->mHeader = $html;
919 $this->mSectionHeaders[$section] = $html;
934 if ( $section ===
null ) {
937 return $this->mSectionHeaders[$section] ??
'';
991 if ( $section ===
null ) {
992 $this->mFooter .= $html;
994 if ( !isset( $this->mSectionFooters[$section] ) ) {
995 $this->mSectionFooters[$section] =
'';
997 $this->mSectionFooters[$section] .= $html;
1013 if ( $section ===
null ) {
1014 $this->mFooter = $html;
1016 $this->mSectionFooters[$section] = $html;
1030 if ( $section ===
null ) {
1033 return $this->mSectionFooters[$section] ??
'';
1085 $this->mPost .= $html;
1099 $this->mPost = $html;
1148 $attribs += [
'name' => $name ];
1149 $this->mHiddenFields[] = [ $value, $attribs ];
1165 foreach ( $fields as $name => $value ) {
1166 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1196 if ( !is_array( $data ) ) {
1197 $args = func_get_args();
1198 if ( count( $args ) < 2 || count( $args ) > 4 ) {
1199 throw new InvalidArgumentException(
1200 'Incorrect number of arguments for deprecated calling style'
1205 'value' => $args[1],
1206 'id' => $args[2] ??
null,
1207 'attribs' => $args[3] ??
null,
1210 if ( !isset( $data[
'name'] ) ) {
1211 throw new InvalidArgumentException(
'A name is required' );
1213 if ( !isset( $data[
'value'] ) ) {
1214 throw new InvalidArgumentException(
'A value is required' );
1217 $this->mButtons[] = $data + [
1237 $this->mTokenSalt = $salt;
1264 private function getHiddenTitle(): string {
1265 if ( $this->hiddenTitleAddedToForm ) {
1275 $this->hiddenTitleAddedToForm =
true;
1290 # For good measure (it is the default)
1291 $this->getOutput()->setPreventClickjacking(
true );
1292 $this->getOutput()->addModules(
'mediawiki.htmlform' );
1293 $this->getOutput()->addModuleStyles(
'mediawiki.htmlform.styles' );
1295 if ( $this->mCollapsible ) {
1297 $this->getOutput()->addModules(
'jquery.makeCollapsible' );
1301 . $this->getErrorsOrWarnings( $submitResult,
'error' )
1302 . $this->getErrorsOrWarnings( $submitResult,
'warning' )
1303 . $this->getHeaderText()
1304 . $this->getHiddenTitle()
1306 . $this->getHiddenFields()
1307 . $this->getButtons()
1308 . $this->getFooterText();
1310 $html = $this->wrapForm( $html );
1312 return '' . $this->mPre . $html . $this->mPost;
1323 $this->mCollapsible =
true;
1324 $this->mCollapsed = $collapsedByDefault;
1334 # Use multipart/form-data
1335 $encType = $this->mUseMultipart
1336 ?
'multipart/form-data'
1337 :
'application/x-www-form-urlencoded';
1340 'class' =>
'mw-htmlform',
1341 'action' => $this->getAction(),
1342 'method' => $this->getMethod(),
1343 'enctype' => $encType,
1346 $attribs[
'id'] = $this->mId;
1348 if ( is_string( $this->mAutocomplete ) ) {
1349 $attribs[
'autocomplete'] = $this->mAutocomplete;
1351 if ( $this->mName ) {
1352 $attribs[
'name'] = $this->mName;
1354 if ( $this->needsJSForHtml5FormValidation() ) {
1355 $attribs[
'novalidate'] =
true;
1369 # Include a <fieldset> wrapper for style, if requested.
1370 if ( $this->mWrapperLegend !==
false ) {
1371 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1372 $html =
Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1377 $this->getFormAttributes(),
1391 $html .= $this->getHiddenTitle();
1393 if ( $this->mFormIdentifier !==
null ) {
1396 $this->mFormIdentifier
1399 if ( $this->getMethod() ===
'post' ) {
1402 $this->
getUser()->getEditToken( $this->mTokenSalt ),
1403 [
'id' =>
'wpEditToken' ]
1407 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1408 $html .=
Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1421 $useMediaWikiUIEverywhere =
1422 $this->getConfig()->get( MainConfigNames::UseMediaWikiUIEverywhere );
1424 if ( $this->mShowSubmit ) {
1427 if ( isset( $this->mSubmitID ) ) {
1428 $attribs[
'id'] = $this->mSubmitID;
1431 if ( isset( $this->mSubmitName ) ) {
1432 $attribs[
'name'] = $this->mSubmitName;
1435 if ( isset( $this->mSubmitTooltip ) ) {
1436 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1439 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1441 if ( $useMediaWikiUIEverywhere ) {
1442 foreach ( $this->mSubmitFlags as $flag ) {
1443 $attribs[
'class'][] =
'mw-ui-' . $flag;
1445 $attribs[
'class'][] =
'mw-ui-button';
1451 if ( $this->mShowReset ) {
1456 'value' => $this->msg(
'htmlform-reset' )->text(),
1457 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' :
null,
1462 if ( $this->mShowCancel ) {
1463 $target = $this->getCancelTargetURL();
1467 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' :
null,
1470 $this->msg(
'cancel' )->text()
1474 foreach ( $this->mButtons as $button ) {
1477 'name' => $button[
'name'],
1478 'value' => $button[
'value']
1481 if ( isset( $button[
'label-message'] ) ) {
1482 $label = $this->getMessage( $button[
'label-message'] )->parse();
1483 } elseif ( isset( $button[
'label'] ) ) {
1484 $label = htmlspecialchars( $button[
'label'] );
1485 } elseif ( isset( $button[
'label-raw'] ) ) {
1486 $label = $button[
'label-raw'];
1488 $label = htmlspecialchars( $button[
'value'] );
1492 if ( $button[
'attribs'] ) {
1494 $attrs += $button[
'attribs'];
1497 if ( isset( $button[
'id'] ) ) {
1498 $attrs[
'id'] = $button[
'id'];
1501 if ( $useMediaWikiUIEverywhere ) {
1502 $attrs[
'class'] = isset( $attrs[
'class'] ) ? (array)$attrs[
'class'] : [];
1503 $attrs[
'class'][] =
'mw-ui-button';
1514 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1523 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1536 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1537 throw new DomainException( $elementsType .
' is not a valid type.' );
1539 $elementstr =
false;
1540 if ( $elements instanceof
Status ) {
1541 [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1542 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1543 if ( $status->isGood() ) {
1546 $elementstr = $status
1548 ->setContext( $this )
1549 ->setInterfaceMessageFlag(
true )
1552 } elseif ( $elementsType ===
'error' ) {
1553 if ( is_array( $elements ) ) {
1554 $elementstr = $this->formatErrors( $elements );
1555 } elseif ( $elements && $elements !==
true ) {
1556 $elementstr = (string)$elements;
1560 if ( !$elementstr ) {
1562 } elseif ( $elementsType ===
'error' ) {
1579 foreach ( $errors as $error ) {
1583 $this->getMessage( $error )->parse()
1600 $this->mSubmitText =
$t;
1612 $this->mSubmitFlags = [
'destructive',
'primary' ];
1626 if ( !$msg instanceof
Message ) {
1627 $msg = $this->msg( $msg );
1629 $this->setSubmitText( $msg->text() );
1639 return $this->mSubmitText ?: $this->msg(
'htmlform-submit' )->text();
1648 $this->mSubmitName = $name;
1659 $this->mSubmitTooltip = $name;
1673 $this->mSubmitID =
$t;
1694 $this->mFormIdentifier = $ident;
1710 $this->mShowSubmit = !$suppressSubmit;
1722 $this->mShowCancel = $show;
1737 $this->mCancelTarget = $target;
1746 if ( is_string( $this->mCancelTarget ) ) {
1747 return $this->mCancelTarget;
1751 return $target->getLocalURL();
1765 $this->mTableId = $id;
1786 $this->mName = $name;
1803 $this->mWrapperLegend = $legend;
1816 $this->mWrapperAttributes = $attributes;
1831 if ( !$msg instanceof
Message ) {
1832 $msg = $this->msg( $msg );
1834 $this->setWrapperLegend( $msg->text() );
1849 $this->mMessagePrefix = $p;
1872 return $this->mTitle ?: $this->
getContext()->getTitle();
1883 $this->mMethod = strtolower( $method );
1892 return $this->mMethod;
1906 return Xml::fieldset( $legend, $section, $attributes ) .
"\n";
1928 $fieldsetIDPrefix =
'',
1929 &$hasUserVisibleFields =
false
1931 if ( $this->mFieldData ===
null ) {
1932 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
1933 .
'You probably called displayForm() without calling prepareForm() first.' );
1936 $displayFormat = $this->getDisplayFormat();
1939 $subsectionHtml =
'';
1944 $getFieldHtmlMethod = $displayFormat ===
'table' ?
'getTableRow' : (
'get' . $displayFormat );
1946 foreach ( $fields as $key => $value ) {
1948 $v = array_key_exists( $key, $this->mFieldData )
1949 ? $this->mFieldData[$key]
1950 : $value->getDefault();
1952 $retval = $value->$getFieldHtmlMethod( $v ??
'' );
1956 if ( $value->hasVisibleOutput() ) {
1959 $labelValue = trim( $value->getLabel() );
1960 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
1964 $hasUserVisibleFields =
true;
1966 } elseif ( is_array( $value ) ) {
1967 $subsectionHasVisibleFields =
false;
1969 $this->displaySection( $value,
1971 "$fieldsetIDPrefix$key-",
1972 $subsectionHasVisibleFields );
1974 if ( $subsectionHasVisibleFields ===
true ) {
1976 $hasUserVisibleFields =
true;
1978 $legend = $this->getLegend( $key );
1980 $section = $this->getHeaderText( $key ) .
1982 $this->getFooterText( $key );
1985 if ( $fieldsetIDPrefix ) {
1988 $subsectionHtml .= $this->wrapFieldSetSection(
1989 $legend, $section, $attributes, $fields === $this->mFieldTree
1993 $subsectionHtml .= $section;
1998 $html = $this->formatSection( $html, $sectionName, $hasLabel );
2000 if ( $subsectionHtml ) {
2001 if ( $this->mSubSectionBeforeFields ) {
2002 return $subsectionHtml .
"\n" . $html;
2004 return $html .
"\n" . $subsectionHtml;
2019 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
2020 if ( !$fieldsHtml ) {
2026 $displayFormat = $this->getDisplayFormat();
2027 $html = implode(
'', $fieldsHtml );
2029 if ( $displayFormat ===
'raw' ) {
2035 if ( !$anyFieldHasLabel ) {
2036 $classes[] =
'mw-htmlform-nolabel';
2039 $attribs = [
'class' => $classes ];
2041 if ( $sectionName ) {
2045 if ( $displayFormat ===
'table' ) {
2049 } elseif ( $displayFormat ===
'inline' ) {
2060 $this->prepareForm();
2070 foreach ( $this->mFlatFields as $fieldname => $field ) {
2071 if ( $field->skipLoadData( $request ) ) {
2074 if ( $field->mParams[
'disabled'] ??
false ) {
2075 $fieldData[$fieldname] = $field->getDefault();
2077 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
2083 foreach ( $fieldData as $name => &$value ) {
2084 $field = $this->mFlatFields[$name];
2085 if ( $field->isDisabled( $fieldData ) ) {
2086 $value = $field->getDefault();
2091 foreach ( $fieldData as $name => &$value ) {
2092 $field = $this->mFlatFields[$name];
2093 $value = $field->filter( $value, $fieldData );
2096 $this->mFieldData = $fieldData;
2107 $this->mShowReset = !$suppressReset;
2136 return $this->msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
2150 $this->mAction = $action;
2164 if ( $this->mAction !==
false ) {
2165 return $this->mAction;
2168 $articlePath = $this->getConfig()->get( MainConfigNames::ArticlePath );
2174 if ( str_contains( $articlePath,
'?' ) && $this->getMethod() ===
'get' ) {
2175 return $this->getConfig()->get( MainConfigNames::Script );
2178 return $this->
getTitle()->getLocalURL();
2192 $this->mAutocomplete = $autocomplete;
2217 foreach ( $this->mFlatFields as $field ) {
2218 if ( $field->needsJSForHtml5FormValidation() ) {
if(!defined('MW_SETUP_CALLBACK'))
The persistent session ID (if any) loaded at startup.
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
setContext(IContextSource $context)
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
static warningBox( $html, $className='')
Return a warning box.
static errorBox( $html, $heading='', $className='')
Return an error box.
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
A class containing constants representing the names of configuration variables.
The Message class deals with fetching and processing of interface message into a variety of formats.
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
static escapeIdForAttribute( $id, $mode=self::ID_PRIMARY)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid HTM...
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.
static newGood( $value=null)
Factory function for good results.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
static castPageToLinkTarget(?PageReference $page)
Casts a PageReference to a LinkTarget.
static castFromPageReference(?PageReference $pageReference)
Return a Title for a given Reference.
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
static castFromLinkTarget( $linkTarget)
Same as newFromLinkTarget, but if passed null, returns null.
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Interface for objects which can provide a MediaWiki context on request.