MediaWiki master
HTMLForm.php
Go to the documentation of this file.
1<?php
2
10namespace MediaWiki\HTMLForm;
11
12use DomainException;
13use InvalidArgumentException;
14use LogicException;
17use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
67use StatusValue;
68use Stringable;
71
214class HTMLForm extends ContextSource {
215 use ProtectedHookAccessorTrait;
216
218 public static $typeMappings = [
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,
253 // HTMLTextField will output the correct type="" attribute automagically.
254 // There are about four zillion other HTML5 input types, like range, but
255 // we don't use those at the moment, so no point in adding all of them.
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,
266 ];
267
270
273
275 protected $mFlatFields = [];
277 protected $mFieldTree = [];
279 protected $mShowSubmit = true;
281 protected $mSubmitFlags = [ 'primary', 'progressive' ];
283 protected $mShowCancel = false;
285 protected $mCancelTarget;
286
294
296 protected $mPre = '';
298 protected $mHeader = '';
300 protected $mFooter = '';
302 protected $mSectionHeaders = [];
304 protected $mSectionFooters = [];
306 protected $mPost = '';
308 protected $mId;
310 protected $mName;
312 protected $mTableId = '';
313
315 protected $mSubmitID;
317 protected $mSubmitName;
319 protected $mSubmitText;
322
326 protected $mSingleForm = false;
327
329 protected $mTitle;
331 protected $mMethod = 'post';
333 protected $mWasSubmitted = false;
334
340 protected $mAction = false;
341
347 protected $mCollapsible = false;
348
354 protected $mCollapsed = false;
355
361 protected $mAutocomplete = null;
362
364 protected $mUseMultipart = false;
369 protected $mHiddenFields = [];
374 protected $mButtons = [];
375
377 protected $mWrapperLegend = false;
379 protected $mWrapperAttributes = [];
380
385 protected $mTokenSalt = '';
386
399 protected $mSections = [];
400
409 protected $mSubSectionBeforeFields = true;
410
416 protected $displayFormat = 'table';
417
423 'table',
424 'div',
425 'raw',
426 'inline',
427 ];
428
434 'codex',
435 'ooui',
436 ];
437
442 private $hiddenTitleAddedToForm = false;
443
457 public static function factory(
458 $displayFormat, $descriptor, IContextSource $context, $messagePrefix = ''
459 ) {
460 switch ( $displayFormat ) {
461 case 'codex':
462 return new CodexHTMLForm( $descriptor, $context, $messagePrefix );
463 case 'ooui':
464 return new OOUIHTMLForm( $descriptor, $context, $messagePrefix );
465 default:
466 $form = new self( $descriptor, $context, $messagePrefix );
467 $form->setDisplayFormat( $displayFormat );
468 return $form;
469 }
470 }
471
483 public function __construct(
484 $descriptor, IContextSource $context, $messagePrefix = ''
485 ) {
486 $this->setContext( $context );
487 $this->mMessagePrefix = $messagePrefix;
488 $this->addFields( $descriptor );
489 }
490
500 public function addFields( $descriptor ) {
501 $loadedDescriptor = [];
502
503 foreach ( $descriptor as $fieldname => $info ) {
504 $section = $info['section'] ?? '';
505
506 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
507 $this->mUseMultipart = true;
508 }
509
510 $field = static::loadInputFromParameters( $fieldname, $info, $this );
511
512 $setSection =& $loadedDescriptor;
513 if ( $section ) {
514 foreach ( explode( '/', $section ) as $newName ) {
515 $setSection[$newName] ??= [];
516 $setSection =& $setSection[$newName];
517 }
518 }
519
520 $setSection[$fieldname] = $field;
521 $this->mFlatFields[$fieldname] = $field;
522 }
523
524 $this->mFieldTree = array_merge_recursive( $this->mFieldTree, $loadedDescriptor );
525
526 return $this;
527 }
528
533 public function hasField( $fieldname ) {
534 return isset( $this->mFlatFields[$fieldname] );
535 }
536
542 public function getField( $fieldname ) {
543 if ( !$this->hasField( $fieldname ) ) {
544 throw new DomainException( __METHOD__ . ': no field named ' . $fieldname );
545 }
546 return $this->mFlatFields[$fieldname];
547 }
548
558 public function setDisplayFormat( $format ) {
559 if (
560 in_array( $format, $this->availableSubclassDisplayFormats, true ) ||
561 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats, true )
562 ) {
563 throw new LogicException( 'Cannot change display format after creation, ' .
564 'use HTMLForm::factory() instead' );
565 }
566
567 if ( !in_array( $format, $this->availableDisplayFormats, true ) ) {
568 throw new InvalidArgumentException( 'Display format must be one of ' .
569 print_r(
570 array_merge(
571 $this->availableDisplayFormats,
572 $this->availableSubclassDisplayFormats
573 ),
574 true
575 ) );
576 }
577
578 $this->displayFormat = $format;
579
580 return $this;
581 }
582
588 public function getDisplayFormat() {
590 }
591
608 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
609 if ( isset( $descriptor['class'] ) ) {
610 $class = $descriptor['class'];
611 } elseif ( isset( $descriptor['type'] ) ) {
612 $class = static::$typeMappings[$descriptor['type']];
613 $descriptor['class'] = $class;
614 } else {
615 $class = null;
616 }
617
618 if ( !$class ) {
619 throw new InvalidArgumentException( "Descriptor with no class for $fieldname: "
620 . print_r( $descriptor, true ) );
621 }
622
623 return $class;
624 }
625
637 public static function loadInputFromParameters( $fieldname, $descriptor, self $parent ) {
638 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
639
640 $descriptor['fieldname'] = $fieldname;
641 $descriptor['parent'] = $parent;
642
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 );
647 }
648
657 public function prepareForm() {
658 # Load data from the request.
659 if (
660 $this->mFormIdentifier === null ||
661 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier ||
662 ( $this->mSingleForm && $this->getMethod() === 'get' )
663 ) {
664 $this->loadFieldData();
665 } else {
666 $this->mFieldData = [];
667 }
668
669 return $this;
670 }
671
676 public function tryAuthorizedSubmit() {
677 $result = false;
678 if ( $this->requestIsAuthorized() ) {
679 $this->mWasSubmitted = true;
680 $result = $this->trySubmit();
681 }
682
683 return $result;
684 }
685
692 public function requestIsAuthorized(): bool {
693 if ( $this->mFormIdentifier === null ) {
694 $identOkay = true;
695 } else {
696 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier;
697 }
698
699 $tokenOkay = false;
700 if ( $this->getMethod() !== 'post' ) {
701 $tokenOkay = true; // no session check needed
702 } elseif ( $this->getRequest()->wasPosted() ) {
703 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
704 if ( $this->getUser()->isRegistered() || $editToken !== null ) {
705 // Session tokens for logged-out users have no security value.
706 // However, if the user gave one, check it in order to give a nice
707 // "session expired" error instead of "permission denied" or such.
708 $tokenOkay = $this->getCsrfTokenSet()->matchTokenField(
709 CsrfTokenSet::DEFAULT_FIELD_NAME, $this->mTokenSalt
710 );
711 } else {
712 $tokenOkay = true;
713 }
714 }
715 return $identOkay && $tokenOkay;
716 }
717
725 public function show() {
726 $this->prepareForm();
727
728 $result = $this->tryAuthorizedSubmit();
729 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
730 return $result;
731 }
732
733 $this->displayForm( $result );
734
735 return false;
736 }
737
743 public function showAlways() {
744 $this->prepareForm();
745
746 $result = $this->tryAuthorizedSubmit();
747
748 $this->displayForm( $result );
749
750 return $result;
751 }
752
764 public function trySubmit() {
765 $valid = true;
766 $hoistedErrors = Status::newGood();
767 if ( $this->mValidationErrorMessage ) {
768 foreach ( $this->mValidationErrorMessage as $error ) {
769 $hoistedErrors->fatal( ...$error );
770 }
771 } else {
772 $hoistedErrors->fatal( 'htmlform-invalid-input' );
773 }
774
775 $this->mWasSubmitted = true;
776
777 # Check for cancelled submission
778 foreach ( $this->mFlatFields as $fieldname => $field ) {
779 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
780 continue;
781 }
782 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
783 $this->mWasSubmitted = false;
784 return false;
785 }
786 }
787
788 # Check for validation
789 $hasNonDefault = false;
790 foreach ( $this->mFlatFields as $fieldname => $field ) {
791 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
792 continue;
793 }
794 $hasNonDefault = $hasNonDefault || $this->mFieldData[$fieldname] !== $field->getDefault();
795 if ( $field->isDisabled( $this->mFieldData ) ) {
796 continue;
797 }
798 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
799 if ( $res !== true ) {
800 $valid = false;
801 if ( $res !== false && !$field->canDisplayErrors() ) {
802 if ( is_string( $res ) ) {
803 $hoistedErrors->fatal( 'rawmessage', $res );
804 } else {
805 $hoistedErrors->fatal( $res );
806 }
807 }
808 }
809 }
810
811 if ( !$valid ) {
812 // Treat as not submitted if got nothing from the user on GET forms.
813 if ( !$hasNonDefault && $this->getMethod() === 'get' &&
814 ( $this->mFormIdentifier === null ||
815 $this->getRequest()->getCheck( 'wpFormIdentifier' ) )
816 ) {
817 $this->mWasSubmitted = false;
818 return false;
819 }
820 return $hoistedErrors;
821 }
822
823 $callback = $this->mSubmitCallback;
824 if ( !is_callable( $callback ) ) {
825 throw new LogicException( 'HTMLForm: no submit callback provided. Use ' .
826 'setSubmitCallback() to set one.' );
827 }
828
829 $data = $this->filterDataForSubmit( $this->mFieldData );
830
831 $res = $callback( $data, $this );
832 if ( $res === false ) {
833 $this->mWasSubmitted = false;
834 } elseif ( $res instanceof StatusValue ) {
835 // DWIM - callbacks are not supposed to return a StatusValue but it's easy to mix up.
836 $res = Status::wrap( $res );
837 }
838
839 return $res;
840 }
841
853 public function wasSubmitted() {
854 return $this->mWasSubmitted;
855 }
856
867 public function setSubmitCallback( $cb ) {
868 $this->mSubmitCallback = $cb;
869
870 return $this;
871 }
872
882 public function setValidationErrorMessage( $msg ) {
883 $this->mValidationErrorMessage = $msg;
884
885 return $this;
886 }
887
896 public function setPreHtml( $html ) {
897 $this->mPre = $html;
898
899 return $this;
900 }
901
910 public function addPreHtml( $html ) {
911 $this->mPre .= $html;
912
913 return $this;
914 }
915
922 public function getPreHtml() {
923 return $this->mPre;
924 }
925
935 public function addHeaderHtml( $html, $section = null ) {
936 if ( $section === null ) {
937 $this->mHeader .= $html;
938 } else {
939 $this->mSectionHeaders[$section] ??= '';
940 $this->mSectionHeaders[$section] .= $html;
941 }
942
943 return $this;
944 }
945
955 public function setHeaderHtml( $html, $section = null ) {
956 if ( $section === null ) {
957 $this->mHeader = $html;
958 } else {
959 $this->mSectionHeaders[$section] = $html;
960 }
961
962 return $this;
963 }
964
973 public function getHeaderHtml( $section = null ) {
974 return $section ? $this->mSectionHeaders[$section] ?? '' : $this->mHeader;
975 }
976
986 public function addFooterHtml( $html, $section = null ) {
987 if ( $section === null ) {
988 $this->mFooter .= $html;
989 } else {
990 $this->mSectionFooters[$section] ??= '';
991 $this->mSectionFooters[$section] .= $html;
992 }
993
994 return $this;
995 }
996
1006 public function setFooterHtml( $html, $section = null ) {
1007 if ( $section === null ) {
1008 $this->mFooter = $html;
1009 } else {
1010 $this->mSectionFooters[$section] = $html;
1011 }
1012
1013 return $this;
1014 }
1015
1023 public function getFooterHtml( $section = null ) {
1024 return $section ? $this->mSectionFooters[$section] ?? '' : $this->mFooter;
1025 }
1026
1035 public function addPostHtml( $html ) {
1036 $this->mPost .= $html;
1037
1038 return $this;
1039 }
1040
1049 public function setPostHtml( $html ) {
1050 $this->mPost = $html;
1051
1052 return $this;
1053 }
1054
1061 public function getPostHtml() {
1062 return $this->mPost;
1063 }
1064
1074 public function setSections( $sections ) {
1075 if ( $this->getDisplayFormat() !== 'codex' ) {
1076 throw new \InvalidArgumentException(
1077 "Non-Codex HTMLForms do not support additional section information."
1078 );
1079 }
1080
1081 $this->mSections = $sections;
1082
1083 return $this;
1084 }
1085
1096 public function addHiddenField( $name, $value, array $attribs = [] ) {
1097 if ( !is_array( $value ) ) {
1098 // Per WebRequest::getVal: Array values are discarded for security reasons.
1099 $attribs += [ 'name' => $name ];
1100 $this->mHiddenFields[] = [ $value, $attribs ];
1101 }
1102
1103 return $this;
1104 }
1105
1117 public function addHiddenFields( array $fields ) {
1118 foreach ( $fields as $name => $value ) {
1119 if ( is_array( $value ) ) {
1120 // Per WebRequest::getVal: Array values are discarded for security reasons.
1121 continue;
1122 }
1123 $this->mHiddenFields[] = [ $value, [ 'name' => $name ] ];
1124 }
1125
1126 return $this;
1127 }
1128
1152 public function addButton( $data ) {
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'
1158 );
1159 }
1160 $data = [
1161 'name' => $args[0],
1162 'value' => $args[1],
1163 'id' => $args[2] ?? null,
1164 'attribs' => $args[3] ?? null,
1165 ];
1166 } else {
1167 if ( !isset( $data['name'] ) ) {
1168 throw new InvalidArgumentException( 'A name is required' );
1169 }
1170 if ( !isset( $data['value'] ) ) {
1171 throw new InvalidArgumentException( 'A value is required' );
1172 }
1173 }
1174 $this->mButtons[] = $data + [
1175 'id' => null,
1176 'attribs' => null,
1177 'flags' => null,
1178 'framed' => true,
1179 ];
1180
1181 return $this;
1182 }
1183
1193 public function setTokenSalt( $salt ) {
1194 $this->mTokenSalt = $salt;
1195
1196 return $this;
1197 }
1198
1213 public function displayForm( $submitResult ) {
1214 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1215 }
1216
1220 private function getHiddenTitle(): string {
1221 if ( $this->hiddenTitleAddedToForm ) {
1222 return '';
1223 }
1224
1225 $html = '';
1226 if ( $this->getMethod() === 'post' ||
1227 $this->getAction() === $this->getConfig()->get( MainConfigNames::Script )
1228 ) {
1229 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1230 }
1231 $this->hiddenTitleAddedToForm = true;
1232 return $html;
1233 }
1234
1245 public function getHTML( $submitResult ) {
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',
1251 // Html::errorBox and Html::warningBox used by HtmlFormField and HtmlForm::getErrorsOrWarnings
1252 'mediawiki.codex.messagebox.styles'
1253 ] );
1254
1255 if ( $this->mCollapsible ) {
1256 // Preload jquery.makeCollapsible for mediawiki.htmlform
1257 $this->getOutput()->addModules( 'jquery.makeCollapsible' );
1258 }
1259
1260 $headerHtml = $this->getHeaderHtml();
1261 $footerHtml = $this->getFooterHtml();
1262 $html = $this->getErrorsOrWarnings( $submitResult, 'error' )
1263 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1264 . $headerHtml
1265 . $this->getHiddenTitle()
1266 . $this->getBody()
1267 . $this->getHiddenFields()
1268 . $this->getButtons()
1269 . $footerHtml;
1270
1271 return $this->mPre . $this->wrapForm( $html ) . $this->mPost;
1272 }
1273
1281 public function setCollapsibleOptions( $collapsedByDefault = false ) {
1282 $this->mCollapsible = true;
1283 $this->mCollapsed = $collapsedByDefault;
1284 return $this;
1285 }
1286
1292 protected function getFormAttributes() {
1293 # Use multipart/form-data
1294 $encType = $this->mUseMultipart
1295 ? 'multipart/form-data'
1296 : 'application/x-www-form-urlencoded';
1297 # Attributes
1298 $attribs = [
1299 'class' => 'mw-htmlform',
1300 'action' => $this->getAction(),
1301 'method' => $this->getMethod(),
1302 'enctype' => $encType,
1303 ];
1304 if ( $this->mId ) {
1305 $attribs['id'] = $this->mId;
1306 }
1307 if ( is_string( $this->mAutocomplete ) ) {
1308 $attribs['autocomplete'] = $this->mAutocomplete;
1309 }
1310 if ( $this->mName ) {
1311 $attribs['name'] = $this->mName;
1312 }
1313 if ( $this->needsJSForHtml5FormValidation() ) {
1314 $attribs['novalidate'] = true;
1315 }
1316 return $attribs;
1317 }
1318
1326 public function wrapForm( $html ) {
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(
1331 'fieldset',
1332 $this->mWrapperAttributes,
1333 ( $legend ? Html::element( 'legend', [], $legend ) : '' ) . $html
1334 );
1335 }
1336
1337 return Html::rawElement(
1338 'form',
1339 $this->getFormAttributes(),
1340 $html
1341 );
1342 }
1343
1348 public function getHiddenFields() {
1349 $html = '';
1350
1351 // add the title as a hidden file if it hasn't been added yet and if it is necessary
1352 // added for backward compatibility with the previous version of this public method
1353 $html .= $this->getHiddenTitle();
1354
1355 if ( $this->mFormIdentifier !== null ) {
1356 $html .= Html::hidden(
1357 'wpFormIdentifier',
1358 $this->mFormIdentifier
1359 ) . "\n";
1360 }
1361 if ( $this->getMethod() === 'post' ) {
1362 $html .= Html::hidden(
1363 'wpEditToken',
1364 $this->getUser()->getEditToken( $this->mTokenSalt ),
1365 [ 'id' => 'wpEditToken' ]
1366 ) . "\n";
1367 }
1368
1369 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1370 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
1371 }
1372
1373 return $html;
1374 }
1375
1381 public function getButtons() {
1382 $buttons = '';
1383
1384 if ( $this->mShowSubmit ) {
1385 $attribs = [];
1386
1387 if ( $this->mSubmitID !== null ) {
1388 $attribs['id'] = $this->mSubmitID;
1389 }
1390
1391 if ( $this->mSubmitName !== null ) {
1392 $attribs['name'] = $this->mSubmitName;
1393 }
1394
1395 if ( $this->mSubmitTooltip !== null ) {
1396 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1397 }
1398
1399 $attribs['class'] = [ 'mw-htmlform-submit' ];
1400
1401 $buttons .= Html::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1402 }
1403
1404 if ( $this->mShowCancel ) {
1405 $target = $this->getCancelTargetURL();
1406 $buttons .= Html::element(
1407 'a',
1408 [
1409 'href' => $target,
1410 ],
1411 $this->msg( 'cancel' )->text()
1412 ) . "\n";
1413 }
1414
1415 foreach ( $this->mButtons as $button ) {
1416 $attrs = [
1417 'type' => 'submit',
1418 'name' => $button['name'],
1419 'value' => $button['value']
1420 ];
1421
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'];
1428 } else {
1429 $label = htmlspecialchars( $button['value'] );
1430 }
1431
1432 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in self::addButton
1433 if ( $button['attribs'] ) {
1434 $attrs += $button['attribs'];
1435 }
1436
1437 if ( isset( $button['id'] ) ) {
1438 $attrs['id'] = $button['id'];
1439 }
1440
1441 $buttons .= Html::rawElement( 'button', $attrs, $label ) . "\n";
1442 }
1443
1444 if ( !$buttons ) {
1445 return '';
1446 }
1447
1448 return Html::rawElement( 'span',
1449 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1450 }
1451
1457 public function getBody() {
1458 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1459 }
1460
1470 public function getErrorsOrWarnings( $elements, $elementsType ) {
1471 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1472 throw new DomainException( $elementsType . ' is not a valid type.' );
1473 }
1474 $elementstr = false;
1475 if ( $elements instanceof Status ) {
1476 [ $errorStatus, $warningStatus ] = $elements->splitByErrorType();
1477 $status = $elementsType === 'error' ? $errorStatus : $warningStatus;
1478 if ( $status->isGood() ) {
1479 $elementstr = '';
1480 } else {
1481 $elementstr = $status
1482 ->getMessage()
1483 ->setContext( $this )
1484 ->setInterfaceMessageFlag( true )
1485 ->parse();
1486 }
1487 } elseif ( $elementsType === 'error' ) {
1488 if ( is_array( $elements ) ) {
1489 $elementstr = $this->formatErrors( $elements );
1490 } elseif ( $elements && $elements !== true ) {
1491 $elementstr = (string)$elements;
1492 }
1493 }
1494
1495 if ( !$elementstr ) {
1496 return '';
1497 } elseif ( $elementsType === 'error' ) {
1498 return Html::errorBox( $elementstr );
1499 } else { // $elementsType can only be 'warning'
1500 return Html::warningBox( $elementstr );
1501 }
1502 }
1503
1511 public function formatErrors( $errors ) {
1512 $errorstr = '';
1513
1514 foreach ( $errors as $error ) {
1515 $errorstr .= Html::rawElement(
1516 'li',
1517 [],
1518 $this->getMessage( $error )->parse()
1519 );
1520 }
1521
1522 return Html::rawElement( 'ul', [], $errorstr );
1523 }
1524
1533 public function setSubmitText( $t ) {
1534 $this->mSubmitText = $t;
1535
1536 return $this;
1537 }
1538
1545 public function setSubmitDestructive() {
1546 $this->mSubmitFlags = [ 'destructive', 'primary' ];
1547
1548 return $this;
1549 }
1550
1559 public function setSubmitTextMsg( $msg ) {
1560 if ( !$msg instanceof Message ) {
1561 $msg = $this->msg( $msg );
1562 }
1563 $this->setSubmitText( $msg->text() );
1564
1565 return $this;
1566 }
1567
1572 public function getSubmitText() {
1573 return $this->mSubmitText ?: $this->msg( 'htmlform-submit' )->text();
1574 }
1575
1581 public function setSubmitName( $name ) {
1582 $this->mSubmitName = $name;
1583
1584 return $this;
1585 }
1586
1592 public function setSubmitTooltip( $name ) {
1593 $this->mSubmitTooltip = $name;
1594
1595 return $this;
1596 }
1597
1606 public function setSubmitID( $t ) {
1607 $this->mSubmitID = $t;
1608
1609 return $this;
1610 }
1611
1630 public function setFormIdentifier( string $ident, bool $single = false ) {
1631 $this->mFormIdentifier = $ident;
1632 $this->mSingleForm = $single;
1633
1634 return $this;
1635 }
1636
1647 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1648 $this->mShowSubmit = !$suppressSubmit;
1649
1650 return $this;
1651 }
1652
1659 public function showCancel( $show = true ) {
1660 $this->mShowCancel = $show;
1661 return $this;
1662 }
1663
1670 public function setCancelTarget( $target ) {
1671 if ( $target instanceof PageReference ) {
1672 $target = TitleValue::castPageToLinkTarget( $target );
1673 }
1674
1675 $this->mCancelTarget = $target;
1676 return $this;
1677 }
1678
1683 protected function getCancelTargetURL() {
1684 if ( is_string( $this->mCancelTarget ) ) {
1685 return $this->mCancelTarget;
1686 } else {
1687 // TODO: use a service to get the local URL for a LinkTarget, see T282283
1688 $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1689 return $target->getLocalURL();
1690 }
1691 }
1692
1702 public function setTableId( $id ) {
1703 $this->mTableId = $id;
1704
1705 return $this;
1706 }
1707
1713 public function setId( $id ) {
1714 $this->mId = $id;
1715
1716 return $this;
1717 }
1718
1723 public function setName( $name ) {
1724 $this->mName = $name;
1725
1726 return $this;
1727 }
1728
1741 public function setWrapperLegend( $legend ) {
1742 $this->mWrapperLegend = $legend;
1743
1744 return $this;
1745 }
1746
1754 public function setWrapperAttributes( $attributes ) {
1755 $this->mWrapperAttributes = $attributes;
1756
1757 return $this;
1758 }
1759
1769 public function setWrapperLegendMsg( $msg ) {
1770 if ( !$msg instanceof Message ) {
1771 $msg = $this->msg( $msg );
1772 }
1773 $this->setWrapperLegend( $msg->text() );
1774
1775 return $this;
1776 }
1777
1787 public function setMessagePrefix( $p ) {
1788 $this->mMessagePrefix = $p;
1789
1790 return $this;
1791 }
1792
1800 public function setTitle( $t ) {
1801 // TODO: make mTitle a PageReference when we have a better way to get URLs, see T282283.
1802 $this->mTitle = Title::castFromPageReference( $t );
1803
1804 return $this;
1805 }
1806
1810 public function getTitle() {
1811 return $this->mTitle ?: $this->getContext()->getTitle();
1812 }
1813
1821 public function setMethod( $method = 'post' ) {
1822 $this->mMethod = strtolower( $method );
1823
1824 return $this;
1825 }
1826
1830 public function getMethod() {
1831 return $this->mMethod;
1832 }
1833
1844 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1845 return Html::rawElement(
1846 'fieldset',
1847 $attributes,
1848 Html::element( 'legend', [], $legend ) . $section
1849 ) . "\n";
1850 }
1851
1870 public function displaySection( $fields,
1871 $sectionName = '',
1872 $fieldsetIDPrefix = '',
1873 &$hasUserVisibleFields = false
1874 ) {
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.' );
1878 }
1879
1880 $html = [];
1881 $subsectionHtml = '';
1882 $hasLabel = false;
1883
1884 foreach ( $fields as $key => $value ) {
1885 if ( $value instanceof HTMLFormField ) {
1886 $v = array_key_exists( $key, $this->mFieldData )
1887 ? $this->mFieldData[$key]
1888 : $value->getDefault();
1889
1890 $retval = $this->formatField( $value, $v ?? '' );
1891
1892 // check, if the form field should be added to
1893 // the output.
1894 if ( $value->hasVisibleOutput() ) {
1895 $html[] = $retval;
1896
1897 $labelValue = trim( $value->getLabel() );
1898 if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
1899 $hasLabel = true;
1900 }
1901
1902 $hasUserVisibleFields = true;
1903 }
1904 } elseif ( is_array( $value ) ) {
1905 $subsectionHasVisibleFields = false;
1906 $section =
1907 $this->displaySection( $value,
1908 "mw-htmlform-$key",
1909 "$fieldsetIDPrefix$key-",
1910 $subsectionHasVisibleFields );
1911
1912 if ( $subsectionHasVisibleFields === true ) {
1913 // Display the section with various niceties.
1914 $hasUserVisibleFields = true;
1915
1916 $legend = $this->getLegend( $key );
1917
1918 $headerHtml = $this->getHeaderHtml( $key );
1919 $footerHtml = $this->getFooterHtml( $key );
1920 $section = $headerHtml .
1921 $section .
1922 $footerHtml;
1923
1924 $attributes = [];
1925 if ( $fieldsetIDPrefix ) {
1926 $attributes['id'] = Sanitizer::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1927 }
1928 $subsectionHtml .= $this->wrapFieldSetSection(
1929 $legend, $section, $attributes, $fields === $this->mFieldTree
1930 );
1931 } else {
1932 // Just return the inputs, nothing fancy.
1933 $subsectionHtml .= $section;
1934 }
1935 }
1936 }
1937
1938 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1939
1940 if ( $subsectionHtml ) {
1941 if ( $this->mSubSectionBeforeFields ) {
1942 return $subsectionHtml . "\n" . $html;
1943 } else {
1944 return $html . "\n" . $subsectionHtml;
1945 }
1946 } else {
1947 return $html;
1948 }
1949 }
1950
1959 protected function formatField( HTMLFormField $field, $value ) {
1960 $displayFormat = $this->getDisplayFormat();
1961 switch ( $displayFormat ) {
1962 case 'table':
1963 return $field->getTableRow( $value );
1964 case 'div':
1965 return $field->getDiv( $value );
1966 case 'raw':
1967 return $field->getRaw( $value );
1968 case 'inline':
1969 return $field->getInline( $value );
1970 default:
1971 throw new LogicException( 'Not implemented' );
1972 }
1973 }
1974
1983 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1984 if ( !$fieldsHtml ) {
1985 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1986 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1987 return '';
1988 }
1989
1990 $displayFormat = $this->getDisplayFormat();
1991 $html = implode( '', $fieldsHtml );
1992
1993 if ( $displayFormat === 'raw' ) {
1994 return $html;
1995 }
1996
1997 // Avoid strange spacing when no labels exist
1998 $attribs = $anyFieldHasLabel ? [] : [ 'class' => 'mw-htmlform-nolabel' ];
1999
2000 if ( $sectionName ) {
2001 $attribs['id'] = Sanitizer::escapeIdForAttribute( $sectionName );
2002 }
2003
2004 if ( $displayFormat === 'table' ) {
2005 return Html::rawElement( 'table',
2006 $attribs,
2007 Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
2008 } elseif ( $displayFormat === 'inline' ) {
2009 return Html::rawElement( 'span', $attribs, "\n$html\n" );
2010 } else {
2011 return Html::rawElement( 'div', $attribs, "\n$html\n" );
2012 }
2013 }
2014
2018 public function loadData() {
2019 $this->prepareForm();
2020 }
2021
2025 protected function loadFieldData() {
2026 $fieldData = [];
2027 $request = $this->getRequest();
2028
2029 foreach ( $this->mFlatFields as $fieldname => $field ) {
2030 if ( $field->skipLoadData( $request ) ) {
2031 continue;
2032 }
2033 if ( $field->mParams['disabled'] ?? false ) {
2034 $fieldData[$fieldname] = $field->getDefault();
2035 } else {
2036 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
2037 }
2038 }
2039
2040 // Reset to default for fields that are supposed to be disabled.
2041 // FIXME: Handle dependency chains, fields that a field checks on may need a reset too.
2042 foreach ( $fieldData as $name => &$value ) {
2043 $field = $this->mFlatFields[$name];
2044 if ( $field->isDisabled( $fieldData ) ) {
2045 $value = $field->getDefault();
2046 }
2047 }
2048
2049 # Filter data.
2050 foreach ( $fieldData as $name => &$value ) {
2051 $field = $this->mFlatFields[$name];
2052 $value = $field->filter( $value, $fieldData );
2053 }
2054
2055 $this->mFieldData = $fieldData;
2056 }
2057
2068 public function filterDataForSubmit( $data ) {
2069 return $data;
2070 }
2071
2081 public function getLegend( $key ) {
2082 return $this->msg( $this->mMessagePrefix ? "{$this->mMessagePrefix}-$key" : $key )->text();
2083 }
2084
2095 public function setAction( $action ) {
2096 $this->mAction = $action;
2097
2098 return $this;
2099 }
2100
2108 public function getAction() {
2109 // If an action is already provided, return it
2110 if ( $this->mAction !== false ) {
2111 return $this->mAction;
2112 }
2113
2114 $articlePath = $this->getConfig()->get( MainConfigNames::ArticlePath );
2115 // Check whether we are in GET mode and the ArticlePath contains a "?"
2116 // meaning that getLocalURL() would return something like "index.php?title=...".
2117 // As browser remove the query string before submitting GET forms,
2118 // it means that the title would be lost. In such case use script path instead
2119 // and put title in a hidden field (see getHiddenFields()).
2120 if ( str_contains( $articlePath, '?' ) && $this->getMethod() === 'get' ) {
2121 return $this->getConfig()->get( MainConfigNames::Script );
2122 }
2123
2124 return $this->getTitle()->getLocalURL();
2125 }
2126
2137 public function setAutocomplete( $autocomplete ) {
2138 $this->mAutocomplete = $autocomplete;
2139
2140 return $this;
2141 }
2142
2149 protected function getMessage( $value ) {
2150 return Message::newFromSpecifier( $value )->setContext( $this );
2151 }
2152
2163 foreach ( $this->mFlatFields as $field ) {
2164 if ( $field->needsJSForHtml5FormValidation() ) {
2165 return true;
2166 }
2167 }
2168 return false;
2169 }
2170}
2171
2173class_alias( HTMLForm::class, 'HTMLForm' );
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:71
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)
Text field for selecting a value from a large list of possible values, with auto-completion and optio...
Adds a generic button inline to the form.
A checkbox matrix Operates similarly to HTMLMultiSelectField, but instead of using an array of option...
A field that will contain a date and/or time.
Expiry Field that allows the user to specify a precise date or a relative date string.
A field that will contain a numeric value.
A container for HTMLFormFields that allows for multiple copies of the set of fields to be displayed t...
An information field (text blob), not a proper input.
A field that must contain a number.
Implements a tag multiselect input field for namespaces.
Implements a tag multiselect input field with a searchable dropdown containing valid tags.
Double field with a dropdown list constructed from a system message in the format.
A limit dropdown, which accepts any valid number.
Creates a Html::namespaceSelector input field with a button assigned to the input field.
Wrapper for Html::namespaceSelector to use in HTMLForm.
Select dropdown field, with an additional "other" textbox.
A size filter field for use on query-type special pages.
Add a submit button inline in the form (as opposed to HTMLForm::addButton(), which will add it at the...
Wrapper for ChangeTags::buildTagFilterSelector to use in HTMLForm.
Implements a tag multiselect input field for arbitrary values.
Creates a text input field with a button assigned to the input field.
Dropdown widget that allows the user to select a timezone, either by choosing a geographic zone,...
Implements a text input field for page titles.
Implements a tag multiselect input field for titles.
Implements a text input field for user names.
Implements a tag multiselect input field for user names.
The parent class to generate form fields.
getDiv( $value)
Get the complete div for the input, including help text, labels, and whatever.
getTableRow( $value)
Get the complete table row for the input, including help text, labels, and whatever.
getRaw( $value)
Get the complete raw fields for the input, including help text, labels, and whatever.
getInline( $value)
Get the complete field as an inline element.
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition HTMLForm.php:214
wrapForm( $html)
Wrap the form innards in an actual "<form>" element.
displayForm( $submitResult)
Display the form (sending to the context's OutputPage object), with an appropriate error message or s...
setHeaderHtml( $html, $section=null)
Set header HTML, inside the form.
Definition HTMLForm.php:955
needsJSForHtml5FormValidation()
Whether this form, with its current fields, requires the user agent to have JavaScript enabled for th...
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element.
showCancel( $show=true)
Show a cancel button (or prevent it).
setMessagePrefix( $p)
Set the prefix for various default messages.
array[] $mSections
Additional information about form sections.
Definition HTMLForm.php:399
wrapFieldSetSection( $legend, $section, $attributes, $isRoot)
Wraps the given $section into a user-visible fieldset.
callable null $mSubmitCallback
Definition HTMLForm.php:288
getHeaderHtml( $section=null)
Get header HTML.
Definition HTMLForm.php:973
bool $mCollapsed
Whether the form is collapsed by default.
Definition HTMLForm.php:354
setFormIdentifier(string $ident, bool $single=false)
Set an internal identifier for this form.
trySubmit()
Validate all the fields, and call the submission callback function if everything is kosher.
Definition HTMLForm.php:764
array $availableSubclassDisplayFormats
Available formats in which to display the form.
Definition HTMLForm.php:433
setAction( $action)
Set the value for the action attribute of the form.
setPreHtml( $html)
Set the introductory message HTML, overwriting any existing message.
Definition HTMLForm.php:896
setTokenSalt( $salt)
Set the salt for the edit token.
setFooterHtml( $html, $section=null)
Set footer HTML, inside the form.
suppressDefaultSubmit( $suppressSubmit=true)
Stop a default submit button being shown for this form.
requestIsAuthorized()
Return true if the http request passes identity and csrf checks.
Definition HTMLForm.php:692
loadFieldData()
Load data of form fields from the request.
tryAuthorizedSubmit()
Try submitting, with edit token check first.
Definition HTMLForm.php:676
wasSubmitted()
Test whether the form was considered to have been submitted or not, i.e.
Definition HTMLForm.php:853
getFormAttributes()
Get HTML attributes for the <form> tag.
static getClassFromDescriptor( $fieldname, &$descriptor)
Get the HTMLFormField subclass for this descriptor.
Definition HTMLForm.php:608
getMessage( $value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name,...
prepareForm()
Prepare form for submission.
Definition HTMLForm.php:657
LinkTarget string null $mCancelTarget
Definition HTMLForm.php:285
bool $mCollapsible
Whether the form can be collapsed.
Definition HTMLForm.php:347
addHiddenField( $name, $value, array $attribs=[])
Add a hidden field to the output Array values are discarded for security reasons (per WebRequest::get...
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
setAutocomplete( $autocomplete)
Set the value for the autocomplete attribute of the form.
getBody()
Get the whole body of the form.
bool $mSubSectionBeforeFields
If true, sections that contain both fields and subsections will render their subsections before their...
Definition HTMLForm.php:409
string $displayFormat
Format in which to display form.
Definition HTMLForm.php:416
static loadInputFromParameters( $fieldname, $descriptor, self $parent)
Initialise a new Object for the field.
Definition HTMLForm.php:637
setWrapperAttributes( $attributes)
For internal use only.
string null $mAutocomplete
Form attribute autocomplete.
Definition HTMLForm.php:361
getDisplayFormat()
Getter for displayFormat.
Definition HTMLForm.php:588
formatSection(array $fieldsHtml, $sectionName, $anyFieldHasLabel)
Put a form section together from the individual fields' HTML, merging it and wrapping.
setDisplayFormat( $format)
Set format in which to display the form.
Definition HTMLForm.php:558
string array $mTokenSalt
Salt for the edit token.
Definition HTMLForm.php:385
getHTML( $submitResult)
Returns the raw HTML generated by the form.
addButton( $data)
Add a button to the form.
getHiddenFields()
Get the hidden fields that should go inside the form.
setTableId( $id)
Set the id of the <table> or outermost <div> element.
setWrapperLegend( $legend)
Prompt the whole form to be wrapped in a "<fieldset>", with this text as its "<legend>" element.
addFooterHtml( $html, $section=null)
Add footer HTML, inside the form.
Definition HTMLForm.php:986
showAlways()
Same as self::show with the difference, that the form will be added to the output,...
Definition HTMLForm.php:743
displaySection( $fields, $sectionName='', $fieldsetIDPrefix='', &$hasUserVisibleFields=false)
addFields( $descriptor)
Add fields to the form.
Definition HTMLForm.php:500
setSubmitText( $t)
Set the text for the submit button.
setPostHtml( $html)
Set HTML at the end of the display.
getFooterHtml( $section=null)
Get footer HTML.
setTitle( $t)
Set the title for form submission.
setSubmitCallback( $cb)
Set a callback to a function to do something with the form once it's been successfully validated.
Definition HTMLForm.php:867
getSubmitText()
Get the text for the submit button, either customised or a default.
addHiddenFields(array $fields)
Add an array of hidden fields to the output Array values are discarded for security reasons (per WebR...
show()
The here's-one-I-made-earlier option: do the submission if posted, or display the form with or withou...
Definition HTMLForm.php:725
formatField(HTMLFormField $field, $value)
Generate the HTML for an individual field in the current display format.
setSections( $sections)
Set an array of information about sections.
formatErrors( $errors)
Format a stack of error messages into a single HTML string.
setValidationErrorMessage( $msg)
Set a message to display on a validation error.
Definition HTMLForm.php:882
HTMLFormField[] $mFlatFields
Definition HTMLForm.php:275
setSubmitDestructive()
Identify that the submit button in the form has a destructive action.
getErrorsOrWarnings( $elements, $elementsType)
Returns a formatted list of errors or warnings from the given elements.
addPreHtml( $html)
Add HTML to introductory message.
Definition HTMLForm.php:910
setSubmitID( $t)
Set the id for the submit button.
array $availableDisplayFormats
Available formats in which to display the form.
Definition HTMLForm.php:422
getPostHtml()
Get HTML at the end of the display.
getLegend( $key)
Get a string to go in the "<legend>" of a section fieldset.
setCancelTarget( $target)
Sets the target where the user is redirected to after clicking cancel.
addHeaderHtml( $html, $section=null)
Add HTML to the header, inside the form.
Definition HTMLForm.php:935
static factory( $displayFormat, $descriptor, IContextSource $context, $messagePrefix='')
Construct a HTMLForm object for given display type.
Definition HTMLForm.php:457
setCollapsibleOptions( $collapsedByDefault=false)
Enable collapsible mode, and set whether the form is collapsed by default.
getAction()
Get the value for the action attribute of the form.
setMethod( $method='post')
Set the method used to submit the form.
getPreHtml()
Get the introductory message HTML.
Definition HTMLForm.php:922
getButtons()
Get the submit and (potentially) reset buttons.
static string[] $typeMappings
A mapping of 'type' inputs onto standard HTMLFormField subclasses.
Definition HTMLForm.php:218
filterDataForSubmit( $data)
Overload this if you want to apply special filtration routines to the form as a whole,...
__construct( $descriptor, IContextSource $context, $messagePrefix='')
Build a new HTMLForm from an array of field attributes.
Definition HTMLForm.php:483
string false $mAction
Form action URL.
Definition HTMLForm.php:340
addPostHtml( $html)
Add HTML to the end of the display.
Compact stacked vertical format for forms, implemented using OOUI widgets.
This class is a collection of static functions that serve two purposes:
Definition Html.php:44
Some internal bits split of from Skin.php.
Definition Linker.php:48
A class containing constants representing the names of configuration variables.
const Script
Name constant for the Script setting, for use with Config::get()
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:144
HTML sanitizer for MediaWiki.
Definition Sanitizer.php:34
Stores and matches CSRF tokens belonging to a given session user.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:44
Represents the target of a wiki link.
Represents a title within MediaWiki.
Definition Title.php:69
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.
Value object representing a message parameter with one of the types from {.
Interface for objects which can provide a MediaWiki context on request.
Represents the target of a wiki link.
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.