24 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
156 use ProtectedHookAccessorTrait;
160 'api' => HTMLApiField::class,
161 'text' => HTMLTextField::class,
162 'textwithbutton' => HTMLTextFieldWithButton::class,
163 'textarea' => HTMLTextAreaField::class,
164 'select' => HTMLSelectField::class,
165 'combobox' => HTMLComboboxField::class,
166 'radio' => HTMLRadioField::class,
167 'multiselect' => HTMLMultiSelectField::class,
168 'limitselect' => HTMLSelectLimitField::class,
169 'check' => HTMLCheckField::class,
170 'toggle' => HTMLCheckField::class,
171 'int' => HTMLIntField::class,
172 'file' => HTMLFileField::class,
173 'float' => HTMLFloatField::class,
174 'info' => HTMLInfoField::class,
175 'selectorother' => HTMLSelectOrOtherField::class,
176 'selectandother' => HTMLSelectAndOtherField::class,
177 'namespaceselect' => HTMLSelectNamespace::class,
178 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
179 'tagfilter' => HTMLTagFilter::class,
180 'sizefilter' => HTMLSizeFilterField::class,
181 'submit' => HTMLSubmitField::class,
182 'hidden' => HTMLHiddenField::class,
183 'edittools' => HTMLEditTools::class,
184 'checkmatrix' => HTMLCheckMatrix::class,
185 'cloner' => HTMLFormFieldCloner::class,
186 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
187 'language' => HTMLSelectLanguageField::class,
188 'date' => HTMLDateTimeField::class,
189 'time' => HTMLDateTimeField::class,
190 'datetime' => HTMLDateTimeField::class,
191 'expiry' => HTMLExpiryField::class,
192 'timezone' => HTMLTimezoneField::class,
196 'email' => HTMLTextField::class,
197 'password' => HTMLTextField::class,
198 'url' => HTMLTextField::class,
199 'title' => HTMLTitleTextField::class,
200 'user' => HTMLUserTextField::class,
201 'tagmultiselect' => HTMLTagMultiselectField::class,
202 'usersmultiselect' => HTMLUsersMultiselectField::class,
203 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
204 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
339 private $hiddenTitleAddedToForm =
false;
359 return new VFormHTMLForm( $descriptor, $context, $messagePrefix );
361 return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
363 $form =
new self( $descriptor, $context, $messagePrefix );
384 $this->mMessagePrefix = $messagePrefix;
388 !$this->
getConfig()->
get( MainConfigNames::HTMLFormAllowTableFormat )
389 && $this->displayFormat ===
'table'
391 $this->displayFormat =
'div';
407 $loadedDescriptor = [];
409 foreach ( $descriptor as $fieldname => $info ) {
411 $section = $info[
'section'] ??
'';
413 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
414 $this->mUseMultipart =
true;
417 $field = static::loadInputFromParameters( $fieldname, $info, $this );
419 $setSection =& $loadedDescriptor;
421 foreach ( explode(
'/', $section ) as $newName ) {
422 if ( !isset( $setSection[$newName] ) ) {
423 $setSection[$newName] = [];
426 $setSection =& $setSection[$newName];
430 $setSection[$fieldname] = $field;
431 $this->mFlatFields[$fieldname] = $field;
434 $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
444 return isset( $this->mFlatFields[$fieldname] );
453 if ( !$this->
hasField( $fieldname ) ) {
454 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
456 return $this->mFlatFields[$fieldname];
471 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
472 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
474 throw new MWException(
'Cannot change display format after creation, ' .
475 'use HTMLForm::factory() instead' );
478 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
479 throw new MWException(
'Display format must be one of ' .
482 $this->availableDisplayFormats,
483 $this->availableSubclassDisplayFormats
490 if ( !$this->
getConfig()->
get( MainConfigNames::HTMLFormAllowTableFormat ) &&
491 $format ===
'table' ) {
495 $this->displayFormat = $format;
527 if ( isset( $descriptor[
'class'] ) ) {
528 $class = $descriptor[
'class'];
529 } elseif ( isset( $descriptor[
'type'] ) ) {
530 $class = static::$typeMappings[$descriptor[
'type']];
531 $descriptor[
'class'] = $class;
537 throw new MWException(
"Descriptor with no class for $fieldname: "
538 . print_r( $descriptor,
true ) );
560 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
562 $descriptor[
'fieldname'] = $fieldname;
564 $descriptor[
'parent'] = $parent;
567 # @todo This will throw a fatal error whenever someone try to use
568 # 'class' to feed a CSS class instead of 'cssclass'. Would be
569 # great to avoid the fatal error and show a nice error.
570 return new $class( $descriptor );
583 # Load data from the request.
585 $this->mFormIdentifier ===
null ||
586 $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier
590 $this->mFieldData = [];
603 if ( $this->mFormIdentifier ===
null ) {
612 } elseif ( $this->
getRequest()->wasPosted() ) {
613 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
614 if ( $this->
getUser()->isRegistered() || $editToken !==
null ) {
618 $tokenOkay = $this->
getUser()->matchEditToken( $editToken, $this->mTokenSalt );
624 if ( $tokenOkay && $identOkay ) {
625 $this->mWasSubmitted =
true;
643 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
682 if ( $this->mValidationErrorMessage ) {
683 foreach ( $this->mValidationErrorMessage as $error ) {
684 $hoistedErrors->fatal( ...$error );
687 $hoistedErrors->fatal(
'htmlform-invalid-input' );
690 $this->mWasSubmitted =
true;
692 # Check for cancelled submission
693 foreach ( $this->mFlatFields as $fieldname => $field ) {
694 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
697 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
698 $this->mWasSubmitted =
false;
703 # Check for validation
704 $hasNonDefault =
false;
705 foreach ( $this->mFlatFields as $fieldname => $field ) {
706 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
709 $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
710 if ( $field->isDisabled( $this->mFieldData ) ) {
713 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
714 if (
$res !==
true ) {
716 if (
$res !==
false && !$field->canDisplayErrors() ) {
717 if ( is_string(
$res ) ) {
718 $hoistedErrors->fatal(
'rawmessage',
$res );
720 $hoistedErrors->fatal(
$res );
728 if ( !$hasNonDefault && $this->
getMethod() ===
'get' &&
729 ( $this->mFormIdentifier ===
null ||
730 $this->
getRequest()->getCheck(
'wpFormIdentifier' ) )
732 $this->mWasSubmitted =
false;
735 return $hoistedErrors;
739 if ( !is_callable( $callback ) ) {
740 throw new MWException(
'HTMLForm: no submit callback provided. Use ' .
741 'setSubmitCallback() to set one.' );
746 $res = call_user_func( $callback, $data, $this );
747 if (
$res ===
false ) {
748 $this->mWasSubmitted =
false;
783 $this->mSubmitCallback = $cb;
798 $this->mValidationErrorMessage = $msg;
838 $this->mPre .= $html;
898 if ( $section ===
null ) {
899 $this->mHeader .= $html;
901 if ( !isset( $this->mSectionHeaders[$section] ) ) {
902 $this->mSectionHeaders[$section] =
'';
904 $this->mSectionHeaders[$section] .= $html;
920 if ( $section ===
null ) {
921 $this->mHeader = $html;
923 $this->mSectionHeaders[$section] = $html;
938 if ( $section ===
null ) {
941 return $this->mSectionHeaders[$section] ??
'';
995 if ( $section ===
null ) {
996 $this->mFooter .= $html;
998 if ( !isset( $this->mSectionFooters[$section] ) ) {
999 $this->mSectionFooters[$section] =
'';
1001 $this->mSectionFooters[$section] .= $html;
1017 if ( $section ===
null ) {
1018 $this->mFooter = $html;
1020 $this->mSectionFooters[$section] = $html;
1034 if ( $section ===
null ) {
1037 return $this->mSectionFooters[$section] ??
'';
1089 $this->mPost .= $html;
1103 $this->mPost = $html;
1153 if ( !is_array( $value ) ) {
1155 $attribs += [
'name' => $name ];
1156 $this->mHiddenFields[] = [ $value, $attribs ];
1174 foreach ( $fields as $name => $value ) {
1175 if ( is_array( $value ) ) {
1179 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1209 if ( !is_array( $data ) ) {
1210 $args = func_get_args();
1211 if ( count( $args ) < 2 || count( $args ) > 4 ) {
1212 throw new InvalidArgumentException(
1213 'Incorrect number of arguments for deprecated calling style'
1218 'value' => $args[1],
1219 'id' => $args[2] ??
null,
1220 'attribs' => $args[3] ??
null,
1223 if ( !isset( $data[
'name'] ) ) {
1224 throw new InvalidArgumentException(
'A name is required' );
1226 if ( !isset( $data[
'value'] ) ) {
1227 throw new InvalidArgumentException(
'A value is required' );
1230 $this->mButtons[] = $data + [
1250 $this->mTokenSalt = $salt;
1277 private function getHiddenTitle(): string {
1278 if ( $this->hiddenTitleAddedToForm ) {
1286 $html .= Html::hidden(
'title', $this->
getTitle()->getPrefixedText() ) .
"\n";
1288 $this->hiddenTitleAddedToForm =
true;
1303 # For good measure (it is the default)
1304 $this->getOutput()->setPreventClickjacking(
true );
1305 $this->getOutput()->addModules(
'mediawiki.htmlform' );
1306 $this->getOutput()->addModuleStyles(
'mediawiki.htmlform.styles' );
1308 if ( $this->mCollapsible ) {
1310 $this->getOutput()->addModules(
'jquery.makeCollapsible' );
1314 . $this->getErrorsOrWarnings( $submitResult,
'error' )
1315 . $this->getErrorsOrWarnings( $submitResult,
'warning' )
1316 . $this->getHeaderText()
1317 . $this->getHiddenTitle()
1319 . $this->getHiddenFields()
1320 . $this->getButtons()
1321 . $this->getFooterText();
1323 $html = $this->wrapForm( $html );
1325 return '' . $this->mPre . $html . $this->mPost;
1336 $this->mCollapsible =
true;
1337 $this->mCollapsed = $collapsedByDefault;
1347 # Use multipart/form-data
1348 $encType = $this->mUseMultipart
1349 ?
'multipart/form-data'
1350 :
'application/x-www-form-urlencoded';
1353 'class' =>
'mw-htmlform',
1354 'action' => $this->getAction(),
1355 'method' => $this->getMethod(),
1356 'enctype' => $encType,
1359 $attribs[
'id'] = $this->mId;
1361 if ( is_string( $this->mAutocomplete ) ) {
1362 $attribs[
'autocomplete'] = $this->mAutocomplete;
1364 if ( $this->mName ) {
1365 $attribs[
'name'] = $this->mName;
1367 if ( $this->needsJSForHtml5FormValidation() ) {
1368 $attribs[
'novalidate'] =
true;
1381 # Include a <fieldset> wrapper for style, if requested.
1382 if ( $this->mWrapperLegend !==
false ) {
1383 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1384 $html =
Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1387 return Html::rawElement(
1389 $this->getFormAttributes(),
1403 $html .= $this->getHiddenTitle();
1405 if ( $this->mFormIdentifier !==
null ) {
1406 $html .= Html::hidden(
1408 $this->mFormIdentifier
1411 if ( $this->getMethod() ===
'post' ) {
1412 $html .= Html::hidden(
1414 $this->
getUser()->getEditToken( $this->mTokenSalt ),
1415 [
'id' =>
'wpEditToken' ]
1419 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1420 $html .= Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1433 $useMediaWikiUIEverywhere =
1434 $this->getConfig()->get( MainConfigNames::UseMediaWikiUIEverywhere );
1436 if ( $this->mShowSubmit ) {
1439 if ( isset( $this->mSubmitID ) ) {
1440 $attribs[
'id'] = $this->mSubmitID;
1443 if ( isset( $this->mSubmitName ) ) {
1444 $attribs[
'name'] = $this->mSubmitName;
1447 if ( isset( $this->mSubmitTooltip ) ) {
1448 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1451 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1453 if ( $useMediaWikiUIEverywhere ) {
1454 foreach ( $this->mSubmitFlags as $flag ) {
1455 $attribs[
'class'][] =
'mw-ui-' . $flag;
1457 $attribs[
'class'][] =
'mw-ui-button';
1463 if ( $this->mShowReset ) {
1464 $buttons .= Html::element(
1468 'value' => $this->msg(
'htmlform-reset' )->text(),
1469 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' :
null,
1474 if ( $this->mShowCancel ) {
1475 $target = $this->getCancelTargetURL();
1476 $buttons .= Html::element(
1479 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' :
null,
1482 $this->msg(
'cancel' )->text()
1486 foreach ( $this->mButtons as $button ) {
1489 'name' => $button[
'name'],
1490 'value' => $button[
'value']
1493 if ( isset( $button[
'label-message'] ) ) {
1494 $label = $this->getMessage( $button[
'label-message'] )->parse();
1495 } elseif ( isset( $button[
'label'] ) ) {
1496 $label = htmlspecialchars( $button[
'label'] );
1497 } elseif ( isset( $button[
'label-raw'] ) ) {
1498 $label = $button[
'label-raw'];
1500 $label = htmlspecialchars( $button[
'value'] );
1504 if ( $button[
'attribs'] ) {
1506 $attrs += $button[
'attribs'];
1509 if ( isset( $button[
'id'] ) ) {
1510 $attrs[
'id'] = $button[
'id'];
1513 if ( $useMediaWikiUIEverywhere ) {
1514 $attrs[
'class'] = isset( $attrs[
'class'] ) ? (array)$attrs[
'class'] : [];
1515 $attrs[
'class'][] =
'mw-ui-button';
1518 $buttons .= Html::rawElement(
'button', $attrs, $label ) .
"\n";
1525 return Html::rawElement(
'span',
1526 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1535 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1548 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1549 throw new DomainException( $elementsType .
' is not a valid type.' );
1551 $elementstr =
false;
1552 if ( $elements instanceof
Status ) {
1553 [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1554 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1555 if ( $status->isGood() ) {
1558 $elementstr = $status
1560 ->setContext( $this )
1561 ->setInterfaceMessageFlag(
true )
1564 } elseif ( $elementsType ===
'error' ) {
1565 if ( is_array( $elements ) ) {
1566 $elementstr = $this->formatErrors( $elements );
1567 } elseif ( $elements && $elements !==
true ) {
1568 $elementstr = (string)$elements;
1572 if ( !$elementstr ) {
1574 } elseif ( $elementsType ===
'error' ) {
1575 return Html::errorBox( $elementstr );
1577 return Html::warningBox( $elementstr );
1591 foreach ( $errors as $error ) {
1592 $errorstr .= Html::rawElement(
1595 $this->getMessage( $error )->parse()
1599 $errorstr = Html::rawElement(
'ul', [], $errorstr );
1612 $this->mSubmitText =
$t;
1624 $this->mSubmitFlags = [
'destructive',
'primary' ];
1638 if ( !$msg instanceof
Message ) {
1639 $msg = $this->msg( $msg );
1641 $this->setSubmitText( $msg->text() );
1651 return $this->mSubmitText ?: $this->msg(
'htmlform-submit' )->text();
1660 $this->mSubmitName = $name;
1671 $this->mSubmitTooltip = $name;
1685 $this->mSubmitID =
$t;
1706 $this->mFormIdentifier = $ident;
1722 $this->mShowSubmit = !$suppressSubmit;
1734 $this->mShowCancel = $show;
1749 $this->mCancelTarget = $target;
1758 if ( is_string( $this->mCancelTarget ) ) {
1759 return $this->mCancelTarget;
1762 $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1763 return $target->getLocalURL();
1777 $this->mTableId = $id;
1798 $this->mName = $name;
1815 $this->mWrapperLegend = $legend;
1828 $this->mWrapperAttributes = $attributes;
1843 if ( !$msg instanceof
Message ) {
1844 $msg = $this->msg( $msg );
1846 $this->setWrapperLegend( $msg->text() );
1861 $this->mMessagePrefix = $p;
1875 $this->mTitle = Title::castFromPageReference(
$t );
1884 return $this->mTitle ?: $this->
getContext()->getTitle();
1895 $this->mMethod = strtolower( $method );
1904 return $this->mMethod;
1918 return Xml::fieldset( $legend, $section, $attributes ) .
"\n";
1940 $fieldsetIDPrefix =
'',
1941 &$hasUserVisibleFields =
false
1943 if ( $this->mFieldData ===
null ) {
1944 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
1945 .
'You probably called displayForm() without calling prepareForm() first.' );
1948 $displayFormat = $this->getDisplayFormat();
1951 $subsectionHtml =
'';
1956 $getFieldHtmlMethod = $displayFormat ===
'table' ?
'getTableRow' : (
'get' . $displayFormat );
1958 foreach ( $fields as $key => $value ) {
1960 $v = array_key_exists( $key, $this->mFieldData )
1961 ? $this->mFieldData[$key]
1962 : $value->getDefault();
1964 $retval = $value->$getFieldHtmlMethod( $v ??
'' );
1968 if ( $value->hasVisibleOutput() ) {
1971 $labelValue = trim( $value->getLabel() );
1972 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
1976 $hasUserVisibleFields =
true;
1978 } elseif ( is_array( $value ) ) {
1979 $subsectionHasVisibleFields =
false;
1981 $this->displaySection( $value,
1983 "$fieldsetIDPrefix$key-",
1984 $subsectionHasVisibleFields );
1986 if ( $subsectionHasVisibleFields ===
true ) {
1988 $hasUserVisibleFields =
true;
1990 $legend = $this->getLegend( $key );
1992 $section = $this->getHeaderText( $key ) .
1994 $this->getFooterText( $key );
1997 if ( $fieldsetIDPrefix ) {
2000 $subsectionHtml .= $this->wrapFieldSetSection(
2001 $legend, $section, $attributes, $fields === $this->mFieldTree
2005 $subsectionHtml .= $section;
2010 $html = $this->formatSection( $html, $sectionName, $hasLabel );
2012 if ( $subsectionHtml ) {
2013 if ( $this->mSubSectionBeforeFields ) {
2014 return $subsectionHtml .
"\n" . $html;
2016 return $html .
"\n" . $subsectionHtml;
2031 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
2032 if ( !$fieldsHtml ) {
2038 $displayFormat = $this->getDisplayFormat();
2039 $html = implode(
'', $fieldsHtml );
2041 if ( $displayFormat ===
'raw' ) {
2047 if ( !$anyFieldHasLabel ) {
2048 $classes[] =
'mw-htmlform-nolabel';
2051 $attribs = [
'class' => $classes ];
2053 if ( $sectionName ) {
2057 if ( $displayFormat ===
'table' ) {
2058 return Html::rawElement(
'table',
2060 Html::rawElement(
'tbody', [],
"\n$html\n" ) ) .
"\n";
2061 } elseif ( $displayFormat ===
'inline' ) {
2062 return Html::rawElement(
'span', $attribs,
"\n$html\n" );
2064 return Html::rawElement(
'div', $attribs,
"\n$html\n" );
2072 $this->prepareForm();
2082 foreach ( $this->mFlatFields as $fieldname => $field ) {
2083 if ( $field->skipLoadData( $request ) ) {
2086 if ( $field->mParams[
'disabled'] ??
false ) {
2087 $fieldData[$fieldname] = $field->getDefault();
2089 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
2095 foreach ( $fieldData as $name => &$value ) {
2096 $field = $this->mFlatFields[$name];
2097 if ( $field->isDisabled( $fieldData ) ) {
2098 $value = $field->getDefault();
2103 foreach ( $fieldData as $name => &$value ) {
2104 $field = $this->mFlatFields[$name];
2105 $value = $field->filter( $value, $fieldData );
2108 $this->mFieldData = $fieldData;
2119 $this->mShowReset = !$suppressReset;
2148 return $this->msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
2162 $this->mAction = $action;
2176 if ( $this->mAction !==
false ) {
2177 return $this->mAction;
2180 $articlePath = $this->getConfig()->get( MainConfigNames::ArticlePath );
2186 if ( str_contains( $articlePath,
'?' ) && $this->getMethod() ===
'get' ) {
2187 return $this->getConfig()->get( MainConfigNames::Script );
2190 return $this->
getTitle()->getLocalURL();
2204 $this->mAutocomplete = $autocomplete;
2229 foreach ( $this->mFlatFields as $field ) {
2230 if ( $field->needsJSForHtml5FormValidation() ) {
if(!defined('MW_SETUP_CALLBACK'))
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
setContext(IContextSource $context)
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 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.