MediaWiki REL1_37
HTMLForm.php
Go to the documentation of this file.
1<?php
2
24use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
27
143class HTMLForm extends ContextSource {
144 use ProtectedHookAccessorTrait;
145
147 public static $typeMappings = [
148 'api' => HTMLApiField::class,
149 'text' => HTMLTextField::class,
150 'textwithbutton' => HTMLTextFieldWithButton::class,
151 'textarea' => HTMLTextAreaField::class,
152 'select' => HTMLSelectField::class,
153 'combobox' => HTMLComboboxField::class,
154 'radio' => HTMLRadioField::class,
155 'multiselect' => HTMLMultiSelectField::class,
156 'limitselect' => HTMLSelectLimitField::class,
157 'check' => HTMLCheckField::class,
158 'toggle' => HTMLCheckField::class,
159 'int' => HTMLIntField::class,
160 'file' => HTMLFileField::class,
161 'float' => HTMLFloatField::class,
162 'info' => HTMLInfoField::class,
163 'selectorother' => HTMLSelectOrOtherField::class,
164 'selectandother' => HTMLSelectAndOtherField::class,
165 'namespaceselect' => HTMLSelectNamespace::class,
166 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
167 'tagfilter' => HTMLTagFilter::class,
168 'sizefilter' => HTMLSizeFilterField::class,
169 'submit' => HTMLSubmitField::class,
170 'hidden' => HTMLHiddenField::class,
171 'edittools' => HTMLEditTools::class,
172 'checkmatrix' => HTMLCheckMatrix::class,
173 'cloner' => HTMLFormFieldCloner::class,
174 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
175 'language' => HTMLSelectLanguageField::class,
176 'date' => HTMLDateTimeField::class,
177 'time' => HTMLDateTimeField::class,
178 'datetime' => HTMLDateTimeField::class,
179 'expiry' => HTMLExpiryField::class,
180 // HTMLTextField will output the correct type="" attribute automagically.
181 // There are about four zillion other HTML5 input types, like range, but
182 // we don't use those at the moment, so no point in adding all of them.
183 'email' => HTMLTextField::class,
184 'password' => HTMLTextField::class,
185 'url' => HTMLTextField::class,
186 'title' => HTMLTitleTextField::class,
187 'user' => HTMLUserTextField::class,
188 'tagmultiselect' => HTMLTagMultiselectField::class,
189 'usersmultiselect' => HTMLUsersMultiselectField::class,
190 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
191 'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
192 ];
193
195
197
199 protected $mFlatFields = [];
200 protected $mFieldTree = [];
201 protected $mShowReset = false;
202 protected $mShowSubmit = true;
204 protected $mSubmitFlags = [ 'primary', 'progressive' ];
205 protected $mShowCancel = false;
206 protected $mCancelTarget;
207
210
211 protected $mPre = '';
212 protected $mHeader = '';
213 protected $mFooter = '';
214 protected $mSectionHeaders = [];
215 protected $mSectionFooters = [];
216 protected $mPost = '';
217 protected $mId;
218 protected $mName;
219 protected $mTableId = '';
220
221 protected $mSubmitID;
222 protected $mSubmitName;
223 protected $mSubmitText;
225
227 protected $mTitle;
228 protected $mMethod = 'post';
229 protected $mWasSubmitted = false;
230
236 protected $mAction = false;
237
243 protected $mCollapsible = false;
244
250 protected $mCollapsed = false;
251
257 protected $mAutocomplete = null;
258
259 protected $mUseMultipart = false;
264 protected $mHiddenFields = [];
269 protected $mButtons = [];
270
271 protected $mWrapperLegend = false;
272 protected $mWrapperAttributes = [];
273
278 protected $mTokenSalt = '';
279
288 protected $mSubSectionBeforeFields = true;
289
295 protected $displayFormat = 'table';
296
302 'table',
303 'div',
304 'raw',
305 'inline',
306 ];
307
313 'vform',
314 'ooui',
315 ];
316
326 public static function factory( $displayFormat, ...$arguments ) {
327 switch ( $displayFormat ) {
328 case 'vform':
329 return new VFormHTMLForm( ...$arguments );
330 case 'ooui':
331 return new OOUIHTMLForm( ...$arguments );
332 default:
333 $form = new self( ...$arguments );
334 $form->setDisplayFormat( $displayFormat );
335 return $form;
336 }
337 }
338
350 public function __construct( $descriptor, /*IContextSource*/ $context = null,
351 $messagePrefix = ''
352 ) {
353 if ( $context instanceof IContextSource ) {
354 $this->setContext( $context );
355 $this->mTitle = false; // We don't need them to set a title
356 $this->mMessagePrefix = $messagePrefix;
357 } elseif ( $context === null && $messagePrefix !== '' ) {
358 $this->mMessagePrefix = $messagePrefix;
359 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
360 // B/C since 1.18
361 // it's actually $messagePrefix
362 $this->mMessagePrefix = $context;
363 }
364
365 // Evil hack for mobile :(
366 if (
367 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
368 && $this->displayFormat === 'table'
369 ) {
370 $this->displayFormat = 'div';
371 }
372
373 $this->addFields( $descriptor );
374 }
375
385 public function addFields( $descriptor ) {
386 $loadedDescriptor = [];
387
388 foreach ( $descriptor as $fieldname => $info ) {
389
390 $section = $info['section'] ?? '';
391
392 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
393 $this->mUseMultipart = true;
394 }
395
396 $field = static::loadInputFromParameters( $fieldname, $info, $this );
397
398 $setSection =& $loadedDescriptor;
399 if ( $section ) {
400 foreach ( explode( '/', $section ) as $newName ) {
401 if ( !isset( $setSection[$newName] ) ) {
402 $setSection[$newName] = [];
403 }
404
405 $setSection =& $setSection[$newName];
406 }
407 }
408
409 $setSection[$fieldname] = $field;
410 $this->mFlatFields[$fieldname] = $field;
411 }
412
413 $this->mFieldTree = array_merge( $this->mFieldTree, $loadedDescriptor );
414
415 return $this;
416 }
417
422 public function hasField( $fieldname ) {
423 return isset( $this->mFlatFields[$fieldname] );
424 }
425
431 public function getField( $fieldname ) {
432 if ( !$this->hasField( $fieldname ) ) {
433 throw new DomainException( __METHOD__ . ': no field named ' . $fieldname );
434 }
435 return $this->mFlatFields[$fieldname];
436 }
437
448 public function setDisplayFormat( $format ) {
449 if (
450 in_array( $format, $this->availableSubclassDisplayFormats, true ) ||
451 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats, true )
452 ) {
453 throw new MWException( 'Cannot change display format after creation, ' .
454 'use HTMLForm::factory() instead' );
455 }
456
457 if ( !in_array( $format, $this->availableDisplayFormats, true ) ) {
458 throw new MWException( 'Display format must be one of ' .
459 print_r(
460 array_merge(
461 $this->availableDisplayFormats,
462 $this->availableSubclassDisplayFormats
463 ),
464 true
465 ) );
466 }
467
468 // Evil hack for mobile :(
469 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
470 $format = 'div';
471 }
472
473 $this->displayFormat = $format;
474
475 return $this;
476 }
477
483 public function getDisplayFormat() {
484 return $this->displayFormat;
485 }
486
504 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
505 if ( isset( $descriptor['class'] ) ) {
506 $class = $descriptor['class'];
507 } elseif ( isset( $descriptor['type'] ) ) {
508 $class = static::$typeMappings[$descriptor['type']];
509 $descriptor['class'] = $class;
510 } else {
511 $class = null;
512 }
513
514 if ( !$class ) {
515 throw new MWException( "Descriptor with no class for $fieldname: "
516 . print_r( $descriptor, true ) );
517 }
518
519 return $class;
520 }
521
534 public static function loadInputFromParameters( $fieldname, $descriptor,
535 HTMLForm $parent = null
536 ) {
537 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
538
539 $descriptor['fieldname'] = $fieldname;
540 if ( $parent ) {
541 $descriptor['parent'] = $parent;
542 }
543
544 # @todo This will throw a fatal error whenever someone try to use
545 # 'class' to feed a CSS class instead of 'cssclass'. Would be
546 # great to avoid the fatal error and show a nice error.
547 return new $class( $descriptor );
548 }
549
559 public function prepareForm() {
560 # Check if we have the info we need
561 if ( !$this->mTitle instanceof PageReference && $this->mTitle !== false ) {
562 throw new MWException( 'You must call setTitle() on an HTMLForm' );
563 }
564
565 # Load data from the request.
566 if (
567 $this->mFormIdentifier === null ||
568 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
569 ) {
570 $this->loadData();
571 } else {
572 $this->mFieldData = [];
573 }
574
575 return $this;
576 }
577
582 public function tryAuthorizedSubmit() {
583 $result = false;
584
585 if ( $this->mFormIdentifier === null ) {
586 $identOkay = true;
587 } else {
588 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier;
589 }
590
591 $tokenOkay = false;
592 if ( $this->getMethod() !== 'post' ) {
593 $tokenOkay = true; // no session check needed
594 } elseif ( $this->getRequest()->wasPosted() ) {
595 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
596 if ( $this->getUser()->isRegistered() || $editToken !== null ) {
597 // Session tokens for logged-out users have no security value.
598 // However, if the user gave one, check it in order to give a nice
599 // "session expired" error instead of "permission denied" or such.
600 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
601 } else {
602 $tokenOkay = true;
603 }
604 }
605
606 if ( $tokenOkay && $identOkay ) {
607 $this->mWasSubmitted = true;
608 $result = $this->trySubmit();
609 }
610
611 return $result;
612 }
613
621 public function show() {
622 $this->prepareForm();
623
624 $result = $this->tryAuthorizedSubmit();
625 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
626 return $result;
627 }
628
629 $this->displayForm( $result );
630
631 return false;
632 }
633
639 public function showAlways() {
640 $this->prepareForm();
641
642 $result = $this->tryAuthorizedSubmit();
643
644 $this->displayForm( $result );
645
646 return $result;
647 }
648
661 public function trySubmit() {
662 $valid = true;
663 $hoistedErrors = Status::newGood();
664 if ( $this->mValidationErrorMessage ) {
665 foreach ( $this->mValidationErrorMessage as $error ) {
666 $hoistedErrors->fatal( ...$error );
667 }
668 } else {
669 $hoistedErrors->fatal( 'htmlform-invalid-input' );
670 }
671
672 $this->mWasSubmitted = true;
673
674 # Check for cancelled submission
675 foreach ( $this->mFlatFields as $fieldname => $field ) {
676 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
677 continue;
678 }
679 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
680 $this->mWasSubmitted = false;
681 return false;
682 }
683 }
684
685 # Check for validation
686 foreach ( $this->mFlatFields as $fieldname => $field ) {
687 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
688 continue;
689 }
690 if ( $field->isHidden( $this->mFieldData ) ) {
691 continue;
692 }
693 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
694 if ( $res !== true ) {
695 $valid = false;
696 if ( $res !== false && !$field->canDisplayErrors() ) {
697 if ( is_string( $res ) ) {
698 $hoistedErrors->fatal( 'rawmessage', $res );
699 } else {
700 $hoistedErrors->fatal( $res );
701 }
702 }
703 }
704 }
705
706 if ( !$valid ) {
707 return $hoistedErrors;
708 }
709
710 $callback = $this->mSubmitCallback;
711 if ( !is_callable( $callback ) ) {
712 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
713 'setSubmitCallback() to set one.' );
714 }
715
716 $data = $this->filterDataForSubmit( $this->mFieldData );
717
718 $res = call_user_func( $callback, $data, $this );
719 if ( $res === false ) {
720 $this->mWasSubmitted = false;
721 }
722
723 return $res;
724 }
725
737 public function wasSubmitted() {
738 return $this->mWasSubmitted;
739 }
740
751 public function setSubmitCallback( $cb ) {
752 $this->mSubmitCallback = $cb;
753
754 return $this;
755 }
756
765 public function setValidationErrorMessage( $msg ) {
766 $this->mValidationErrorMessage = $msg;
767
768 return $this;
769 }
770
778 public function setIntro( $msg ) {
779 $this->setPreText( $msg );
780
781 return $this;
782 }
783
792 public function setPreText( $msg ) {
793 $this->mPre = $msg;
794
795 return $this;
796 }
797
805 public function addPreText( $msg ) {
806 $this->mPre .= $msg;
807
808 return $this;
809 }
810
818 public function getPreText() {
819 return $this->mPre;
820 }
821
830 public function addHeaderText( $msg, $section = null ) {
831 if ( $section === null ) {
832 $this->mHeader .= $msg;
833 } else {
834 if ( !isset( $this->mSectionHeaders[$section] ) ) {
835 $this->mSectionHeaders[$section] = '';
836 }
837 $this->mSectionHeaders[$section] .= $msg;
838 }
839
840 return $this;
841 }
842
852 public function setHeaderText( $msg, $section = null ) {
853 if ( $section === null ) {
854 $this->mHeader = $msg;
855 } else {
856 $this->mSectionHeaders[$section] = $msg;
857 }
858
859 return $this;
860 }
861
870 public function getHeaderText( $section = null ) {
871 if ( $section === null ) {
872 return $this->mHeader;
873 } else {
874 return $this->mSectionHeaders[$section] ?? '';
875 }
876 }
877
886 public function addFooterText( $msg, $section = null ) {
887 if ( $section === null ) {
888 $this->mFooter .= $msg;
889 } else {
890 if ( !isset( $this->mSectionFooters[$section] ) ) {
891 $this->mSectionFooters[$section] = '';
892 }
893 $this->mSectionFooters[$section] .= $msg;
894 }
895
896 return $this;
897 }
898
908 public function setFooterText( $msg, $section = null ) {
909 if ( $section === null ) {
910 $this->mFooter = $msg;
911 } else {
912 $this->mSectionFooters[$section] = $msg;
913 }
914
915 return $this;
916 }
917
925 public function getFooterText( $section = null ) {
926 if ( $section === null ) {
927 return $this->mFooter;
928 } else {
929 return $this->mSectionFooters[$section] ?? '';
930 }
931 }
932
940 public function addPostText( $msg ) {
941 $this->mPost .= $msg;
942
943 return $this;
944 }
945
953 public function setPostText( $msg ) {
954 $this->mPost = $msg;
955
956 return $this;
957 }
958
968 public function addHiddenField( $name, $value, array $attribs = [] ) {
969 $attribs += [ 'name' => $name ];
970 $this->mHiddenFields[] = [ $value, $attribs ];
971
972 return $this;
973 }
974
985 public function addHiddenFields( array $fields ) {
986 foreach ( $fields as $name => $value ) {
987 $this->mHiddenFields[] = [ $value, [ 'name' => $name ] ];
988 }
989
990 return $this;
991 }
992
1016 public function addButton( $data ) {
1017 if ( !is_array( $data ) ) {
1018 $args = func_get_args();
1019 if ( count( $args ) < 2 || count( $args ) > 4 ) {
1020 throw new InvalidArgumentException(
1021 'Incorrect number of arguments for deprecated calling style'
1022 );
1023 }
1024 $data = [
1025 'name' => $args[0],
1026 'value' => $args[1],
1027 'id' => $args[2] ?? null,
1028 'attribs' => $args[3] ?? null,
1029 ];
1030 } else {
1031 if ( !isset( $data['name'] ) ) {
1032 throw new InvalidArgumentException( 'A name is required' );
1033 }
1034 if ( !isset( $data['value'] ) ) {
1035 throw new InvalidArgumentException( 'A value is required' );
1036 }
1037 }
1038 $this->mButtons[] = $data + [
1039 'id' => null,
1040 'attribs' => null,
1041 'flags' => null,
1042 'framed' => true,
1043 ];
1044
1045 return $this;
1046 }
1047
1057 public function setTokenSalt( $salt ) {
1058 $this->mTokenSalt = $salt;
1059
1060 return $this;
1061 }
1062
1077 public function displayForm( $submitResult ) {
1078 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1079 }
1080
1091 public function getHTML( $submitResult ) {
1092 # For good measure (it is the default)
1093 $this->getOutput()->preventClickjacking();
1094 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1095 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1096
1097 if ( $this->mCollapsible ) {
1098 // Preload jquery.makeCollapsible for mediawiki.htmlform
1099 $this->getOutput()->addModules( 'jquery.makeCollapsible' );
1100 }
1101
1102 $html = ''
1103 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1104 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1105 . $this->getHeaderText()
1106 . $this->getBody()
1107 . $this->getHiddenFields()
1108 . $this->getButtons()
1109 . $this->getFooterText();
1110
1111 $html = $this->wrapForm( $html );
1112
1113 return '' . $this->mPre . $html . $this->mPost;
1114 }
1115
1123 public function setCollapsibleOptions( $collapsedByDefault = false ) {
1124 $this->mCollapsible = true;
1125 $this->mCollapsed = $collapsedByDefault;
1126 return $this;
1127 }
1128
1134 protected function getFormAttributes() {
1135 # Use multipart/form-data
1136 $encType = $this->mUseMultipart
1137 ? 'multipart/form-data'
1138 : 'application/x-www-form-urlencoded';
1139 # Attributes
1140 $attribs = [
1141 'class' => 'mw-htmlform',
1142 'action' => $this->getAction(),
1143 'method' => $this->getMethod(),
1144 'enctype' => $encType,
1145 ];
1146 if ( $this->mId ) {
1147 $attribs['id'] = $this->mId;
1148 }
1149 if ( is_string( $this->mAutocomplete ) ) {
1150 $attribs['autocomplete'] = $this->mAutocomplete;
1151 }
1152 if ( $this->mName ) {
1153 $attribs['name'] = $this->mName;
1154 }
1155 if ( $this->needsJSForHtml5FormValidation() ) {
1156 $attribs['novalidate'] = true;
1157 }
1158 return $attribs;
1159 }
1160
1169 public function wrapForm( $html ) {
1170 # Include a <fieldset> wrapper for style, if requested.
1171 if ( $this->mWrapperLegend !== false ) {
1172 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend : false;
1173 $html = Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1174 }
1175
1176 return Html::rawElement(
1177 'form',
1178 $this->getFormAttributes(),
1179 $html
1180 );
1181 }
1182
1187 public function getHiddenFields() {
1188 $html = '';
1189 if ( $this->mFormIdentifier !== null ) {
1190 $html .= Html::hidden(
1191 'wpFormIdentifier',
1192 $this->mFormIdentifier
1193 ) . "\n";
1194 }
1195 if ( $this->getMethod() === 'post' ) {
1196 $html .= Html::hidden(
1197 'wpEditToken',
1198 $this->getUser()->getEditToken( $this->mTokenSalt ),
1199 [ 'id' => 'wpEditToken' ]
1200 ) . "\n";
1201 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1202 }
1203
1204 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1205 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1206 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1207 }
1208
1209 foreach ( $this->mHiddenFields as [ $value, $attribs ] ) {
1210 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
1211 }
1212
1213 return $html;
1214 }
1215
1221 public function getButtons() {
1222 $buttons = '';
1223 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1224
1225 if ( $this->mShowSubmit ) {
1226 $attribs = [];
1227
1228 if ( isset( $this->mSubmitID ) ) {
1229 $attribs['id'] = $this->mSubmitID;
1230 }
1231
1232 if ( isset( $this->mSubmitName ) ) {
1233 $attribs['name'] = $this->mSubmitName;
1234 }
1235
1236 if ( isset( $this->mSubmitTooltip ) ) {
1237 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1238 }
1239
1240 $attribs['class'] = [ 'mw-htmlform-submit' ];
1241
1242 if ( $useMediaWikiUIEverywhere ) {
1243 foreach ( $this->mSubmitFlags as $flag ) {
1244 $attribs['class'][] = 'mw-ui-' . $flag;
1245 }
1246 $attribs['class'][] = 'mw-ui-button';
1247 }
1248
1249 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1250 }
1251
1252 if ( $this->mShowReset ) {
1253 $buttons .= Html::element(
1254 'input',
1255 [
1256 'type' => 'reset',
1257 'value' => $this->msg( 'htmlform-reset' )->text(),
1258 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1259 ]
1260 ) . "\n";
1261 }
1262
1263 if ( $this->mShowCancel ) {
1264 $target = $this->getCancelTargetURL();
1265 $buttons .= Html::element(
1266 'a',
1267 [
1268 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1269 'href' => $target,
1270 ],
1271 $this->msg( 'cancel' )->text()
1272 ) . "\n";
1273 }
1274
1275 foreach ( $this->mButtons as $button ) {
1276 $attrs = [
1277 'type' => 'submit',
1278 'name' => $button['name'],
1279 'value' => $button['value']
1280 ];
1281
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'];
1288 } else {
1289 $label = htmlspecialchars( $button['value'] );
1290 }
1291
1292 if ( $button['attribs'] ) {
1293 $attrs += $button['attribs'];
1294 }
1295
1296 if ( isset( $button['id'] ) ) {
1297 $attrs['id'] = $button['id'];
1298 }
1299
1300 if ( $useMediaWikiUIEverywhere ) {
1301 $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : [];
1302 $attrs['class'][] = 'mw-ui-button';
1303 }
1304
1305 $buttons .= Html::rawElement( 'button', $attrs, $label ) . "\n";
1306 }
1307
1308 if ( !$buttons ) {
1309 return '';
1310 }
1311
1312 return Html::rawElement( 'span',
1313 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1314 }
1315
1321 public function getBody() {
1322 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1323 }
1324
1334 public function getErrorsOrWarnings( $elements, $elementsType ) {
1335 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1336 throw new DomainException( $elementsType . ' is not a valid type.' );
1337 }
1338 $elementstr = false;
1339 if ( $elements instanceof Status ) {
1340 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1341 $status = $elementsType === 'error' ? $errorStatus : $warningStatus;
1342 if ( $status->isGood() ) {
1343 $elementstr = '';
1344 } else {
1345 $elementstr = $status
1346 ->getMessage()
1347 ->setContext( $this )
1348 ->setInterfaceMessageFlag( true )
1349 ->parse();
1350 }
1351 } elseif ( $elementsType === 'error' ) {
1352 if ( is_array( $elements ) ) {
1353 $elementstr = $this->formatErrors( $elements );
1354 } elseif ( $elements && $elements !== true ) {
1355 $elementstr = (string)$elements;
1356 }
1357 }
1358
1359 return $elementstr
1360 ? Html::rawElement( 'div', [ 'class' => $elementsType . 'box' ], $elementstr )
1361 : '';
1362 }
1363
1371 public function formatErrors( $errors ) {
1372 $errorstr = '';
1373
1374 foreach ( $errors as $error ) {
1375 $errorstr .= Html::rawElement(
1376 'li',
1377 [],
1378 $this->getMessage( $error )->parse()
1379 );
1380 }
1381
1382 $errorstr = Html::rawElement( 'ul', [], $errorstr );
1383
1384 return $errorstr;
1385 }
1386
1394 public function setSubmitText( $t ) {
1395 $this->mSubmitText = $t;
1396
1397 return $this;
1398 }
1399
1406 public function setSubmitDestructive() {
1407 $this->mSubmitFlags = [ 'destructive', 'primary' ];
1408
1409 return $this;
1410 }
1411
1420 public function setSubmitTextMsg( $msg ) {
1421 if ( !$msg instanceof Message ) {
1422 $msg = $this->msg( $msg );
1423 }
1424 $this->setSubmitText( $msg->text() );
1425
1426 return $this;
1427 }
1428
1433 public function getSubmitText() {
1434 return $this->mSubmitText ?: $this->msg( 'htmlform-submit' )->text();
1435 }
1436
1442 public function setSubmitName( $name ) {
1443 $this->mSubmitName = $name;
1444
1445 return $this;
1446 }
1447
1453 public function setSubmitTooltip( $name ) {
1454 $this->mSubmitTooltip = $name;
1455
1456 return $this;
1457 }
1458
1467 public function setSubmitID( $t ) {
1468 $this->mSubmitID = $t;
1469
1470 return $this;
1471 }
1472
1488 public function setFormIdentifier( $ident ) {
1489 $this->mFormIdentifier = $ident;
1490
1491 return $this;
1492 }
1493
1504 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1505 $this->mShowSubmit = !$suppressSubmit;
1506
1507 return $this;
1508 }
1509
1516 public function showCancel( $show = true ) {
1517 $this->mShowCancel = $show;
1518 return $this;
1519 }
1520
1527 public function setCancelTarget( $target ) {
1528 if ( $target instanceof PageReference ) {
1529 $target = TitleValue::castPageToLinkTarget( $target );
1530 }
1531
1532 $this->mCancelTarget = $target;
1533 return $this;
1534 }
1535
1540 protected function getCancelTargetURL() {
1541 if ( is_string( $this->mCancelTarget ) ) {
1542 return $this->mCancelTarget;
1543 } else {
1544 // TODO: use a service to get the local URL for a LinkTarget, see T282283
1545 $target = Title::castFromLinkTarget( $this->mCancelTarget ) ?: Title::newMainPage();
1546 return $target->getLocalURL();
1547 }
1548 }
1549
1559 public function setTableId( $id ) {
1560 $this->mTableId = $id;
1561
1562 return $this;
1563 }
1564
1570 public function setId( $id ) {
1571 $this->mId = $id;
1572
1573 return $this;
1574 }
1575
1580 public function setName( $name ) {
1581 $this->mName = $name;
1582
1583 return $this;
1584 }
1585
1597 public function setWrapperLegend( $legend ) {
1598 $this->mWrapperLegend = $legend;
1599
1600 return $this;
1601 }
1602
1610 public function setWrapperAttributes( $attributes ) {
1611 $this->mWrapperAttributes = $attributes;
1612
1613 return $this;
1614 }
1615
1625 public function setWrapperLegendMsg( $msg ) {
1626 if ( !$msg instanceof Message ) {
1627 $msg = $this->msg( $msg );
1628 }
1629 $this->setWrapperLegend( $msg->text() );
1630
1631 return $this;
1632 }
1633
1643 public function setMessagePrefix( $p ) {
1644 $this->mMessagePrefix = $p;
1645
1646 return $this;
1647 }
1648
1656 public function setTitle( $t ) {
1657 // TODO: make mTitle a PageReference when we have a better way to get URLs, see T282283.
1658 $this->mTitle = Title::castFromPageReference( $t );
1659
1660 return $this;
1661 }
1662
1666 public function getTitle() {
1667 return $this->mTitle ?: $this->getContext()->getTitle();
1668 }
1669
1677 public function setMethod( $method = 'post' ) {
1678 $this->mMethod = strtolower( $method );
1679
1680 return $this;
1681 }
1682
1686 public function getMethod() {
1687 return $this->mMethod;
1688 }
1689
1700 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1701 return Xml::fieldset( $legend, $section, $attributes ) . "\n";
1702 }
1703
1721 public function displaySection( $fields,
1722 $sectionName = '',
1723 $fieldsetIDPrefix = '',
1724 &$hasUserVisibleFields = false
1725 ) {
1726 if ( $this->mFieldData === null ) {
1727 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1728 . 'You probably called displayForm() without calling prepareForm() first.' );
1729 }
1730
1732
1733 $html = [];
1734 $subsectionHtml = '';
1735 $hasLabel = false;
1736
1737 // Conveniently, PHP method names are case-insensitive.
1738 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1739 $getFieldHtmlMethod = $displayFormat === 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1740
1741 foreach ( $fields as $key => $value ) {
1742 if ( $value instanceof HTMLFormField ) {
1743 $v = array_key_exists( $key, $this->mFieldData )
1744 ? $this->mFieldData[$key]
1745 : $value->getDefault();
1746
1747 $retval = $value->$getFieldHtmlMethod( $v );
1748
1749 // check, if the form field should be added to
1750 // the output.
1751 if ( $value->hasVisibleOutput() ) {
1752 $html[] = $retval;
1753
1754 $labelValue = trim( $value->getLabel() );
1755 if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
1756 $hasLabel = true;
1757 }
1758
1759 $hasUserVisibleFields = true;
1760 }
1761 } elseif ( is_array( $value ) ) {
1762 $subsectionHasVisibleFields = false;
1763 $section =
1764 $this->displaySection( $value,
1765 "mw-htmlform-$key",
1766 "$fieldsetIDPrefix$key-",
1767 $subsectionHasVisibleFields );
1768 $legend = null;
1769
1770 if ( $subsectionHasVisibleFields === true ) {
1771 // Display the section with various niceties.
1772 $hasUserVisibleFields = true;
1773
1774 $legend = $this->getLegend( $key );
1775
1776 $section = $this->getHeaderText( $key ) .
1777 $section .
1778 $this->getFooterText( $key );
1779
1780 $attributes = [];
1781 if ( $fieldsetIDPrefix ) {
1782 $attributes['id'] = Sanitizer::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1783 }
1784 $subsectionHtml .= $this->wrapFieldSetSection(
1785 $legend, $section, $attributes, $fields === $this->mFieldTree
1786 );
1787 } else {
1788 // Just return the inputs, nothing fancy.
1789 $subsectionHtml .= $section;
1790 }
1791 }
1792 }
1793
1794 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1795
1796 if ( $subsectionHtml ) {
1797 if ( $this->mSubSectionBeforeFields ) {
1798 return $subsectionHtml . "\n" . $html;
1799 } else {
1800 return $html . "\n" . $subsectionHtml;
1801 }
1802 } else {
1803 return $html;
1804 }
1805 }
1806
1815 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1816 if ( !$fieldsHtml ) {
1817 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1818 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1819 return '';
1820 }
1821
1823 $html = implode( '', $fieldsHtml );
1824
1825 if ( $displayFormat === 'raw' ) {
1826 return $html;
1827 }
1828
1829 $classes = [];
1830
1831 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1832 $classes[] = 'mw-htmlform-nolabel';
1833 }
1834
1835 $attribs = [ 'class' => $classes ];
1836
1837 if ( $sectionName ) {
1838 $attribs['id'] = Sanitizer::escapeIdForAttribute( $sectionName );
1839 }
1840
1841 if ( $displayFormat === 'table' ) {
1842 return Html::rawElement( 'table',
1843 $attribs,
1844 Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1845 } elseif ( $displayFormat === 'inline' ) {
1846 return Html::rawElement( 'span', $attribs, "\n$html\n" );
1847 } else {
1848 return Html::rawElement( 'div', $attribs, "\n$html\n" );
1849 }
1850 }
1851
1855 public function loadData() {
1856 $fieldData = [];
1857
1858 foreach ( $this->mFlatFields as $fieldname => $field ) {
1859 $request = $this->getRequest();
1860 if ( $field->skipLoadData( $request ) ) {
1861 continue;
1862 }
1863 if ( !empty( $field->mParams['disabled'] ) ) {
1864 $fieldData[$fieldname] = $field->getDefault();
1865 } else {
1866 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1867 }
1868 }
1869
1870 # Filter data.
1871 foreach ( $fieldData as $name => &$value ) {
1872 $field = $this->mFlatFields[$name];
1873 $value = $field->filter( $value, $this->mFlatFields );
1874 }
1875
1876 $this->mFieldData = $fieldData;
1877 }
1878
1886 public function suppressReset( $suppressReset = true ) {
1887 $this->mShowReset = !$suppressReset;
1888
1889 return $this;
1890 }
1891
1902 public function filterDataForSubmit( $data ) {
1903 return $data;
1904 }
1905
1915 public function getLegend( $key ) {
1916 return $this->msg( $this->mMessagePrefix ? "{$this->mMessagePrefix}-$key" : $key )->text();
1917 }
1918
1929 public function setAction( $action ) {
1930 $this->mAction = $action;
1931
1932 return $this;
1933 }
1934
1942 public function getAction() {
1943 // If an action is alredy provided, return it
1944 if ( $this->mAction !== false ) {
1945 return $this->mAction;
1946 }
1947
1948 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1949 // Check whether we are in GET mode and the ArticlePath contains a "?"
1950 // meaning that getLocalURL() would return something like "index.php?title=...".
1951 // As browser remove the query string before submitting GET forms,
1952 // it means that the title would be lost. In such case use wfScript() instead
1953 // and put title in an hidden field (see getHiddenFields()).
1954 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1955 return wfScript();
1956 }
1957
1958 return $this->getTitle()->getLocalURL();
1959 }
1960
1971 public function setAutocomplete( $autocomplete ) {
1972 $this->mAutocomplete = $autocomplete;
1973
1974 return $this;
1975 }
1976
1983 protected function getMessage( $value ) {
1984 return Message::newFromSpecifier( $value )->setContext( $this );
1985 }
1986
1997 foreach ( $this->mFlatFields as $fieldname => $field ) {
1998 if ( $field->needsJSForHtml5FormValidation() ) {
1999 return true;
2000 }
2001 }
2002 return false;
2003 }
2004}
addFields( $fields)
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
getContext()
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()
IContextSource $context
setContext(IContextSource $context)
The parent class to generate form fields.
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition HTMLForm.php:143
needsJSForHtml5FormValidation()
Whether this form, with its current fields, requires the user agent to have JavaScript enabled for th...
setSubmitCallback( $cb)
Set a callback to a function to do something with the form once it's been successfully validated.
Definition HTMLForm.php:751
setHeaderText( $msg, $section=null)
Set header text, inside the form.
Definition HTMLForm.php:852
displayForm( $submitResult)
Display the form (sending to the context's OutputPage object), with an appropriate error message or s...
string null $mAutocomplete
Form attribute autocomplete.
Definition HTMLForm.php:257
bool string $mAction
Form action URL.
Definition HTMLForm.php:236
setAction( $action)
Set the value for the action attribute of the form.
string array $mTokenSalt
Salt for the edit token.
Definition HTMLForm.php:278
string[] $mSubmitFlags
Definition HTMLForm.php:204
getSubmitText()
Get the text for the submit button, either customised or a default.
setMethod( $method='post')
Set the method used to submit the form.
$mValidationErrorMessage
Definition HTMLForm.php:209
setValidationErrorMessage( $msg)
Set a message to display on a validation error.
Definition HTMLForm.php:765
getCancelTargetURL()
getMessage( $value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name,...
setAutocomplete( $autocomplete)
Set the value for the autocomplete attribute of the form.
static loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition HTMLForm.php:534
setSubmitName( $name)
setTitle( $t)
Set the title for form submission.
static getClassFromDescriptor( $fieldname, &$descriptor)
Get the HTMLFormField subclass for this descriptor.
Definition HTMLForm.php:504
array $availableSubclassDisplayFormats
Available formats in which to display the form.
Definition HTMLForm.php:312
string $displayFormat
Format in which to display form.
Definition HTMLForm.php:295
__construct( $descriptor, $context=null, $messagePrefix='')
Build a new HTMLForm from an array of field attributes.
Definition HTMLForm.php:350
bool $mSubSectionBeforeFields
If true, sections that contain both fields and subsections will render their subsections before their...
Definition HTMLForm.php:288
setTableId( $id)
Set the id of the <table> or outermost <div> element.
getHTML( $submitResult)
Returns the raw HTML generated by the form.
getLegend( $key)
Get a string to go in the "<legend>" of a section fieldset.
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
wrapFieldSetSection( $legend, $section, $attributes, $isRoot)
Wraps the given $section into an user-visible fieldset.
filterDataForSubmit( $data)
Overload this if you want to apply special filtration routines to the form as a whole,...
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element.
setId( $id)
setWrapperLegend( $legend)
Prompt the whole form to be wrapped in a "<fieldset>", with this text as its "<legend>" element.
formatErrors( $errors)
Format a stack of error messages into a single HTML string.
setDisplayFormat( $format)
Set format in which to display the form.
Definition HTMLForm.php:448
addButton( $data)
Add a button to the form.
loadData()
Construct the form fields from the Descriptor array.
getPreText()
Get the introductory message HTML.
Definition HTMLForm.php:818
static string[] $typeMappings
A mapping of 'type' inputs onto standard HTMLFormField subclasses.
Definition HTMLForm.php:147
getHiddenFields()
Get the hidden fields that should go inside the form.
setSubmitDestructive()
Identify that the submit button in the form has a destructive action.
suppressDefaultSubmit( $suppressSubmit=true)
Stop a default submit button being shown for this form.
setSubmitID( $t)
Set the id for the submit button.
getDisplayFormat()
Getter for displayFormat.
Definition HTMLForm.php:483
getAction()
Get the value for the action attribute of the form.
show()
The here's-one-I-made-earlier option: do the submission if posted, or display the form with or withou...
Definition HTMLForm.php:621
hasField( $fieldname)
Definition HTMLForm.php:422
$mWrapperAttributes
Definition HTMLForm.php:272
addFooterText( $msg, $section=null)
Add footer text, inside the form.
Definition HTMLForm.php:886
addPostText( $msg)
Add text to the end of the display.
Definition HTMLForm.php:940
getFooterText( $section=null)
Get footer text.
Definition HTMLForm.php:925
addHeaderText( $msg, $section=null)
Add HTML to the header, inside the form.
Definition HTMLForm.php:830
setWrapperAttributes( $attributes)
For internal use only.
prepareForm()
Prepare form for submission.
Definition HTMLForm.php:559
setCollapsibleOptions( $collapsedByDefault=false)
Enable collapsible mode, and set whether the form is collapsed by default.
wasSubmitted()
Test whether the form was considered to have been submitted or not, i.e.
Definition HTMLForm.php:737
getHeaderText( $section=null)
Get header text.
Definition HTMLForm.php:870
array[] $mButtons
Definition HTMLForm.php:269
tryAuthorizedSubmit()
Try submitting, with edit token check first.
Definition HTMLForm.php:582
setSubmitTooltip( $name)
displaySection( $fields, $sectionName='', $fieldsetIDPrefix='', &$hasUserVisibleFields=false)
array[] $mHiddenFields
Definition HTMLForm.php:264
setPreText( $msg)
Set the introductory message HTML, overwriting any existing message.
Definition HTMLForm.php:792
bool $mCollapsible
Whether the form can be collapsed.
Definition HTMLForm.php:243
addHiddenField( $name, $value, array $attribs=[])
Add a hidden field to the output.
Definition HTMLForm.php:968
setFooterText( $msg, $section=null)
Set footer text, inside the form.
Definition HTMLForm.php:908
setMessagePrefix( $p)
Set the prefix for various default messages.
getField( $fieldname)
Definition HTMLForm.php:431
bool $mCollapsed
Whether the form is collapsed by default.
Definition HTMLForm.php:250
wrapForm( $html)
Wrap the form innards in an actual "<form>" element.
getFormAttributes()
Get HTML attributes for the <form> tag.
getBody()
Get the whole body of the form.
showAlways()
Same as self::show with the difference, that the form will be added to the output,...
Definition HTMLForm.php:639
setTokenSalt( $salt)
Set the salt for the edit token.
addPreText( $msg)
Add HTML to introductory message.
Definition HTMLForm.php:805
setFormIdentifier( $ident)
Set an internal identifier for this form.
setName( $name)
suppressReset( $suppressReset=true)
Stop a reset button being shown for this form.
setPostText( $msg)
Set text at the end of the display.
Definition HTMLForm.php:953
formatSection(array $fieldsHtml, $sectionName, $anyFieldHasLabel)
Put a form section together from the individual fields' HTML, merging it and wrapping.
setCancelTarget( $target)
Sets the target where the user is redirected to after clicking cancel.
array $availableDisplayFormats
Available formats in which to display the form.
Definition HTMLForm.php:301
showCancel( $show=true)
Show a cancel button (or prevent it).
setSubmitText( $t)
Set the text for the submit button.
static factory( $displayFormat,... $arguments)
Construct a HTMLForm object for given display type.
Definition HTMLForm.php:326
setIntro( $msg)
Set the introductory message, overwriting any existing message.
Definition HTMLForm.php:778
getButtons()
Get the submit and (potentially) reset buttons.
trySubmit()
Validate all the fields, and call the submission callback function if everything is kosher.
Definition HTMLForm.php:661
HTMLFormField[] $mFlatFields
Definition HTMLForm.php:199
getErrorsOrWarnings( $elements, $elementsType)
Returns a formatted list of errors or warnings from the given elements.
addHiddenFields(array $fields)
Add an array of hidden fields to the output.
Definition HTMLForm.php:985
addFields( $descriptor)
Add fields to the form.
Definition HTMLForm.php:385
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition Linker.php:2455
MediaWiki exception.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:138
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition Message.php:414
Compact stacked vertical format for forms, implemented using OOUI widgets.
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.
Definition Status.php:44
Compact stacked vertical format for forms.
Interface for objects which can provide a MediaWiki context on request.
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
if( $line===false) $args
Definition mcc.php:124