24use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
136 use ProtectedHookAccessorTrait;
140 'api' => HTMLApiField::class,
141 'text' => HTMLTextField::class,
142 'textwithbutton' => HTMLTextFieldWithButton::class,
143 'textarea' => HTMLTextAreaField::class,
144 'select' => HTMLSelectField::class,
145 'combobox' => HTMLComboboxField::class,
146 'radio' => HTMLRadioField::class,
147 'multiselect' => HTMLMultiSelectField::class,
148 'limitselect' => HTMLSelectLimitField::class,
149 'check' => HTMLCheckField::class,
150 'toggle' => HTMLCheckField::class,
151 'int' => HTMLIntField::class,
152 'float' => HTMLFloatField::class,
153 'info' => HTMLInfoField::class,
154 'selectorother' => HTMLSelectOrOtherField::class,
155 'selectandother' => HTMLSelectAndOtherField::class,
156 'namespaceselect' => HTMLSelectNamespace::class,
157 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
158 'tagfilter' => HTMLTagFilter::class,
159 'sizefilter' => HTMLSizeFilterField::class,
160 'submit' => HTMLSubmitField::class,
161 'hidden' => HTMLHiddenField::class,
162 'edittools' => HTMLEditTools::class,
163 'checkmatrix' => HTMLCheckMatrix::class,
164 'cloner' => HTMLFormFieldCloner::class,
165 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
166 'language' => HTMLSelectLanguageField::class,
167 'date' => HTMLDateTimeField::class,
168 'time' => HTMLDateTimeField::class,
169 'datetime' => HTMLDateTimeField::class,
170 'expiry' => HTMLExpiryField::class,
174 'email' => HTMLTextField::class,
175 'password' => HTMLTextField::class,
176 'url' => HTMLTextField::class,
177 'title' => HTMLTitleTextField::class,
178 'user' => HTMLUserTextField::class,
179 'usersmultiselect' => HTMLUsersMultiselectField::class,
180 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
181 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
315 public static function factory( $displayFormat, ...$arguments ) {
322 $form =
new self( ...$arguments );
344 $this->mTitle =
false;
345 $this->mMessagePrefix = $messagePrefix;
346 } elseif (
$context ===
null && $messagePrefix !==
'' ) {
347 $this->mMessagePrefix = $messagePrefix;
348 } elseif ( is_string(
$context ) && $messagePrefix ===
'' ) {
356 !$this->
getConfig()->
get(
'HTMLFormAllowTableFormat' )
357 && $this->displayFormat ===
'table'
359 $this->displayFormat =
'div';
375 $loadedDescriptor = [];
377 foreach ( $descriptor as $fieldname => $info ) {
379 $section = $info[
'section'] ??
'';
381 if ( isset( $info[
'type'] ) && $info[
'type'] ===
'file' ) {
382 $this->mUseMultipart =
true;
385 $field = static::loadInputFromParameters( $fieldname, $info, $this );
387 $setSection =& $loadedDescriptor;
389 foreach ( explode(
'/', $section ) as $newName ) {
390 if ( !isset( $setSection[$newName] ) ) {
391 $setSection[$newName] = [];
394 $setSection =& $setSection[$newName];
398 $setSection[$fieldname] = $field;
399 $this->mFlatFields[$fieldname] = $field;
402 $this->mFieldTree = array_merge( $this->mFieldTree, $loadedDescriptor );
412 return isset( $this->mFlatFields[$fieldname] );
421 if ( !$this->
hasField( $fieldname ) ) {
422 throw new DomainException( __METHOD__ .
': no field named ' . $fieldname );
424 return $this->mFlatFields[$fieldname];
439 in_array( $format, $this->availableSubclassDisplayFormats,
true ) ||
440 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats,
true )
442 throw new MWException(
'Cannot change display format after creation, ' .
443 'use HTMLForm::factory() instead' );
446 if ( !in_array( $format, $this->availableDisplayFormats,
true ) ) {
447 throw new MWException(
'Display format must be one of ' .
450 $this->availableDisplayFormats,
451 $this->availableSubclassDisplayFormats
458 if ( !$this->
getConfig()->
get(
'HTMLFormAllowTableFormat' ) && $format ===
'table' ) {
462 $this->displayFormat = $format;
473 return $this->displayFormat;
494 if ( isset( $descriptor[
'class'] ) ) {
495 $class = $descriptor[
'class'];
496 } elseif ( isset( $descriptor[
'type'] ) ) {
497 $class = static::$typeMappings[$descriptor[
'type']];
498 $descriptor[
'class'] = $class;
504 throw new MWException(
"Descriptor with no class for $fieldname: "
505 . print_r( $descriptor,
true ) );
526 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
528 $descriptor[
'fieldname'] = $fieldname;
530 $descriptor[
'parent'] = $parent;
533 # @todo This will throw a fatal error whenever someone try to use
534 # 'class' to feed a CSS class instead of 'cssclass'. Would be
535 # great to avoid the fatal error and show a nice error.
536 return new $class( $descriptor );
549 # Check if we have the info we need
550 if ( !$this->mTitle instanceof
Title && $this->mTitle !==
false ) {
551 throw new MWException(
'You must call setTitle() on an HTMLForm' );
554 # Load data from the request.
556 $this->mFormIdentifier ===
null ||
557 $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier
561 $this->mFieldData = [];
574 if ( $this->mFormIdentifier ===
null ) {
577 $identOkay = $this->
getRequest()->getVal(
'wpFormIdentifier' ) === $this->mFormIdentifier;
583 } elseif ( $this->
getRequest()->wasPosted() ) {
584 $editToken = $this->
getRequest()->getVal(
'wpEditToken' );
585 if ( $this->
getUser()->isLoggedIn() || $editToken !==
null ) {
589 $tokenOkay = $this->
getUser()->matchEditToken( $editToken, $this->mTokenSalt );
595 if ( $tokenOkay && $identOkay ) {
596 $this->mWasSubmitted =
true;
614 if ( $result ===
true || ( $result instanceof
Status && $result->
isGood() ) ) {
652 $hoistedErrors = Status::newGood();
653 if ( $this->mValidationErrorMessage ) {
654 foreach ( $this->mValidationErrorMessage as $error ) {
655 $hoistedErrors->fatal( ...$error );
658 $hoistedErrors->fatal(
'htmlform-invalid-input' );
661 $this->mWasSubmitted =
true;
663 # Check for cancelled submission
664 foreach ( $this->mFlatFields as $fieldname => $field ) {
665 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
668 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
669 $this->mWasSubmitted =
false;
674 # Check for validation
675 foreach ( $this->mFlatFields as $fieldname => $field ) {
676 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
679 if ( $field->isHidden( $this->mFieldData ) ) {
682 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
683 if (
$res !==
true ) {
685 if (
$res !==
false && !$field->canDisplayErrors() ) {
686 if ( is_string(
$res ) ) {
687 $hoistedErrors->fatal(
'rawmessage',
$res );
689 $hoistedErrors->fatal(
$res );
696 return $hoistedErrors;
699 $callback = $this->mSubmitCallback;
700 if ( !is_callable( $callback ) ) {
701 throw new MWException(
'HTMLForm: no submit callback provided. Use ' .
702 'setSubmitCallback() to set one.' );
707 $res = call_user_func( $callback, $data, $this );
708 if (
$res ===
false ) {
709 $this->mWasSubmitted =
false;
727 return $this->mWasSubmitted;
741 $this->mSubmitCallback = $cb;
755 $this->mValidationErrorMessage = $msg;
820 if ( $section ===
null ) {
821 $this->mHeader .= $msg;
823 if ( !isset( $this->mSectionHeaders[$section] ) ) {
824 $this->mSectionHeaders[$section] =
'';
826 $this->mSectionHeaders[$section] .= $msg;
842 if ( $section ===
null ) {
843 $this->mHeader = $msg;
845 $this->mSectionHeaders[$section] = $msg;
860 if ( $section ===
null ) {
861 return $this->mHeader;
863 return $this->mSectionHeaders[$section] ??
'';
876 if ( $section ===
null ) {
877 $this->mFooter .= $msg;
879 if ( !isset( $this->mSectionFooters[$section] ) ) {
880 $this->mSectionFooters[$section] =
'';
882 $this->mSectionFooters[$section] .= $msg;
898 if ( $section ===
null ) {
899 $this->mFooter = $msg;
901 $this->mSectionFooters[$section] = $msg;
915 if ( $section ===
null ) {
916 return $this->mFooter;
918 return $this->mSectionFooters[$section] ??
'';
930 $this->mPost .= $msg;
958 $attribs += [
'name' => $name ];
959 $this->mHiddenFields[] = [ $value, $attribs ];
975 foreach ( $fields as $name => $value ) {
976 $this->mHiddenFields[] = [ $value, [
'name' => $name ] ];
1007 if ( !is_array( $data ) ) {
1008 $args = func_get_args();
1009 if ( count(
$args ) < 2 || count(
$args ) > 4 ) {
1010 throw new InvalidArgumentException(
1011 'Incorrect number of arguments for deprecated calling style'
1016 'value' =>
$args[1],
1017 'id' =>
$args[2] ??
null,
1018 'attribs' =>
$args[3] ??
null,
1021 if ( !isset( $data[
'name'] ) ) {
1022 throw new InvalidArgumentException(
'A name is required' );
1024 if ( !isset( $data[
'value'] ) ) {
1025 throw new InvalidArgumentException(
'A value is required' );
1028 $this->mButtons[] = $data + [
1048 $this->mTokenSalt = $salt;
1082 # For good measure (it is the default)
1083 $this->
getOutput()->preventClickjacking();
1084 $this->
getOutput()->addModules(
'mediawiki.htmlform' );
1085 $this->
getOutput()->addModuleStyles(
'mediawiki.htmlform.styles' );
1098 return '' . $this->mPre . $html . $this->mPost;
1109 $this->mCollapsible =
true;
1110 $this->mCollapsed = $collapsedByDefault;
1120 # Use multipart/form-data
1121 $encType = $this->mUseMultipart
1122 ?
'multipart/form-data'
1123 :
'application/x-www-form-urlencoded';
1126 'class' =>
'mw-htmlform',
1129 'enctype' => $encType,
1132 $attribs[
'id'] = $this->mId;
1134 if ( is_string( $this->mAutocomplete ) ) {
1135 $attribs[
'autocomplete'] = $this->mAutocomplete;
1137 if ( $this->mName ) {
1138 $attribs[
'name'] = $this->mName;
1141 $attribs[
'novalidate'] =
true;
1155 # Include a <fieldset> wrapper for style, if requested.
1156 if ( $this->mWrapperLegend !==
false ) {
1157 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend :
false;
1158 $html = Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1161 return Html::rawElement(
1174 if ( $this->mFormIdentifier !==
null ) {
1175 $html .= Html::hidden(
1177 $this->mFormIdentifier
1181 $html .= Html::hidden(
1183 $this->
getUser()->getEditToken( $this->mTokenSalt ),
1184 [
'id' =>
'wpEditToken' ]
1186 $html .= Html::hidden(
'title', $this->
getTitle()->getPrefixedText() ) .
"\n";
1189 $articlePath = $this->
getConfig()->get(
'ArticlePath' );
1190 if ( strpos( $articlePath,
'?' ) !==
false && $this->
getMethod() ===
'get' ) {
1191 $html .= Html::hidden(
'title', $this->
getTitle()->getPrefixedText() ) .
"\n";
1194 foreach ( $this->mHiddenFields as $data ) {
1195 list( $value, $attribs ) = $data;
1196 $html .= Html::hidden( $attribs[
'name'], $value, $attribs ) .
"\n";
1209 $useMediaWikiUIEverywhere = $this->
getConfig()->get(
'UseMediaWikiUIEverywhere' );
1211 if ( $this->mShowSubmit ) {
1214 if ( isset( $this->mSubmitID ) ) {
1215 $attribs[
'id'] = $this->mSubmitID;
1218 if ( isset( $this->mSubmitName ) ) {
1219 $attribs[
'name'] = $this->mSubmitName;
1222 if ( isset( $this->mSubmitTooltip ) ) {
1226 $attribs[
'class'] = [
'mw-htmlform-submit' ];
1228 if ( $useMediaWikiUIEverywhere ) {
1229 foreach ( $this->mSubmitFlags as $flag ) {
1230 $attribs[
'class'][] =
'mw-ui-' . $flag;
1232 $attribs[
'class'][] =
'mw-ui-button';
1235 $buttons .= Xml::submitButton( $this->
getSubmitText(), $attribs ) .
"\n";
1238 if ( $this->mShowReset ) {
1239 $buttons .= Html::element(
1243 'value' => $this->
msg(
'htmlform-reset' )->text(),
1244 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' :
null,
1249 if ( $this->mShowCancel ) {
1250 $target = $this->mCancelTarget ?: Title::newMainPage();
1251 if ( $target instanceof
Title ) {
1252 $target = $target->getLocalURL();
1254 $buttons .= Html::element(
1257 'class' => $useMediaWikiUIEverywhere ?
'mw-ui-button' :
null,
1260 $this->
msg(
'cancel' )->text()
1264 foreach ( $this->mButtons as $button ) {
1267 'name' => $button[
'name'],
1268 'value' => $button[
'value']
1271 if ( isset( $button[
'label-message'] ) ) {
1272 $label = $this->
getMessage( $button[
'label-message'] )->parse();
1273 } elseif ( isset( $button[
'label'] ) ) {
1274 $label = htmlspecialchars( $button[
'label'] );
1275 } elseif ( isset( $button[
'label-raw'] ) ) {
1276 $label = $button[
'label-raw'];
1278 $label = htmlspecialchars( $button[
'value'] );
1281 if ( $button[
'attribs'] ) {
1282 $attrs += $button[
'attribs'];
1285 if ( isset( $button[
'id'] ) ) {
1286 $attrs[
'id'] = $button[
'id'];
1289 if ( $useMediaWikiUIEverywhere ) {
1290 $attrs[
'class'] = isset( $attrs[
'class'] ) ? (array)$attrs[
'class'] : [];
1291 $attrs[
'class'][] =
'mw-ui-button';
1294 $buttons .= Html::rawElement(
'button', $attrs, $label ) .
"\n";
1301 return Html::rawElement(
'span',
1302 [
'class' =>
'mw-htmlform-submit-buttons' ],
"\n$buttons" ) .
"\n";
1311 return $this->
displaySection( $this->mFieldTree, $this->mTableId );
1324 if ( !in_array( $elementsType, [
'error',
'warning' ],
true ) ) {
1325 throw new DomainException( $elementsType .
' is not a valid type.' );
1327 $elementstr =
false;
1328 if ( $elements instanceof
Status ) {
1329 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1330 $status = $elementsType ===
'error' ? $errorStatus : $warningStatus;
1331 if ( $status->isGood() ) {
1334 $elementstr = $status
1336 ->setContext( $this )
1337 ->setInterfaceMessageFlag(
true )
1340 } elseif ( is_array( $elements ) && $elementsType ===
'error' ) {
1342 } elseif ( $elementsType ===
'error' ) {
1343 $elementstr = $elements;
1347 ? Html::rawElement(
'div', [
'class' => $elementsType .
'box' ], $elementstr )
1361 foreach ( $errors as $error ) {
1362 $errorstr .= Html::rawElement(
1369 $errorstr = Html::rawElement(
'ul', [], $errorstr );
1382 $this->mSubmitText =
$t;
1394 $this->mSubmitFlags = [
'destructive',
'primary' ];
1408 if ( !$msg instanceof
Message ) {
1409 $msg = $this->
msg( $msg );
1421 return $this->mSubmitText ?: $this->
msg(
'htmlform-submit' )->text();
1430 $this->mSubmitName = $name;
1441 $this->mSubmitTooltip = $name;
1455 $this->mSubmitID =
$t;
1476 $this->mFormIdentifier = $ident;
1492 $this->mShowSubmit = !$suppressSubmit;
1504 $this->mShowCancel = $show;
1515 $this->mCancelTarget = $target;
1529 $this->mTableId = $id;
1550 $this->mName = $name;
1567 $this->mWrapperLegend = $legend;
1580 $this->mWrapperAttributes = $attributes;
1595 if ( !$msg instanceof
Message ) {
1596 $msg = $this->
msg( $msg );
1613 $this->mMessagePrefix = $p;
1636 return $this->mTitle ===
false
1649 $this->mMethod = strtolower( $method );
1658 return $this->mMethod;
1672 return Xml::fieldset( $legend, $section, $attributes ) .
"\n";
1694 $fieldsetIDPrefix =
'',
1695 &$hasUserVisibleFields =
false
1697 if ( $this->mFieldData ===
null ) {
1698 throw new LogicException(
'HTMLForm::displaySection() called on uninitialized field data. '
1699 .
'You probably called displayForm() without calling prepareForm() first.' );
1705 $subsectionHtml =
'';
1712 foreach ( $fields as $key => $value ) {
1714 $v = array_key_exists( $key, $this->mFieldData )
1715 ? $this->mFieldData[$key]
1716 : $value->getDefault();
1718 $retval = $value->$getFieldHtmlMethod( $v );
1722 if ( $value->hasVisibleOutput() ) {
1725 $labelValue = trim( $value->getLabel() );
1726 if ( $labelValue !==
"\u{00A0}" && $labelValue !==
' ' && $labelValue !==
'' ) {
1730 $hasUserVisibleFields =
true;
1732 } elseif ( is_array( $value ) ) {
1733 $subsectionHasVisibleFields =
false;
1737 "$fieldsetIDPrefix$key-",
1738 $subsectionHasVisibleFields );
1741 if ( $subsectionHasVisibleFields ===
true ) {
1743 $hasUserVisibleFields =
true;
1752 if ( $fieldsetIDPrefix ) {
1753 $attributes[
'id'] = Sanitizer::escapeIdForAttribute(
"$fieldsetIDPrefix$key" );
1756 $legend, $section, $attributes, $fields === $this->mFieldTree
1760 $subsectionHtml .= $section;
1765 $html = $this->
formatSection( $html, $sectionName, $hasLabel );
1767 if ( $subsectionHtml ) {
1768 if ( $this->mSubSectionBeforeFields ) {
1769 return $subsectionHtml .
"\n" . $html;
1771 return $html .
"\n" . $subsectionHtml;
1786 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1787 if ( !$fieldsHtml ) {
1794 $html = implode(
'', $fieldsHtml );
1802 if ( !$anyFieldHasLabel ) {
1803 $classes[] =
'mw-htmlform-nolabel';
1807 'class' => implode(
' ', $classes ),
1810 if ( $sectionName ) {
1811 $attribs[
'id'] = Sanitizer::escapeIdForAttribute( $sectionName );
1815 return Html::rawElement(
'table',
1817 Html::rawElement(
'tbody', [],
"\n$html\n" ) ) .
"\n";
1819 return Html::rawElement(
'span', $attribs,
"\n$html\n" );
1821 return Html::rawElement(
'div', $attribs,
"\n$html\n" );
1831 foreach ( $this->mFlatFields as $fieldname => $field ) {
1833 if ( $field->skipLoadData( $request ) ) {
1835 } elseif ( !empty( $field->mParams[
'disabled'] ) ) {
1836 $fieldData[$fieldname] = $field->getDefault();
1838 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1843 foreach ( $fieldData as $name => &$value ) {
1844 $field = $this->mFlatFields[$name];
1845 $value = $field->filter( $value, $this->mFlatFields );
1848 $this->mFieldData = $fieldData;
1859 $this->mShowReset = !$suppressReset;
1888 return $this->
msg( $this->mMessagePrefix ?
"{$this->mMessagePrefix}-$key" : $key )->text();
1902 $this->mAction = $action;
1916 if ( $this->mAction !==
false ) {
1917 return $this->mAction;
1920 $articlePath = $this->
getConfig()->get(
'ArticlePath' );
1926 if ( strpos( $articlePath,
'?' ) !==
false && $this->
getMethod() ===
'get' ) {
1930 return $this->
getTitle()->getLocalURL();
1944 $this->mAutocomplete = $autocomplete;
1969 foreach ( $this->mFlatFields as $fieldname => $field ) {
1970 if ( $field->needsJSForHtml5FormValidation() ) {
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
setContext(IContextSource $context)
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
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...
isGood()
Returns whether the operation completed and didn't have any error or warnings.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Represents a title within MediaWiki.
Interface for objects which can provide a MediaWiki context on request.