24 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
141 use ProtectedHookAccessorTrait;
145 'api' => HTMLApiField::class,
146 'text' => HTMLTextField::class,
147 'textwithbutton' => HTMLTextFieldWithButton::class,
148 'textarea' => HTMLTextAreaField::class,
149 'select' => HTMLSelectField::class,
150 'combobox' => HTMLComboboxField::class,
151 'radio' => HTMLRadioField::class,
152 'multiselect' => HTMLMultiSelectField::class,
153 'limitselect' => HTMLSelectLimitField::class,
154 'check' => HTMLCheckField::class,
155 'toggle' => HTMLCheckField::class,
156 'int' => HTMLIntField::class,
157 'file' => HTMLFileField::class,
158 'float' => HTMLFloatField::class,
159 'info' => HTMLInfoField::class,
160 'selectorother' => HTMLSelectOrOtherField::class,
161 'selectandother' => HTMLSelectAndOtherField::class,
162 'namespaceselect' => HTMLSelectNamespace::class,
163 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
164 'tagfilter' => HTMLTagFilter::class,
165 'sizefilter' => HTMLSizeFilterField::class,
166 'submit' => HTMLSubmitField::class,
167 'hidden' => HTMLHiddenField::class,
168 'edittools' => HTMLEditTools::class,
169 'checkmatrix' => HTMLCheckMatrix::class,
170 'cloner' => HTMLFormFieldCloner::class,
171 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
172 'language' => HTMLSelectLanguageField::class,
173 'date' => HTMLDateTimeField::class,
174 'time' => HTMLDateTimeField::class,
175 'datetime' => HTMLDateTimeField::class,
176 'expiry' => HTMLExpiryField::class,
180 'email' => HTMLTextField::class,
181 'password' => HTMLTextField::class,
182 'url' => HTMLTextField::class,
183 'title' => HTMLTitleTextField::class,
184 'user' => HTMLUserTextField::class,
185 'usersmultiselect' => HTMLUsersMultiselectField::class,
186 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
187 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
329 $form =
new self( ...$arguments );
351 $this->mTitle =
false;
352 $this->mMessagePrefix = $messagePrefix;
353 } elseif (
$context ===
null && $messagePrefix !==
'' ) {
354 $this->mMessagePrefix = $messagePrefix;
355 } elseif ( is_string(
$context ) && $messagePrefix ===
'' ) {
363 !$this->
getConfig()->
get(
'HTMLFormAllowTableFormat' )
364 && $this->displayFormat ===
'table'
366 $this->displayFormat =
'div';
382 $loadedDescriptor = [];
384 foreach ( $descriptor as $fieldname => $info ) {
386 $section = $info[
'section'] ??
'';
388 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
389 $this->mUseMultipart =
true;
392 $field = static::loadInputFromParameters( $fieldname, $info, $this );
394 $setSection =& $loadedDescriptor;
396 foreach ( explode(
'/', $section ) as $newName ) {
397 if ( !isset( $setSection[$newName] ) ) {
398 $setSection[$newName] = [];
401 $setSection =& $setSection[$newName];
405 $setSection[$fieldname] = $field;
406 $this->mFlatFields[$fieldname] = $field;
409 $this->mFieldTree = array_merge( $this->mFieldTree, $loadedDescriptor );
419 return isset( $this->mFlatFields[$fieldname] );
428 if ( !$this->
hasField( $fieldname ) ) {
429 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
431 return $this->mFlatFields[$fieldname];
446 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
447 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
449 throw new MWException(
'Cannot change display format after creation, ' .
450 'use HTMLForm::factory() instead' );
453 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
454 throw new MWException(
'Display format must be one of ' .
457 $this->availableDisplayFormats,
458 $this->availableSubclassDisplayFormats
465 if ( !$this->
getConfig()->
get(
'HTMLFormAllowTableFormat' ) && $format ===
'table' ) {
469 $this->displayFormat = $format;
501 if ( isset( $descriptor[
'class'] ) ) {
502 $class = $descriptor[
'class'];
503 } elseif ( isset( $descriptor[
'type'] ) ) {
504 $class = static::$typeMappings[$descriptor[
'type']];
505 $descriptor[
'class'] = $class;
511 throw new MWException(
"Descriptor with no class for $fieldname: "
512 . print_r( $descriptor,
true ) );
533 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
535 $descriptor[
'fieldname'] = $fieldname;
537 $descriptor[
'parent'] = $parent;
540 # @todo This will throw a fatal error whenever someone try to use
541 # 'class' to feed a CSS class instead of 'cssclass'. Would be
542 # great to avoid the fatal error and show a nice error.
543 return new $class( $descriptor );
556 # Check if we have the info we need
557 if ( !$this->mTitle instanceof
Title && $this->mTitle !==
false ) {
558 throw new MWException(
'You must call setTitle() on an HTMLForm' );
561 # Load data from the request.
563 $this->mFormIdentifier ===
null ||
564 $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier
568 $this->mFieldData = [];
581 if ( $this->mFormIdentifier ===
null ) {
590 } elseif ( $this->
getRequest()->wasPosted() ) {
591 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
592 if ( $this->
getUser()->isRegistered() || $editToken !==
null ) {
596 $tokenOkay = $this->
getUser()->matchEditToken( $editToken, $this->mTokenSalt );
602 if ( $tokenOkay && $identOkay ) {
603 $this->mWasSubmitted =
true;
621 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
660 if ( $this->mValidationErrorMessage ) {
661 foreach ( $this->mValidationErrorMessage as $error ) {
662 $hoistedErrors->fatal( ...$error );
665 $hoistedErrors->fatal(
'htmlform-invalid-input' );
668 $this->mWasSubmitted =
true;
670 # Check for cancelled submission
671 foreach ( $this->mFlatFields as $fieldname => $field ) {
672 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
675 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
676 $this->mWasSubmitted =
false;
681 # Check for validation
682 foreach ( $this->mFlatFields as $fieldname => $field ) {
683 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
686 if ( $field->isHidden( $this->mFieldData ) ) {
689 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
690 if (
$res !==
true ) {
692 if (
$res !==
false && !$field->canDisplayErrors() ) {
693 if ( is_string(
$res ) ) {
694 $hoistedErrors->fatal(
'rawmessage',
$res );
696 $hoistedErrors->fatal(
$res );
703 return $hoistedErrors;
707 if ( !is_callable( $callback ) ) {
708 throw new MWException(
'HTMLForm: no submit callback provided. Use ' .
709 'setSubmitCallback() to set one.' );
714 $res = call_user_func( $callback, $data, $this );
715 if (
$res ===
false ) {
716 $this->mWasSubmitted =
false;
748 $this->mSubmitCallback = $cb;
762 $this->mValidationErrorMessage = $msg;
827 if ( $section ===
null ) {
828 $this->mHeader .= $msg;
830 if ( !isset( $this->mSectionHeaders[$section] ) ) {
831 $this->mSectionHeaders[$section] =
'';
833 $this->mSectionHeaders[$section] .= $msg;
849 if ( $section ===
null ) {
850 $this->mHeader = $msg;
852 $this->mSectionHeaders[$section] = $msg;
867 if ( $section ===
null ) {
870 return $this->mSectionHeaders[$section] ??
'';
883 if ( $section ===
null ) {
884 $this->mFooter .= $msg;
886 if ( !isset( $this->mSectionFooters[$section] ) ) {
887 $this->mSectionFooters[$section] =
'';
889 $this->mSectionFooters[$section] .= $msg;
905 if ( $section ===
null ) {
906 $this->mFooter = $msg;
908 $this->mSectionFooters[$section] = $msg;
922 if ( $section ===
null ) {
925 return $this->mSectionFooters[$section] ??
'';
937 $this->mPost .= $msg;
965 $attribs += [
'name' => $name ];
966 $this->mHiddenFields[] = [ $value, $attribs ];
982 foreach ( $fields as $name => $value ) {
983 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1014 if ( !is_array( $data ) ) {
1015 $args = func_get_args();
1016 if ( count(
$args ) < 2 || count(
$args ) > 4 ) {
1017 throw new InvalidArgumentException(
1018 'Incorrect number of arguments for deprecated calling style'
1023 'value' =>
$args[1],
1024 'id' =>
$args[2] ??
null,
1025 'attribs' =>
$args[3] ??
null,
1028 if ( !isset( $data[
'name'] ) ) {
1029 throw new InvalidArgumentException(
'A name is required' );
1031 if ( !isset( $data[
'value'] ) ) {
1032 throw new InvalidArgumentException(
'A value is required' );
1035 $this->mButtons[] = $data + [
1055 $this->mTokenSalt = $salt;
1089 # For good measure (it is the default)
1090 $this->
getOutput()->preventClickjacking();
1091 $this->
getOutput()->addModules(
'mediawiki.htmlform' );
1092 $this->
getOutput()->addModuleStyles(
'mediawiki.htmlform.styles' );
1094 if ( $this->mCollapsible ) {
1096 $this->
getOutput()->addModules(
'jquery.makeCollapsible' );
1121 $this->mCollapsible =
true;
1122 $this->mCollapsed = $collapsedByDefault;
1132 # Use multipart/form-data
1133 $encType = $this->mUseMultipart
1134 ?
'multipart/form-data'
1135 :
'application/x-www-form-urlencoded';
1138 'class' =>
'mw-htmlform',
1141 'enctype' => $encType,
1146 if ( is_string( $this->mAutocomplete ) ) {
1149 if ( $this->mName ) {
1153 $attribs[
'novalidate'] =
true;
1167 # Include a <fieldset> wrapper for style, if requested.
1168 if ( $this->mWrapperLegend !==
false ) {
1169 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1170 $html =
Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1186 if ( $this->mFormIdentifier !==
null ) {
1189 $this->mFormIdentifier
1195 $this->
getUser()->getEditToken( $this->mTokenSalt ),
1196 [
'id' =>
'wpEditToken' ]
1201 $articlePath = $this->
getConfig()->get(
'ArticlePath' );
1202 if ( strpos( $articlePath,
'?' ) !==
false && $this->
getMethod() ===
'get' ) {
1206 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1207 $html .=
Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1220 $useMediaWikiUIEverywhere = $this->
getConfig()->get(
'UseMediaWikiUIEverywhere' );
1222 if ( $this->mShowSubmit ) {
1225 if ( isset( $this->mSubmitID ) ) {
1229 if ( isset( $this->mSubmitName ) ) {
1233 if ( isset( $this->mSubmitTooltip ) ) {
1237 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1239 if ( $useMediaWikiUIEverywhere ) {
1240 foreach ( $this->mSubmitFlags as $flag ) {
1241 $attribs[
'class'][] =
'mw-ui-' . $flag;
1243 $attribs[
'class'][] =
'mw-ui-button';
1249 if ( $this->mShowReset ) {
1254 'value' => $this->
msg(
'htmlform-reset' )->text(),
1255 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' :
null,
1260 if ( $this->mShowCancel ) {
1262 if ( $target instanceof
Title ) {
1263 $target = $target->getLocalURL();
1268 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' :
null,
1271 $this->
msg(
'cancel' )->text()
1275 foreach ( $this->mButtons as $button ) {
1278 'name' => $button[
'name'],
1279 'value' => $button[
'value']
1282 if ( isset( $button[
'label-message'] ) ) {
1283 $label = $this->
getMessage( $button[
'label-message'] )->parse();
1284 } elseif ( isset( $button[
'label'] ) ) {
1285 $label = htmlspecialchars( $button[
'label'] );
1286 } elseif ( isset( $button[
'label-raw'] ) ) {
1287 $label = $button[
'label-raw'];
1289 $label = htmlspecialchars( $button[
'value'] );
1292 if ( $button[
'attribs'] ) {
1293 $attrs += $button[
'attribs'];
1296 if ( isset( $button[
'id'] ) ) {
1297 $attrs[
'id'] = $button[
'id'];
1300 if ( $useMediaWikiUIEverywhere ) {
1301 $attrs[
'class'] = isset( $attrs[
'class'] ) ? (array)$attrs[
'class'] : [];
1302 $attrs[
'class'][] =
'mw-ui-button';
1313 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1322 return $this->
displaySection( $this->mFieldTree, $this->mTableId );
1335 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1336 throw new DomainException( $elementsType .
' is not a valid type.' );
1338 $elementstr =
false;
1339 if ( $elements instanceof
Status ) {
1340 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1341 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1342 if ( $status->isGood() ) {
1345 $elementstr = $status
1347 ->setContext( $this )
1348 ->setInterfaceMessageFlag(
true )
1351 } elseif ( $elementsType ===
'error' ) {
1352 if ( is_array( $elements ) ) {
1354 } elseif ( $elements && $elements !==
true ) {
1355 $elementstr = (string)$elements;
1360 ?
Html::rawElement(
'div', [
'class' => $elementsType .
'box' ], $elementstr )
1374 foreach ( $errors as $error ) {
1395 $this->mSubmitText =
$t;
1407 $this->mSubmitFlags = [
'destructive',
'primary' ];
1421 if ( !$msg instanceof
Message ) {
1422 $msg = $this->
msg( $msg );
1434 return $this->mSubmitText ?: $this->
msg(
'htmlform-submit' )->text();
1443 $this->mSubmitName = $name;
1454 $this->mSubmitTooltip = $name;
1468 $this->mSubmitID =
$t;
1489 $this->mFormIdentifier = $ident;
1505 $this->mShowSubmit = !$suppressSubmit;
1517 $this->mShowCancel = $show;
1528 $this->mCancelTarget = $target;
1542 $this->mTableId = $id;
1563 $this->mName = $name;
1580 $this->mWrapperLegend = $legend;
1593 $this->mWrapperAttributes = $attributes;
1608 if ( !$msg instanceof
Message ) {
1609 $msg = $this->
msg( $msg );
1626 $this->mMessagePrefix = $p;
1648 return $this->mTitle ===
false
1661 $this->mMethod = strtolower( $method );
1684 return Xml::fieldset( $legend, $section, $attributes ) .
"\n";
1706 $fieldsetIDPrefix =
'',
1707 &$hasUserVisibleFields =
false
1709 if ( $this->mFieldData ===
null ) {
1710 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
1711 .
'You probably called displayForm() without calling prepareForm() first.' );
1717 $subsectionHtml =
'';
1724 foreach ( $fields as $key => $value ) {
1726 $v = array_key_exists( $key, $this->mFieldData )
1727 ? $this->mFieldData[$key]
1728 : $value->getDefault();
1730 $retval = $value->$getFieldHtmlMethod( $v );
1734 if ( $value->hasVisibleOutput() ) {
1737 $labelValue = trim( $value->getLabel() );
1738 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
1742 $hasUserVisibleFields =
true;
1744 } elseif ( is_array( $value ) ) {
1745 $subsectionHasVisibleFields =
false;
1749 "$fieldsetIDPrefix$key-",
1750 $subsectionHasVisibleFields );
1753 if ( $subsectionHasVisibleFields ===
true ) {
1755 $hasUserVisibleFields =
true;
1764 if ( $fieldsetIDPrefix ) {
1768 $legend, $section, $attributes, $fields === $this->mFieldTree
1772 $subsectionHtml .= $section;
1777 $html = $this->
formatSection( $html, $sectionName, $hasLabel );
1779 if ( $subsectionHtml ) {
1780 if ( $this->mSubSectionBeforeFields ) {
1781 return $subsectionHtml .
"\n" . $html;
1783 return $html .
"\n" . $subsectionHtml;
1798 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1799 if ( !$fieldsHtml ) {
1806 $html = implode(
'', $fieldsHtml );
1814 if ( !$anyFieldHasLabel ) {
1815 $classes[] =
'mw-htmlform-nolabel';
1818 $attribs = [
'class' => $classes ];
1820 if ( $sectionName ) {
1841 foreach ( $this->mFlatFields as $fieldname => $field ) {
1843 if ( $field->skipLoadData( $request ) ) {
1845 } elseif ( !empty( $field->mParams[
'disabled'] ) ) {
1846 $fieldData[$fieldname] = $field->getDefault();
1848 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1853 foreach ( $fieldData as $name => &$value ) {
1854 $field = $this->mFlatFields[$name];
1855 $value = $field->filter( $value, $this->mFlatFields );
1858 $this->mFieldData = $fieldData;
1869 $this->mShowReset = !$suppressReset;
1898 return $this->
msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
1912 $this->mAction = $action;
1926 if ( $this->mAction !==
false ) {
1930 $articlePath = $this->
getConfig()->get(
'ArticlePath' );
1936 if ( strpos( $articlePath,
'?' ) !==
false && $this->
getMethod() ===
'get' ) {
1940 return $this->
getTitle()->getLocalURL();
1954 $this->mAutocomplete = $autocomplete;
1979 foreach ( $this->mFlatFields as $fieldname => $field ) {
1980 if ( $field->needsJSForHtml5FormValidation() ) {