13use InvalidArgumentException;
17use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
215 use ProtectedHookAccessorTrait;
219 'api' => HTMLApiField::class,
220 'text' => HTMLTextField::class,
221 'textwithbutton' => HTMLTextFieldWithButton::class,
222 'textarea' => HTMLTextAreaField::class,
223 'select' => HTMLSelectField::class,
224 'combobox' => HTMLComboboxField::class,
225 'radio' => HTMLRadioField::class,
226 'multiselect' => HTMLMultiSelectField::class,
227 'limitselect' => HTMLSelectLimitField::class,
228 'check' => HTMLCheckField::class,
229 'toggle' => HTMLCheckField::class,
230 'int' => HTMLIntField::class,
231 'file' => HTMLFileField::class,
232 'float' => HTMLFloatField::class,
233 'info' => HTMLInfoField::class,
234 'selectorother' => HTMLSelectOrOtherField::class,
235 'selectandother' => HTMLSelectAndOtherField::class,
236 'namespaceselect' => HTMLSelectNamespace::class,
237 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
238 'tagfilter' => HTMLTagFilter::class,
239 'sizefilter' => HTMLSizeFilterField::class,
240 'button' => HTMLButtonField::class,
241 'submit' => HTMLSubmitField::class,
242 'hidden' => HTMLHiddenField::class,
243 'edittools' => HTMLEditTools::class,
244 'checkmatrix' => HTMLCheckMatrix::class,
245 'cloner' => HTMLFormFieldCloner::class,
246 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
247 'language' => HTMLSelectLanguageField::class,
248 'date' => HTMLDateTimeField::class,
249 'time' => HTMLDateTimeField::class,
250 'datetime' => HTMLDateTimeField::class,
251 'expiry' => HTMLExpiryField::class,
252 'timezone' => HTMLTimezoneField::class,
256 'email' => HTMLTextField::class,
257 'password' => HTMLTextField::class,
258 'url' => HTMLTextField::class,
259 'title' => HTMLTitleTextField::class,
260 'user' => HTMLUserTextField::class,
261 'tagmultiselect' => HTMLTagMultiselectField::class,
262 'orderedmultiselect' => HTMLOrderedMultiselectField::class,
263 'usersmultiselect' => HTMLUsersMultiselectField::class,
264 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
265 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
442 private $hiddenTitleAddedToForm =
false;
462 return new CodexHTMLForm( $descriptor, $context, $messagePrefix );
464 return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
466 $form =
new self( $descriptor, $context, $messagePrefix );
487 $this->mMessagePrefix = $messagePrefix;
501 $loadedDescriptor = [];
503 foreach ( $descriptor as $fieldname => $info ) {
504 $section = $info[
'section'] ??
'';
506 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
507 $this->mUseMultipart =
true;
510 $field = static::loadInputFromParameters( $fieldname, $info, $this );
512 $setSection =& $loadedDescriptor;
514 foreach ( explode(
'/', $section ) as $newName ) {
515 $setSection[$newName] ??= [];
516 $setSection =& $setSection[$newName];
520 $setSection[$fieldname] = $field;
521 $this->mFlatFields[$fieldname] = $field;
524 $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
534 return isset( $this->mFlatFields[$fieldname] );
543 if ( !$this->
hasField( $fieldname ) ) {
544 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
546 return $this->mFlatFields[$fieldname];
560 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
561 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
563 throw new LogicException(
'Cannot change display format after creation, ' .
564 'use HTMLForm::factory() instead' );
567 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
568 throw new InvalidArgumentException(
'Display format must be one of ' .
571 $this->availableDisplayFormats,
572 $this->availableSubclassDisplayFormats
578 $this->displayFormat = $format;
609 if ( isset( $descriptor[
'class'] ) ) {
610 $class = $descriptor[
'class'];
611 } elseif ( isset( $descriptor[
'type'] ) ) {
612 $class = static::$typeMappings[$descriptor[
'type']];
613 $descriptor[
'class'] = $class;
619 throw new InvalidArgumentException(
"Descriptor with no class for $fieldname: "
620 . print_r( $descriptor,
true ) );
638 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
640 $descriptor[
'fieldname'] = $fieldname;
641 $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 $this->mWasSubmitted =
true;
693 if ( $this->mFormIdentifier === null ) {
702 } elseif ( $this->
getRequest()->wasPosted() ) {
703 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
704 if ( $this->
getUser()->isRegistered() || $editToken !==
null ) {
709 CsrfTokenSet::DEFAULT_FIELD_NAME, $this->mTokenSalt
715 return $identOkay && $tokenOkay;
726 $this->prepareForm();
728 $result = $this->tryAuthorizedSubmit();
729 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
733 $this->displayForm( $result );
744 $this->prepareForm();
746 $result = $this->tryAuthorizedSubmit();
748 $this->displayForm( $result );
766 $hoistedErrors = Status::newGood();
767 if ( $this->mValidationErrorMessage ) {
768 foreach ( $this->mValidationErrorMessage as $error ) {
769 $hoistedErrors->fatal( ...$error );
772 $hoistedErrors->fatal(
'htmlform-invalid-input' );
775 $this->mWasSubmitted =
true;
777 # Check for cancelled submission
778 foreach ( $this->mFlatFields as $fieldname => $field ) {
779 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
782 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
783 $this->mWasSubmitted =
false;
788 # Check for validation
789 $hasNonDefault =
false;
790 foreach ( $this->mFlatFields as $fieldname => $field ) {
791 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
794 $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
795 if ( $field->isDisabled( $this->mFieldData ) ) {
798 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
799 if ( $res !==
true ) {
801 if ( $res !==
false && !$field->canDisplayErrors() ) {
802 if ( is_string( $res ) ) {
803 $hoistedErrors->fatal(
'rawmessage', $res );
805 $hoistedErrors->fatal( $res );
813 if ( !$hasNonDefault && $this->getMethod() ===
'get' &&
814 ( $this->mFormIdentifier ===
null ||
815 $this->getRequest()->getCheck(
'wpFormIdentifier' ) )
817 $this->mWasSubmitted =
false;
820 return $hoistedErrors;
823 $callback = $this->mSubmitCallback;
824 if ( !is_callable( $callback ) ) {
825 throw new LogicException(
'HTMLForm: no submit callback provided. Use ' .
826 'setSubmitCallback() to set one.' );
829 $data = $this->filterDataForSubmit( $this->mFieldData );
831 $res = $callback( $data, $this );
832 if ( $res ===
false ) {
833 $this->mWasSubmitted =
false;
836 $res = Status::wrap( $res );
854 return $this->mWasSubmitted;
868 $this->mSubmitCallback = $cb;
883 $this->mValidationErrorMessage = $msg;
911 $this->mPre .= $html;
936 if ( $section ===
null ) {
937 $this->mHeader .= $html;
939 $this->mSectionHeaders[$section] ??=
'';
940 $this->mSectionHeaders[$section] .= $html;
956 if ( $section ===
null ) {
957 $this->mHeader = $html;
959 $this->mSectionHeaders[$section] = $html;
974 return $section ? $this->mSectionHeaders[$section] ??
'' : $this->mHeader;
987 if ( $section ===
null ) {
988 $this->mFooter .= $html;
990 $this->mSectionFooters[$section] ??=
'';
991 $this->mSectionFooters[$section] .= $html;
1007 if ( $section ===
null ) {
1008 $this->mFooter = $html;
1010 $this->mSectionFooters[$section] = $html;
1024 return $section ? $this->mSectionFooters[$section] ??
'' : $this->mFooter;
1036 $this->mPost .= $html;
1050 $this->mPost = $html;
1062 return $this->mPost;
1075 if ( $this->getDisplayFormat() !==
'codex' ) {
1076 throw new \InvalidArgumentException(
1077 "Non-Codex HTMLForms do not support additional section information."
1081 $this->mSections = $sections;
1097 if ( !is_array( $value ) ) {
1099 $attribs += [
'name' => $name ];
1100 $this->mHiddenFields[] = [ $value, $attribs ];
1118 foreach ( $fields as $name => $value ) {
1119 if ( is_array( $value ) ) {
1123 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1153 if ( !is_array( $data ) ) {
1154 $args = func_get_args();
1155 if ( count( $args ) < 2 || count( $args ) > 4 ) {
1156 throw new InvalidArgumentException(
1157 'Incorrect number of arguments for deprecated calling style'
1162 'value' => $args[1],
1163 'id' => $args[2] ??
null,
1164 'attribs' => $args[3] ??
null,
1167 if ( !isset( $data[
'name'] ) ) {
1168 throw new InvalidArgumentException(
'A name is required' );
1170 if ( !isset( $data[
'value'] ) ) {
1171 throw new InvalidArgumentException(
'A value is required' );
1174 $this->mButtons[] = $data + [
1194 $this->mTokenSalt = $salt;
1214 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1220 private function getHiddenTitle(): string {
1221 if ( $this->hiddenTitleAddedToForm ) {
1226 if ( $this->getMethod() ===
'post' ||
1229 $html .= Html::hidden(
'title', $this->getTitle()->getPrefixedText() ) .
"\n";
1231 $this->hiddenTitleAddedToForm =
true;
1246 # For good measure (it is the default)
1247 $this->getOutput()->getMetadata()->setPreventClickjacking(
true );
1248 $this->getOutput()->addModules(
'mediawiki.htmlform' );
1249 $this->getOutput()->addModuleStyles( [
1250 'mediawiki.htmlform.styles',
1252 'mediawiki.codex.messagebox.styles'
1255 if ( $this->mCollapsible ) {
1257 $this->getOutput()->addModules(
'jquery.makeCollapsible' );
1260 $headerHtml = $this->getHeaderHtml();
1261 $footerHtml = $this->getFooterHtml();
1262 $html = $this->getErrorsOrWarnings( $submitResult,
'error' )
1263 . $this->getErrorsOrWarnings( $submitResult,
'warning' )
1265 . $this->getHiddenTitle()
1267 . $this->getHiddenFields()
1268 . $this->getButtons()
1271 return $this->mPre . $this->wrapForm( $html ) . $this->mPost;
1282 $this->mCollapsible =
true;
1283 $this->mCollapsed = $collapsedByDefault;
1293 # Use multipart/form-data
1294 $encType = $this->mUseMultipart
1295 ?
'multipart/form-data'
1296 :
'application/x-www-form-urlencoded';
1299 'class' =>
'mw-htmlform',
1300 'action' => $this->getAction(),
1301 'method' => $this->getMethod(),
1302 'enctype' => $encType,
1305 $attribs[
'id'] = $this->mId;
1307 if ( is_string( $this->mAutocomplete ) ) {
1308 $attribs[
'autocomplete'] = $this->mAutocomplete;
1310 if ( $this->mName ) {
1311 $attribs[
'name'] = $this->mName;
1313 if ( $this->needsJSForHtml5FormValidation() ) {
1314 $attribs[
'novalidate'] =
true;
1327 # Include a <fieldset> wrapper for style, if requested.
1328 if ( $this->mWrapperLegend !==
false ) {
1329 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1330 $html = Html::rawElement(
1332 $this->mWrapperAttributes,
1333 ( $legend ? Html::element(
'legend', [], $legend ) :
'' ) . $html
1337 return Html::rawElement(
1339 $this->getFormAttributes(),
1353 $html .= $this->getHiddenTitle();
1355 if ( $this->mFormIdentifier !==
null ) {
1356 $html .= Html::hidden(
1358 $this->mFormIdentifier
1361 if ( $this->getMethod() ===
'post' ) {
1362 $html .= Html::hidden(
1364 $this->getUser()->getEditToken( $this->mTokenSalt ),
1365 [
'id' =>
'wpEditToken' ]
1369 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1370 $html .= Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1384 if ( $this->mShowSubmit ) {
1387 if ( $this->mSubmitID !==
null ) {
1388 $attribs[
'id'] = $this->mSubmitID;
1391 if ( $this->mSubmitName !==
null ) {
1392 $attribs[
'name'] = $this->mSubmitName;
1395 if ( $this->mSubmitTooltip !==
null ) {
1396 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1399 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1401 $buttons .= Html::submitButton( $this->getSubmitText(), $attribs ) .
"\n";
1404 if ( $this->mShowCancel ) {
1405 $target = $this->getCancelTargetURL();
1406 $buttons .= Html::element(
1411 $this->msg(
'cancel' )->text()
1415 foreach ( $this->mButtons as $button ) {
1418 'name' => $button[
'name'],
1419 'value' => $button[
'value']
1422 if ( isset( $button[
'label-message'] ) ) {
1423 $label = $this->getMessage( $button[
'label-message'] )->parse();
1424 } elseif ( isset( $button[
'label'] ) ) {
1425 $label = htmlspecialchars( $button[
'label'] );
1426 } elseif ( isset( $button[
'label-raw'] ) ) {
1427 $label = $button[
'label-raw'];
1429 $label = htmlspecialchars( $button[
'value'] );
1433 if ( $button[
'attribs'] ) {
1434 $attrs += $button[
'attribs'];
1437 if ( isset( $button[
'id'] ) ) {
1438 $attrs[
'id'] = $button[
'id'];
1441 $buttons .= Html::rawElement(
'button', $attrs, $label ) .
"\n";
1448 return Html::rawElement(
'span',
1449 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1458 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1471 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1472 throw new DomainException( $elementsType .
' is not a valid type.' );
1474 $elementstr =
false;
1475 if ( $elements instanceof
Status ) {
1476 [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1477 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1478 if ( $status->isGood() ) {
1481 $elementstr = $status
1483 ->setContext( $this )
1484 ->setInterfaceMessageFlag(
true )
1487 } elseif ( $elementsType ===
'error' ) {
1488 if ( is_array( $elements ) ) {
1489 $elementstr = $this->formatErrors( $elements );
1490 } elseif ( $elements && $elements !==
true ) {
1491 $elementstr = (string)$elements;
1495 if ( !$elementstr ) {
1497 } elseif ( $elementsType ===
'error' ) {
1498 return Html::errorBox( $elementstr );
1500 return Html::warningBox( $elementstr );
1514 foreach ( $errors as $error ) {
1515 $errorstr .= Html::rawElement(
1518 $this->getMessage( $error )->parse()
1522 return Html::rawElement(
'ul', [], $errorstr );
1534 $this->mSubmitText = $t;
1546 $this->mSubmitFlags = [
'destructive',
'primary' ];
1560 if ( !$msg instanceof
Message ) {
1561 $msg = $this->msg( $msg );
1563 $this->setSubmitText( $msg->text() );
1573 return $this->mSubmitText ?: $this->msg(
'htmlform-submit' )->text();
1582 $this->mSubmitName = $name;
1593 $this->mSubmitTooltip = $name;
1607 $this->mSubmitID = $t;
1631 $this->mFormIdentifier = $ident;
1632 $this->mSingleForm = $single;
1648 $this->mShowSubmit = !$suppressSubmit;
1660 $this->mShowCancel = $show;
1672 $target = TitleValue::castPageToLinkTarget( $target );
1675 $this->mCancelTarget = $target;
1684 if ( is_string( $this->mCancelTarget ) ) {
1685 return $this->mCancelTarget;
1688 $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1689 return $target->getLocalURL();
1703 $this->mTableId = $id;
1724 $this->mName = $name;
1742 $this->mWrapperLegend = $legend;
1755 $this->mWrapperAttributes = $attributes;
1770 if ( !$msg instanceof
Message ) {
1771 $msg = $this->msg( $msg );
1773 $this->setWrapperLegend( $msg->text() );
1788 $this->mMessagePrefix = $p;
1802 $this->mTitle = Title::castFromPageReference( $t );
1811 return $this->mTitle ?: $this->getContext()->getTitle();
1822 $this->mMethod = strtolower( $method );
1831 return $this->mMethod;
1845 return Html::rawElement(
1848 Html::element(
'legend', [], $legend ) . $section
1872 $fieldsetIDPrefix =
'',
1873 &$hasUserVisibleFields =
false
1875 if ( $this->mFieldData ===
null ) {
1876 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
1877 .
'You probably called displayForm() without calling prepareForm() first.' );
1881 $subsectionHtml =
'';
1884 foreach ( $fields as $key => $value ) {
1886 $v = array_key_exists( $key, $this->mFieldData )
1887 ? $this->mFieldData[$key]
1888 : $value->getDefault();
1890 $retval = $this->formatField( $value, $v ??
'' );
1894 if ( $value->hasVisibleOutput() ) {
1897 $labelValue = trim( $value->getLabel() );
1898 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
1902 $hasUserVisibleFields =
true;
1904 } elseif ( is_array( $value ) ) {
1905 $subsectionHasVisibleFields =
false;
1907 $this->displaySection( $value,
1909 "$fieldsetIDPrefix$key-",
1910 $subsectionHasVisibleFields );
1912 if ( $subsectionHasVisibleFields ===
true ) {
1914 $hasUserVisibleFields =
true;
1916 $legend = $this->getLegend( $key );
1918 $headerHtml = $this->getHeaderHtml( $key );
1919 $footerHtml = $this->getFooterHtml( $key );
1920 $section = $headerHtml .
1925 if ( $fieldsetIDPrefix ) {
1926 $attributes[
'id'] = Sanitizer::escapeIdForAttribute(
"$fieldsetIDPrefix$key" );
1928 $subsectionHtml .= $this->wrapFieldSetSection(
1929 $legend, $section, $attributes, $fields === $this->mFieldTree
1933 $subsectionHtml .= $section;
1938 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1940 if ( $subsectionHtml ) {
1941 if ( $this->mSubSectionBeforeFields ) {
1942 return $subsectionHtml .
"\n" . $html;
1944 return $html .
"\n" . $subsectionHtml;
1960 $displayFormat = $this->getDisplayFormat();
1961 switch ( $displayFormat ) {
1965 return $field->
getDiv( $value );
1967 return $field->
getRaw( $value );
1971 throw new LogicException(
'Not implemented' );
1983 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1984 if ( !$fieldsHtml ) {
1990 $displayFormat = $this->getDisplayFormat();
1991 $html = implode(
'', $fieldsHtml );
1993 if ( $displayFormat ===
'raw' ) {
1998 $attribs = $anyFieldHasLabel ? [] : [
'class' =>
'mw-htmlform-nolabel' ];
2000 if ( $sectionName ) {
2001 $attribs[
'id'] = Sanitizer::escapeIdForAttribute( $sectionName );
2004 if ( $displayFormat ===
'table' ) {
2005 return Html::rawElement(
'table',
2007 Html::rawElement(
'tbody', [],
"\n$html\n" ) ) .
"\n";
2008 } elseif ( $displayFormat ===
'inline' ) {
2009 return Html::rawElement(
'span', $attribs,
"\n$html\n" );
2011 return Html::rawElement(
'div', $attribs,
"\n$html\n" );
2019 $this->prepareForm();
2029 foreach ( $this->mFlatFields as $fieldname => $field ) {
2030 if ( $field->skipLoadData(
$request ) ) {
2033 if ( $field->mParams[
'disabled'] ??
false ) {
2034 $fieldData[$fieldname] = $field->getDefault();
2036 $fieldData[$fieldname] = $field->loadDataFromRequest(
$request );
2042 foreach ( $fieldData as $name => &$value ) {
2043 $field = $this->mFlatFields[$name];
2044 if ( $field->isDisabled( $fieldData ) ) {
2045 $value = $field->getDefault();
2050 foreach ( $fieldData as $name => &$value ) {
2051 $field = $this->mFlatFields[$name];
2052 $value = $field->filter( $value, $fieldData );
2055 $this->mFieldData = $fieldData;
2082 return $this->msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
2096 $this->mAction = $action;
2110 if ( $this->mAction !==
false ) {
2111 return $this->mAction;
2114 $articlePath = $this->getConfig()->get( MainConfigNames::ArticlePath );
2120 if ( str_contains( $articlePath,
'?' ) && $this->getMethod() ===
'get' ) {
2121 return $this->getConfig()->get( MainConfigNames::Script );
2124 return $this->getTitle()->getLocalURL();
2138 $this->mAutocomplete = $autocomplete;
2150 return Message::newFromSpecifier( $value )->setContext( $this );
2163 foreach ( $this->mFlatFields as $field ) {
2164 if ( $field->needsJSForHtml5FormValidation() ) {
2173class_alias( HTMLForm::class,
'HTMLForm' );
if(!defined('MW_SETUP_CALLBACK'))
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
getCsrfTokenSet()
Get a repository to obtain and match CSRF tokens.
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 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.