27use InvalidArgumentException;
31use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
210 use ProtectedHookAccessorTrait;
214 'api' => HTMLApiField::class,
215 'text' => HTMLTextField::class,
216 'textwithbutton' => HTMLTextFieldWithButton::class,
217 'textarea' => HTMLTextAreaField::class,
218 'select' => HTMLSelectField::class,
219 'combobox' => HTMLComboboxField::class,
220 'radio' => HTMLRadioField::class,
221 'multiselect' => HTMLMultiSelectField::class,
222 'limitselect' => HTMLSelectLimitField::class,
223 'check' => HTMLCheckField::class,
224 'toggle' => HTMLCheckField::class,
225 'int' => HTMLIntField::class,
226 'file' => HTMLFileField::class,
227 'float' => HTMLFloatField::class,
228 'info' => HTMLInfoField::class,
229 'selectorother' => HTMLSelectOrOtherField::class,
230 'selectandother' => HTMLSelectAndOtherField::class,
231 'namespaceselect' => HTMLSelectNamespace::class,
232 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
233 'tagfilter' => HTMLTagFilter::class,
234 'sizefilter' => HTMLSizeFilterField::class,
235 'submit' => HTMLSubmitField::class,
236 'hidden' => HTMLHiddenField::class,
237 'edittools' => HTMLEditTools::class,
238 'checkmatrix' => HTMLCheckMatrix::class,
239 'cloner' => HTMLFormFieldCloner::class,
240 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
241 'language' => HTMLSelectLanguageField::class,
242 'date' => HTMLDateTimeField::class,
243 'time' => HTMLDateTimeField::class,
244 'datetime' => HTMLDateTimeField::class,
245 'expiry' => HTMLExpiryField::class,
246 'timezone' => HTMLTimezoneField::class,
250 'email' => HTMLTextField::class,
251 'password' => HTMLTextField::class,
252 'url' => HTMLTextField::class,
253 'title' => HTMLTitleTextField::class,
254 'user' => HTMLUserTextField::class,
255 'tagmultiselect' => HTMLTagMultiselectField::class,
256 'orderedmultiselect' => HTMLOrderedMultiselectField::class,
257 'usersmultiselect' => HTMLUsersMultiselectField::class,
258 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
259 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
437 private $hiddenTitleAddedToForm =
false;
457 return new CodexHTMLForm( $descriptor, $context, $messagePrefix );
459 return new VFormHTMLForm( $descriptor, $context, $messagePrefix );
461 return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
463 $form =
new self( $descriptor, $context, $messagePrefix );
484 $this->mMessagePrefix = $messagePrefix;
498 $loadedDescriptor = [];
500 foreach ( $descriptor as $fieldname => $info ) {
501 $section = $info[
'section'] ??
'';
503 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
504 $this->mUseMultipart =
true;
507 $field = static::loadInputFromParameters( $fieldname, $info, $this );
509 $setSection =& $loadedDescriptor;
511 foreach ( explode(
'/', $section ) as $newName ) {
512 $setSection[$newName] ??= [];
513 $setSection =& $setSection[$newName];
517 $setSection[$fieldname] = $field;
518 $this->mFlatFields[$fieldname] = $field;
521 $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
531 return isset( $this->mFlatFields[$fieldname] );
540 if ( !$this->
hasField( $fieldname ) ) {
541 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
543 return $this->mFlatFields[$fieldname];
557 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
558 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
560 throw new LogicException(
'Cannot change display format after creation, ' .
561 'use HTMLForm::factory() instead' );
564 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
565 throw new InvalidArgumentException(
'Display format must be one of ' .
568 $this->availableDisplayFormats,
569 $this->availableSubclassDisplayFormats
575 $this->displayFormat = $format;
606 if ( isset( $descriptor[
'class'] ) ) {
607 $class = $descriptor[
'class'];
608 } elseif ( isset( $descriptor[
'type'] ) ) {
609 $class = static::$typeMappings[$descriptor[
'type']];
610 $descriptor[
'class'] = $class;
616 throw new InvalidArgumentException(
"Descriptor with no class for $fieldname: "
617 . print_r( $descriptor,
true ) );
638 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
640 $descriptor[
'fieldname'] = $fieldname;
642 $descriptor[
'parent'] = $parent;
645 # @todo This will throw a fatal error whenever someone try to use
646 # 'class' to feed a CSS class instead of 'cssclass'. Would be
647 # great to avoid the fatal error and show a nice error.
648 return new $class( $descriptor );
660 # Load data from the request.
662 $this->mFormIdentifier ===
null ||
663 $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier ||
664 ( $this->mSingleForm && $this->
getMethod() ===
'get' )
668 $this->mFieldData = [];
681 if ( $this->mFormIdentifier ===
null ) {
690 } elseif ( $this->
getRequest()->wasPosted() ) {
691 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
692 if ( $this->
getUser()->isRegistered() || $editToken !==
null ) {
697 CsrfTokenSet::DEFAULT_FIELD_NAME, $this->mTokenSalt
704 if ( $tokenOkay && $identOkay ) {
705 $this->mWasSubmitted =
true;
723 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
760 $hoistedErrors = Status::newGood();
761 if ( $this->mValidationErrorMessage ) {
762 foreach ( $this->mValidationErrorMessage as $error ) {
763 $hoistedErrors->fatal( ...$error );
766 $hoistedErrors->fatal(
'htmlform-invalid-input' );
769 $this->mWasSubmitted =
true;
771 # Check for cancelled submission
772 foreach ( $this->mFlatFields as $fieldname => $field ) {
773 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
776 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
777 $this->mWasSubmitted =
false;
782 # Check for validation
783 $hasNonDefault =
false;
784 foreach ( $this->mFlatFields as $fieldname => $field ) {
785 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
788 $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
789 if ( $field->isDisabled( $this->mFieldData ) ) {
792 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
793 if ( $res !==
true ) {
795 if ( $res !==
false && !$field->canDisplayErrors() ) {
796 if ( is_string( $res ) ) {
797 $hoistedErrors->fatal(
'rawmessage', $res );
799 $hoistedErrors->fatal( $res );
807 if ( !$hasNonDefault && $this->
getMethod() ===
'get' &&
808 ( $this->mFormIdentifier ===
null ||
809 $this->
getRequest()->getCheck(
'wpFormIdentifier' ) )
811 $this->mWasSubmitted =
false;
814 return $hoistedErrors;
818 if ( !is_callable( $callback ) ) {
819 throw new LogicException(
'HTMLForm: no submit callback provided. Use ' .
820 'setSubmitCallback() to set one.' );
825 $res = $callback( $data, $this );
826 if ( $res ===
false ) {
827 $this->mWasSubmitted =
false;
830 $res = Status::wrap( $res );
862 $this->mSubmitCallback = $cb;
877 $this->mValidationErrorMessage = $msg;
905 $this->mPre .= $html;
930 if ( $section ===
null ) {
931 $this->mHeader .= $html;
933 $this->mSectionHeaders[$section] ??=
'';
934 $this->mSectionHeaders[$section] .= $html;
950 if ( $section ===
null ) {
951 $this->mHeader = $html;
953 $this->mSectionHeaders[$section] = $html;
968 return $section ? $this->mSectionHeaders[$section] ??
'' :
$this->mHeader;
981 if ( $section ===
null ) {
982 $this->mFooter .= $html;
984 $this->mSectionFooters[$section] ??=
'';
985 $this->mSectionFooters[$section] .= $html;
1001 if ( $section ===
null ) {
1002 $this->mFooter = $html;
1004 $this->mSectionFooters[$section] = $html;
1018 return $section ? $this->mSectionFooters[$section] ??
'' :
$this->mFooter;
1030 $this->mPost .= $html;
1044 $this->mPost = $html;
1070 throw new \InvalidArgumentException(
1071 "Non-Codex HTMLForms do not support additional section information."
1075 $this->mSections = $sections;
1091 if ( !is_array( $value ) ) {
1093 $attribs += [
'name' => $name ];
1094 $this->mHiddenFields[] = [ $value, $attribs ];
1112 foreach ( $fields as $name => $value ) {
1113 if ( is_array( $value ) ) {
1117 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1147 if ( !is_array( $data ) ) {
1148 $args = func_get_args();
1149 if ( count( $args ) < 2 || count( $args ) > 4 ) {
1150 throw new InvalidArgumentException(
1151 'Incorrect number of arguments for deprecated calling style'
1156 'value' => $args[1],
1157 'id' => $args[2] ??
null,
1158 'attribs' => $args[3] ??
null,
1161 if ( !isset( $data[
'name'] ) ) {
1162 throw new InvalidArgumentException(
'A name is required' );
1164 if ( !isset( $data[
'value'] ) ) {
1165 throw new InvalidArgumentException(
'A value is required' );
1168 $this->mButtons[] = $data + [
1188 $this->mTokenSalt = $salt;
1214 private function getHiddenTitle(): string {
1215 if ( $this->hiddenTitleAddedToForm ) {
1223 $html .= Html::hidden(
'title', $this->
getTitle()->getPrefixedText() ) .
"\n";
1225 $this->hiddenTitleAddedToForm =
true;
1240 # For good measure (it is the default)
1241 $this->getOutput()->getMetadata()->setPreventClickjacking(
true );
1242 $this->getOutput()->addModules(
'mediawiki.htmlform' );
1243 $this->getOutput()->addModuleStyles( [
1244 'mediawiki.htmlform.styles',
1246 'mediawiki.codex.messagebox.styles'
1249 if ( $this->mCollapsible ) {
1251 $this->getOutput()->addModules(
'jquery.makeCollapsible' );
1254 $headerHtml = $this->getHeaderHtml();
1255 $footerHtml = $this->getFooterHtml();
1256 $html = $this->getErrorsOrWarnings( $submitResult,
'error' )
1257 . $this->getErrorsOrWarnings( $submitResult,
'warning' )
1259 . $this->getHiddenTitle()
1261 . $this->getHiddenFields()
1262 . $this->getButtons()
1265 return $this->mPre . $this->wrapForm( $html ) . $this->mPost;
1276 $this->mCollapsible =
true;
1277 $this->mCollapsed = $collapsedByDefault;
1287 # Use multipart/form-data
1288 $encType = $this->mUseMultipart
1289 ?
'multipart/form-data'
1290 :
'application/x-www-form-urlencoded';
1293 'class' =>
'mw-htmlform',
1294 'action' => $this->getAction(),
1295 'method' => $this->getMethod(),
1296 'enctype' => $encType,
1299 $attribs[
'id'] = $this->mId;
1301 if ( is_string( $this->mAutocomplete ) ) {
1302 $attribs[
'autocomplete'] = $this->mAutocomplete;
1304 if ( $this->mName ) {
1305 $attribs[
'name'] = $this->mName;
1307 if ( $this->needsJSForHtml5FormValidation() ) {
1308 $attribs[
'novalidate'] =
true;
1321 # Include a <fieldset> wrapper for style, if requested.
1322 if ( $this->mWrapperLegend !==
false ) {
1323 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1324 $html = Html::rawElement(
1326 $this->mWrapperAttributes,
1327 ( $legend ?
Html::element(
'legend', [], $legend ) :
'' ) . $html
1331 return Html::rawElement(
1333 $this->getFormAttributes(),
1347 $html .= $this->getHiddenTitle();
1349 if ( $this->mFormIdentifier !==
null ) {
1350 $html .= Html::hidden(
1352 $this->mFormIdentifier
1355 if ( $this->getMethod() ===
'post' ) {
1356 $html .= Html::hidden(
1358 $this->getUser()->getEditToken( $this->mTokenSalt ),
1359 [
'id' =>
'wpEditToken' ]
1363 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1364 $html .= Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1378 if ( $this->mShowSubmit ) {
1381 if ( $this->mSubmitID !==
null ) {
1382 $attribs[
'id'] = $this->mSubmitID;
1385 if ( $this->mSubmitName !==
null ) {
1386 $attribs[
'name'] = $this->mSubmitName;
1389 if ( $this->mSubmitTooltip !==
null ) {
1390 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1393 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1395 $buttons .= Html::submitButton( $this->getSubmitText(), $attribs ) .
"\n";
1398 if ( $this->mShowCancel ) {
1399 $target = $this->getCancelTargetURL();
1405 $this->msg(
'cancel' )->text()
1409 foreach ( $this->mButtons as $button ) {
1412 'name' => $button[
'name'],
1413 'value' => $button[
'value']
1416 if ( isset( $button[
'label-message'] ) ) {
1417 $label = $this->getMessage( $button[
'label-message'] )->parse();
1418 } elseif ( isset( $button[
'label'] ) ) {
1419 $label = htmlspecialchars( $button[
'label'] );
1420 } elseif ( isset( $button[
'label-raw'] ) ) {
1421 $label = $button[
'label-raw'];
1423 $label = htmlspecialchars( $button[
'value'] );
1427 if ( $button[
'attribs'] ) {
1429 $attrs += $button[
'attribs'];
1432 if ( isset( $button[
'id'] ) ) {
1433 $attrs[
'id'] = $button[
'id'];
1436 $buttons .= Html::rawElement(
'button', $attrs, $label ) .
"\n";
1443 return Html::rawElement(
'span',
1444 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1453 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1466 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1467 throw new DomainException( $elementsType .
' is not a valid type.' );
1469 $elementstr =
false;
1470 if ( $elements instanceof
Status ) {
1471 [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1472 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1473 if ( $status->isGood() ) {
1476 $elementstr = $status
1478 ->setContext( $this )
1479 ->setInterfaceMessageFlag(
true )
1482 } elseif ( $elementsType ===
'error' ) {
1483 if ( is_array( $elements ) ) {
1484 $elementstr = $this->formatErrors( $elements );
1485 } elseif ( $elements && $elements !==
true ) {
1486 $elementstr = (string)$elements;
1490 if ( !$elementstr ) {
1492 } elseif ( $elementsType ===
'error' ) {
1493 return Html::errorBox( $elementstr );
1495 return Html::warningBox( $elementstr );
1509 foreach ( $errors as $error ) {
1510 $errorstr .= Html::rawElement(
1513 $this->getMessage( $error )->parse()
1517 return Html::rawElement(
'ul', [], $errorstr );
1528 $this->mSubmitText = $t;
1540 $this->mSubmitFlags = [
'destructive',
'primary' ];
1554 if ( !$msg instanceof
Message ) {
1555 $msg = $this->msg( $msg );
1557 $this->setSubmitText( $msg->text() );
1567 return $this->mSubmitText ?: $this->msg(
'htmlform-submit' )->text();
1576 $this->mSubmitName = $name;
1587 $this->mSubmitTooltip = $name;
1601 $this->mSubmitID = $t;
1625 $this->mFormIdentifier = $ident;
1626 $this->mSingleForm = $single;
1642 $this->mShowSubmit = !$suppressSubmit;
1654 $this->mShowCancel = $show;
1666 $target = TitleValue::castPageToLinkTarget( $target );
1669 $this->mCancelTarget = $target;
1678 if ( is_string( $this->mCancelTarget ) ) {
1679 return $this->mCancelTarget;
1682 $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1683 return $target->getLocalURL();
1697 $this->mTableId = $id;
1718 $this->mName = $name;
1735 $this->mWrapperLegend = $legend;
1748 $this->mWrapperAttributes = $attributes;
1763 if ( !$msg instanceof
Message ) {
1764 $msg = $this->msg( $msg );
1766 $this->setWrapperLegend( $msg->text() );
1781 $this->mMessagePrefix = $p;
1795 $this->mTitle = Title::castFromPageReference( $t );
1804 return $this->mTitle ?: $this->getContext()->getTitle();
1815 $this->mMethod = strtolower( $method );
1824 return $this->mMethod;
1838 return Html::rawElement(
1865 $fieldsetIDPrefix =
'',
1866 &$hasUserVisibleFields =
false
1868 if ( $this->mFieldData ===
null ) {
1869 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
1870 .
'You probably called displayForm() without calling prepareForm() first.' );
1874 $subsectionHtml =
'';
1877 foreach ( $fields as $key => $value ) {
1879 $v = array_key_exists( $key, $this->mFieldData )
1880 ? $this->mFieldData[$key]
1881 : $value->getDefault();
1883 $retval = $this->formatField( $value, $v ??
'' );
1887 if ( $value->hasVisibleOutput() ) {
1890 $labelValue = trim( $value->getLabel() );
1891 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
1895 $hasUserVisibleFields =
true;
1897 } elseif ( is_array( $value ) ) {
1898 $subsectionHasVisibleFields =
false;
1900 $this->displaySection( $value,
1902 "$fieldsetIDPrefix$key-",
1903 $subsectionHasVisibleFields );
1905 if ( $subsectionHasVisibleFields ===
true ) {
1907 $hasUserVisibleFields =
true;
1909 $legend = $this->getLegend( $key );
1911 $headerHtml = $this->getHeaderHtml( $key );
1912 $footerHtml = $this->getFooterHtml( $key );
1913 $section = $headerHtml .
1918 if ( $fieldsetIDPrefix ) {
1919 $attributes[
'id'] = Sanitizer::escapeIdForAttribute(
"$fieldsetIDPrefix$key" );
1921 $subsectionHtml .= $this->wrapFieldSetSection(
1922 $legend, $section, $attributes, $fields === $this->mFieldTree
1926 $subsectionHtml .= $section;
1931 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1933 if ( $subsectionHtml ) {
1934 if ( $this->mSubSectionBeforeFields ) {
1935 return $subsectionHtml .
"\n" . $html;
1937 return $html .
"\n" . $subsectionHtml;
1953 $displayFormat = $this->getDisplayFormat();
1954 switch ( $displayFormat ) {
1958 return $field->
getDiv( $value );
1960 return $field->
getRaw( $value );
1964 throw new LogicException(
'Not implemented' );
1976 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1977 if ( !$fieldsHtml ) {
1983 $displayFormat = $this->getDisplayFormat();
1984 $html = implode(
'', $fieldsHtml );
1986 if ( $displayFormat ===
'raw' ) {
1991 $attribs = $anyFieldHasLabel ? [] : [
'class' =>
'mw-htmlform-nolabel' ];
1993 if ( $sectionName ) {
1994 $attribs[
'id'] = Sanitizer::escapeIdForAttribute( $sectionName );
1997 if ( $displayFormat ===
'table' ) {
1998 return Html::rawElement(
'table',
2000 Html::rawElement(
'tbody', [],
"\n$html\n" ) ) .
"\n";
2001 } elseif ( $displayFormat ===
'inline' ) {
2002 return Html::rawElement(
'span', $attribs,
"\n$html\n" );
2004 return Html::rawElement(
'div', $attribs,
"\n$html\n" );
2012 $this->prepareForm();
2020 $request = $this->getRequest();
2022 foreach ( $this->mFlatFields as $fieldname => $field ) {
2023 if ( $field->skipLoadData( $request ) ) {
2026 if ( $field->mParams[
'disabled'] ??
false ) {
2027 $fieldData[$fieldname] = $field->getDefault();
2029 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
2035 foreach ( $fieldData as $name => &$value ) {
2036 $field = $this->mFlatFields[$name];
2037 if ( $field->isDisabled( $fieldData ) ) {
2038 $value = $field->getDefault();
2043 foreach ( $fieldData as $name => &$value ) {
2044 $field = $this->mFlatFields[$name];
2045 $value = $field->filter( $value, $fieldData );
2048 $this->mFieldData = $fieldData;
2075 return $this->msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
2089 $this->mAction = $action;
2103 if ( $this->mAction !==
false ) {
2104 return $this->mAction;
2113 if ( str_contains( $articlePath,
'?' ) && $this->getMethod() ===
'get' ) {
2117 return $this->
getTitle()->getLocalURL();
2131 $this->mAutocomplete = $autocomplete;
2156 foreach ( $this->mFlatFields as $field ) {
2157 if ( $field->needsJSForHtml5FormValidation() ) {
2166class_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 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.