MediaWiki  master
HTMLForm.php
Go to the documentation of this file.
1 <?php
2 
131 class HTMLForm extends ContextSource {
132  // A mapping of 'type' inputs onto standard HTMLFormField subclasses
133  public static $typeMappings = [
134  'api' => HTMLApiField::class,
136  'textwithbutton' => HTMLTextFieldWithButton::class,
137  'textarea' => HTMLTextAreaField::class,
138  'select' => HTMLSelectField::class,
139  'combobox' => HTMLComboboxField::class,
140  'radio' => HTMLRadioField::class,
141  'multiselect' => HTMLMultiSelectField::class,
142  'limitselect' => HTMLSelectLimitField::class,
143  'check' => HTMLCheckField::class,
144  'toggle' => HTMLCheckField::class,
145  'int' => HTMLIntField::class,
146  'float' => HTMLFloatField::class,
147  'info' => HTMLInfoField::class,
148  'selectorother' => HTMLSelectOrOtherField::class,
149  'selectandother' => HTMLSelectAndOtherField::class,
150  'namespaceselect' => HTMLSelectNamespace::class,
151  'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
152  'tagfilter' => HTMLTagFilter::class,
153  'sizefilter' => HTMLSizeFilterField::class,
154  'submit' => HTMLSubmitField::class,
155  'hidden' => HTMLHiddenField::class,
156  'edittools' => HTMLEditTools::class,
157  'checkmatrix' => HTMLCheckMatrix::class,
158  'cloner' => HTMLFormFieldCloner::class,
159  'autocompleteselect' => HTMLAutoCompleteSelectField::class,
160  'language' => HTMLSelectLanguageField::class,
161  'date' => HTMLDateTimeField::class,
162  'time' => HTMLDateTimeField::class,
163  'datetime' => HTMLDateTimeField::class,
164  'expiry' => HTMLExpiryField::class,
165  // HTMLTextField will output the correct type="" attribute automagically.
166  // There are about four zillion other HTML5 input types, like range, but
167  // we don't use those at the moment, so no point in adding all of them.
168  'email' => HTMLTextField::class,
169  'password' => HTMLTextField::class,
170  'url' => HTMLTextField::class,
171  'title' => HTMLTitleTextField::class,
172  'user' => HTMLUserTextField::class,
173  'usersmultiselect' => HTMLUsersMultiselectField::class,
174  'titlesmultiselect' => HTMLTitlesMultiselectField::class,
175  'namespacesmultiselect' => HTMLNamespacesMultiselectField::class,
176  ];
177 
178  public $mFieldData;
179 
180  protected $mMessagePrefix;
181 
183  protected $mFlatFields = [];
184  protected $mFieldTree = [];
185  protected $mShowReset = false;
186  protected $mShowSubmit = true;
188  protected $mSubmitFlags = [ 'primary', 'progressive' ];
189  protected $mShowCancel = false;
190  protected $mCancelTarget;
191 
192  protected $mSubmitCallback;
194 
195  protected $mPre = '';
196  protected $mHeader = '';
197  protected $mFooter = '';
198  protected $mSectionHeaders = [];
199  protected $mSectionFooters = [];
200  protected $mPost = '';
201  protected $mId;
202  protected $mName;
203  protected $mTableId = '';
204 
205  protected $mSubmitID;
206  protected $mSubmitName;
207  protected $mSubmitText;
208  protected $mSubmitTooltip;
209 
210  protected $mFormIdentifier;
211  protected $mTitle;
212  protected $mMethod = 'post';
213  protected $mWasSubmitted = false;
214 
220  protected $mAction = false;
221 
227  protected $mCollapsible = false;
228 
234  protected $mCollapsed = false;
235 
241  protected $mAutocomplete = null;
242 
243  protected $mUseMultipart = false;
244  protected $mHiddenFields = [];
245  protected $mButtons = [];
246 
247  protected $mWrapperLegend = false;
248  protected $mWrapperAttributes = [];
249 
254  protected $mTokenSalt = '';
255 
263  protected $mSubSectionBeforeFields = true;
264 
270  protected $displayFormat = 'table';
271 
277  'table',
278  'div',
279  'raw',
280  'inline',
281  ];
282 
288  'vform',
289  'ooui',
290  ];
291 
299  public static function factory( $displayFormat/*, $arguments...*/ ) {
300  $arguments = func_get_args();
301  array_shift( $arguments );
302 
303  switch ( $displayFormat ) {
304  case 'vform':
305  return new VFormHTMLForm( ...$arguments );
306  case 'ooui':
307  return new OOUIHTMLForm( ...$arguments );
308  default:
309  $form = new self( ...$arguments );
310  $form->setDisplayFormat( $displayFormat );
311  return $form;
312  }
313  }
314 
324  public function __construct( $descriptor, /*IContextSource*/ $context = null,
325  $messagePrefix = ''
326  ) {
327  if ( $context instanceof IContextSource ) {
328  $this->setContext( $context );
329  $this->mTitle = false; // We don't need them to set a title
330  $this->mMessagePrefix = $messagePrefix;
331  } elseif ( $context === null && $messagePrefix !== '' ) {
332  $this->mMessagePrefix = $messagePrefix;
333  } elseif ( is_string( $context ) && $messagePrefix === '' ) {
334  // B/C since 1.18
335  // it's actually $messagePrefix
336  $this->mMessagePrefix = $context;
337  }
338 
339  // Evil hack for mobile :(
340  if (
341  !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
342  && $this->displayFormat === 'table'
343  ) {
344  $this->displayFormat = 'div';
345  }
346 
347  $this->addFields( $descriptor );
348  }
349 
359  public function addFields( $descriptor ) {
360  $loadedDescriptor = [];
361 
362  foreach ( $descriptor as $fieldname => $info ) {
363 
364  $section = $info['section'] ?? '';
365 
366  if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
367  $this->mUseMultipart = true;
368  }
369 
370  $field = static::loadInputFromParameters( $fieldname, $info, $this );
371 
372  $setSection =& $loadedDescriptor;
373  if ( $section ) {
374  foreach ( explode( '/', $section ) as $newName ) {
375  if ( !isset( $setSection[$newName] ) ) {
376  $setSection[$newName] = [];
377  }
378 
379  $setSection =& $setSection[$newName];
380  }
381  }
382 
383  $setSection[$fieldname] = $field;
384  $this->mFlatFields[$fieldname] = $field;
385  }
386 
387  $this->mFieldTree = array_merge( $this->mFieldTree, $loadedDescriptor );
388 
389  return $this;
390  }
391 
396  public function hasField( $fieldname ) {
397  return isset( $this->mFlatFields[$fieldname] );
398  }
399 
405  public function getField( $fieldname ) {
406  if ( !$this->hasField( $fieldname ) ) {
407  throw new DomainException( __METHOD__ . ': no field named ' . $fieldname );
408  }
409  return $this->mFlatFields[$fieldname];
410  }
411 
422  public function setDisplayFormat( $format ) {
423  if (
424  in_array( $format, $this->availableSubclassDisplayFormats, true ) ||
425  in_array( $this->displayFormat, $this->availableSubclassDisplayFormats, true )
426  ) {
427  throw new MWException( 'Cannot change display format after creation, ' .
428  'use HTMLForm::factory() instead' );
429  }
430 
431  if ( !in_array( $format, $this->availableDisplayFormats, true ) ) {
432  throw new MWException( 'Display format must be one of ' .
433  print_r(
434  array_merge(
435  $this->availableDisplayFormats,
436  $this->availableSubclassDisplayFormats
437  ),
438  true
439  ) );
440  }
441 
442  // Evil hack for mobile :(
443  if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
444  $format = 'div';
445  }
446 
447  $this->displayFormat = $format;
448 
449  return $this;
450  }
451 
457  public function getDisplayFormat() {
458  return $this->displayFormat;
459  }
460 
478  public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
479  if ( isset( $descriptor['class'] ) ) {
480  $class = $descriptor['class'];
481  } elseif ( isset( $descriptor['type'] ) ) {
482  $class = static::$typeMappings[$descriptor['type']];
483  $descriptor['class'] = $class;
484  } else {
485  $class = null;
486  }
487 
488  if ( !$class ) {
489  throw new MWException( "Descriptor with no class for $fieldname: "
490  . print_r( $descriptor, true ) );
491  }
492 
493  return $class;
494  }
495 
507  public static function loadInputFromParameters( $fieldname, $descriptor,
509  ) {
510  $class = static::getClassFromDescriptor( $fieldname, $descriptor );
511 
512  $descriptor['fieldname'] = $fieldname;
513  if ( $parent ) {
514  $descriptor['parent'] = $parent;
515  }
516 
517  # @todo This will throw a fatal error whenever someone try to use
518  # 'class' to feed a CSS class instead of 'cssclass'. Would be
519  # great to avoid the fatal error and show a nice error.
520  return new $class( $descriptor );
521  }
522 
532  public function prepareForm() {
533  # Check if we have the info we need
534  if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
535  throw new MWException( 'You must call setTitle() on an HTMLForm' );
536  }
537 
538  # Load data from the request.
539  if (
540  $this->mFormIdentifier === null ||
541  $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
542  ) {
543  $this->loadData();
544  } else {
545  $this->mFieldData = [];
546  }
547 
548  return $this;
549  }
550 
555  public function tryAuthorizedSubmit() {
556  $result = false;
557 
558  if ( $this->mFormIdentifier === null ) {
559  $identOkay = true;
560  } else {
561  $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier;
562  }
563 
564  $tokenOkay = false;
565  if ( $this->getMethod() !== 'post' ) {
566  $tokenOkay = true; // no session check needed
567  } elseif ( $this->getRequest()->wasPosted() ) {
568  $editToken = $this->getRequest()->getVal( 'wpEditToken' );
569  if ( $this->getUser()->isLoggedIn() || $editToken !== null ) {
570  // Session tokens for logged-out users have no security value.
571  // However, if the user gave one, check it in order to give a nice
572  // "session expired" error instead of "permission denied" or such.
573  $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
574  } else {
575  $tokenOkay = true;
576  }
577  }
578 
579  if ( $tokenOkay && $identOkay ) {
580  $this->mWasSubmitted = true;
581  $result = $this->trySubmit();
582  }
583 
584  return $result;
585  }
586 
593  public function show() {
594  $this->prepareForm();
595 
596  $result = $this->tryAuthorizedSubmit();
597  if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
598  return $result;
599  }
600 
601  $this->displayForm( $result );
602 
603  return false;
604  }
605 
611  public function showAlways() {
612  $this->prepareForm();
613 
614  $result = $this->tryAuthorizedSubmit();
615 
616  $this->displayForm( $result );
617 
618  return $result;
619  }
620 
632  public function trySubmit() {
633  $valid = true;
634  $hoistedErrors = Status::newGood();
635  if ( $this->mValidationErrorMessage ) {
636  foreach ( $this->mValidationErrorMessage as $error ) {
637  $hoistedErrors->fatal( ...$error );
638  }
639  } else {
640  $hoistedErrors->fatal( 'htmlform-invalid-input' );
641  }
642 
643  $this->mWasSubmitted = true;
644 
645  # Check for cancelled submission
646  foreach ( $this->mFlatFields as $fieldname => $field ) {
647  if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
648  continue;
649  }
650  if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
651  $this->mWasSubmitted = false;
652  return false;
653  }
654  }
655 
656  # Check for validation
657  foreach ( $this->mFlatFields as $fieldname => $field ) {
658  if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
659  continue;
660  }
661  if ( $field->isHidden( $this->mFieldData ) ) {
662  continue;
663  }
664  $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
665  if ( $res !== true ) {
666  $valid = false;
667  if ( $res !== false && !$field->canDisplayErrors() ) {
668  if ( is_string( $res ) ) {
669  $hoistedErrors->fatal( 'rawmessage', $res );
670  } else {
671  $hoistedErrors->fatal( $res );
672  }
673  }
674  }
675  }
676 
677  if ( !$valid ) {
678  return $hoistedErrors;
679  }
680 
681  $callback = $this->mSubmitCallback;
682  if ( !is_callable( $callback ) ) {
683  throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
684  'setSubmitCallback() to set one.' );
685  }
686 
687  $data = $this->filterDataForSubmit( $this->mFieldData );
688 
689  $res = call_user_func( $callback, $data, $this );
690  if ( $res === false ) {
691  $this->mWasSubmitted = false;
692  }
693 
694  return $res;
695  }
696 
708  public function wasSubmitted() {
709  return $this->mWasSubmitted;
710  }
711 
722  public function setSubmitCallback( $cb ) {
723  $this->mSubmitCallback = $cb;
724 
725  return $this;
726  }
727 
736  public function setValidationErrorMessage( $msg ) {
737  $this->mValidationErrorMessage = $msg;
738 
739  return $this;
740  }
741 
749  public function setIntro( $msg ) {
750  $this->setPreText( $msg );
751 
752  return $this;
753  }
754 
763  public function setPreText( $msg ) {
764  $this->mPre = $msg;
765 
766  return $this;
767  }
768 
776  public function addPreText( $msg ) {
777  $this->mPre .= $msg;
778 
779  return $this;
780  }
781 
789  public function getPreText() {
790  return $this->mPre;
791  }
792 
801  public function addHeaderText( $msg, $section = null ) {
802  if ( $section === null ) {
803  $this->mHeader .= $msg;
804  } else {
805  if ( !isset( $this->mSectionHeaders[$section] ) ) {
806  $this->mSectionHeaders[$section] = '';
807  }
808  $this->mSectionHeaders[$section] .= $msg;
809  }
810 
811  return $this;
812  }
813 
823  public function setHeaderText( $msg, $section = null ) {
824  if ( $section === null ) {
825  $this->mHeader = $msg;
826  } else {
827  $this->mSectionHeaders[$section] = $msg;
828  }
829 
830  return $this;
831  }
832 
840  public function getHeaderText( $section = null ) {
841  if ( $section === null ) {
842  return $this->mHeader;
843  } else {
844  return $this->mSectionHeaders[$section] ?? '';
845  }
846  }
847 
856  public function addFooterText( $msg, $section = null ) {
857  if ( $section === null ) {
858  $this->mFooter .= $msg;
859  } else {
860  if ( !isset( $this->mSectionFooters[$section] ) ) {
861  $this->mSectionFooters[$section] = '';
862  }
863  $this->mSectionFooters[$section] .= $msg;
864  }
865 
866  return $this;
867  }
868 
878  public function setFooterText( $msg, $section = null ) {
879  if ( $section === null ) {
880  $this->mFooter = $msg;
881  } else {
882  $this->mSectionFooters[$section] = $msg;
883  }
884 
885  return $this;
886  }
887 
895  public function getFooterText( $section = null ) {
896  if ( $section === null ) {
897  return $this->mFooter;
898  } else {
899  return $this->mSectionFooters[$section] ?? '';
900  }
901  }
902 
910  public function addPostText( $msg ) {
911  $this->mPost .= $msg;
912 
913  return $this;
914  }
915 
923  public function setPostText( $msg ) {
924  $this->mPost = $msg;
925 
926  return $this;
927  }
928 
938  public function addHiddenField( $name, $value, array $attribs = [] ) {
939  $attribs += [ 'name' => $name ];
940  $this->mHiddenFields[] = [ $value, $attribs ];
941 
942  return $this;
943  }
944 
955  public function addHiddenFields( array $fields ) {
956  foreach ( $fields as $name => $value ) {
957  $this->mHiddenFields[] = [ $value, [ 'name' => $name ] ];
958  }
959 
960  return $this;
961  }
962 
987  public function addButton( $data ) {
988  if ( !is_array( $data ) ) {
989  $args = func_get_args();
990  if ( count( $args ) < 2 || count( $args ) > 4 ) {
991  throw new InvalidArgumentException(
992  'Incorrect number of arguments for deprecated calling style'
993  );
994  }
995  $data = [
996  'name' => $args[0],
997  'value' => $args[1],
998  'id' => $args[2] ?? null,
999  'attribs' => $args[3] ?? null,
1000  ];
1001  } else {
1002  if ( !isset( $data['name'] ) ) {
1003  throw new InvalidArgumentException( 'A name is required' );
1004  }
1005  if ( !isset( $data['value'] ) ) {
1006  throw new InvalidArgumentException( 'A value is required' );
1007  }
1008  }
1009  $this->mButtons[] = $data + [
1010  'id' => null,
1011  'attribs' => null,
1012  'flags' => null,
1013  'framed' => true,
1014  ];
1015 
1016  return $this;
1017  }
1018 
1028  public function setTokenSalt( $salt ) {
1029  $this->mTokenSalt = $salt;
1030 
1031  return $this;
1032  }
1033 
1046  public function displayForm( $submitResult ) {
1047  $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1048  }
1049 
1058  public function getHTML( $submitResult ) {
1059  # For good measure (it is the default)
1060  $this->getOutput()->preventClickjacking();
1061  $this->getOutput()->addModules( 'mediawiki.htmlform' );
1062  $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1063 
1064  $html = ''
1065  . $this->getErrorsOrWarnings( $submitResult, 'error' )
1066  . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1067  . $this->getHeaderText()
1068  . $this->getBody()
1069  . $this->getHiddenFields()
1070  . $this->getButtons()
1071  . $this->getFooterText();
1072 
1073  $html = $this->wrapForm( $html );
1074 
1075  return '' . $this->mPre . $html . $this->mPost;
1076  }
1077 
1085  public function setCollapsibleOptions( $collapsedByDefault = false ) {
1086  $this->mCollapsible = true;
1087  $this->mCollapsed = $collapsedByDefault;
1088  return $this;
1089  }
1090 
1095  protected function getFormAttributes() {
1096  # Use multipart/form-data
1097  $encType = $this->mUseMultipart
1098  ? 'multipart/form-data'
1099  : 'application/x-www-form-urlencoded';
1100  # Attributes
1101  $attribs = [
1102  'class' => 'mw-htmlform',
1103  'action' => $this->getAction(),
1104  'method' => $this->getMethod(),
1105  'enctype' => $encType,
1106  ];
1107  if ( $this->mId ) {
1108  $attribs['id'] = $this->mId;
1109  }
1110  if ( is_string( $this->mAutocomplete ) ) {
1111  $attribs['autocomplete'] = $this->mAutocomplete;
1112  }
1113  if ( $this->mName ) {
1114  $attribs['name'] = $this->mName;
1115  }
1116  if ( $this->needsJSForHtml5FormValidation() ) {
1117  $attribs['novalidate'] = true;
1118  }
1119  return $attribs;
1120  }
1121 
1129  public function wrapForm( $html ) {
1130  # Include a <fieldset> wrapper for style, if requested.
1131  if ( $this->mWrapperLegend !== false ) {
1132  $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend : false;
1133  $html = Xml::fieldset( $legend, $html, $this->mWrapperAttributes );
1134  }
1135 
1136  return Html::rawElement(
1137  'form',
1138  $this->getFormAttributes(),
1139  $html
1140  );
1141  }
1142 
1147  public function getHiddenFields() {
1148  $html = '';
1149  if ( $this->mFormIdentifier !== null ) {
1150  $html .= Html::hidden(
1151  'wpFormIdentifier',
1152  $this->mFormIdentifier
1153  ) . "\n";
1154  }
1155  if ( $this->getMethod() === 'post' ) {
1156  $html .= Html::hidden(
1157  'wpEditToken',
1158  $this->getUser()->getEditToken( $this->mTokenSalt ),
1159  [ 'id' => 'wpEditToken' ]
1160  ) . "\n";
1161  $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1162  }
1163 
1164  $articlePath = $this->getConfig()->get( 'ArticlePath' );
1165  if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1166  $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1167  }
1168 
1169  foreach ( $this->mHiddenFields as $data ) {
1170  list( $value, $attribs ) = $data;
1171  $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
1172  }
1173 
1174  return $html;
1175  }
1176 
1181  public function getButtons() {
1182  $buttons = '';
1183  $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1184 
1185  if ( $this->mShowSubmit ) {
1186  $attribs = [];
1187 
1188  if ( isset( $this->mSubmitID ) ) {
1189  $attribs['id'] = $this->mSubmitID;
1190  }
1191 
1192  if ( isset( $this->mSubmitName ) ) {
1193  $attribs['name'] = $this->mSubmitName;
1194  }
1195 
1196  if ( isset( $this->mSubmitTooltip ) ) {
1197  $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1198  }
1199 
1200  $attribs['class'] = [ 'mw-htmlform-submit' ];
1201 
1202  if ( $useMediaWikiUIEverywhere ) {
1203  foreach ( $this->mSubmitFlags as $flag ) {
1204  $attribs['class'][] = 'mw-ui-' . $flag;
1205  }
1206  $attribs['class'][] = 'mw-ui-button';
1207  }
1208 
1209  $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1210  }
1211 
1212  if ( $this->mShowReset ) {
1213  $buttons .= Html::element(
1214  'input',
1215  [
1216  'type' => 'reset',
1217  'value' => $this->msg( 'htmlform-reset' )->text(),
1218  'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1219  ]
1220  ) . "\n";
1221  }
1222 
1223  if ( $this->mShowCancel ) {
1224  $target = $this->mCancelTarget ?: Title::newMainPage();
1225  if ( $target instanceof Title ) {
1226  $target = $target->getLocalURL();
1227  }
1228  $buttons .= Html::element(
1229  'a',
1230  [
1231  'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1232  'href' => $target,
1233  ],
1234  $this->msg( 'cancel' )->text()
1235  ) . "\n";
1236  }
1237 
1238  // IE<8 has bugs with <button>, so we'll need to avoid them.
1239  $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1240 
1241  foreach ( $this->mButtons as $button ) {
1242  $attrs = [
1243  'type' => 'submit',
1244  'name' => $button['name'],
1245  'value' => $button['value']
1246  ];
1247 
1248  if ( isset( $button['label-message'] ) ) {
1249  $label = $this->getMessage( $button['label-message'] )->parse();
1250  } elseif ( isset( $button['label'] ) ) {
1251  $label = htmlspecialchars( $button['label'] );
1252  } elseif ( isset( $button['label-raw'] ) ) {
1253  $label = $button['label-raw'];
1254  } else {
1255  $label = htmlspecialchars( $button['value'] );
1256  }
1257 
1258  if ( $button['attribs'] ) {
1259  $attrs += $button['attribs'];
1260  }
1261 
1262  if ( isset( $button['id'] ) ) {
1263  $attrs['id'] = $button['id'];
1264  }
1265 
1266  if ( $useMediaWikiUIEverywhere ) {
1267  $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : [];
1268  $attrs['class'][] = 'mw-ui-button';
1269  }
1270 
1271  if ( $isBadIE ) {
1272  $buttons .= Html::element( 'input', $attrs ) . "\n";
1273  } else {
1274  $buttons .= Html::rawElement( 'button', $attrs, $label ) . "\n";
1275  }
1276  }
1277 
1278  if ( !$buttons ) {
1279  return '';
1280  }
1281 
1282  return Html::rawElement( 'span',
1283  [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1284  }
1285 
1290  public function getBody() {
1291  return $this->displaySection( $this->mFieldTree, $this->mTableId );
1292  }
1293 
1302  public function getErrorsOrWarnings( $elements, $elementsType ) {
1303  if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1304  throw new DomainException( $elementsType . ' is not a valid type.' );
1305  }
1306  $elementstr = false;
1307  if ( $elements instanceof Status ) {
1308  list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1309  $status = $elementsType === 'error' ? $errorStatus : $warningStatus;
1310  if ( $status->isGood() ) {
1311  $elementstr = '';
1312  } else {
1313  $elementstr = $this->getOutput()->parseAsInterface(
1314  $status->getWikiText()
1315  );
1316  }
1317  } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1318  $elementstr = $this->formatErrors( $elements );
1319  } elseif ( $elementsType === 'error' ) {
1320  $elementstr = $elements;
1321  }
1322 
1323  return $elementstr
1324  ? Html::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1325  : '';
1326  }
1327 
1335  public function formatErrors( $errors ) {
1336  $errorstr = '';
1337 
1338  foreach ( $errors as $error ) {
1339  $errorstr .= Html::rawElement(
1340  'li',
1341  [],
1342  $this->getMessage( $error )->parse()
1343  );
1344  }
1345 
1346  $errorstr = Html::rawElement( 'ul', [], $errorstr );
1347 
1348  return $errorstr;
1349  }
1350 
1358  public function setSubmitText( $t ) {
1359  $this->mSubmitText = $t;
1360 
1361  return $this;
1362  }
1363 
1370  public function setSubmitDestructive() {
1371  $this->mSubmitFlags = [ 'destructive', 'primary' ];
1372 
1373  return $this;
1374  }
1375 
1384  public function setSubmitTextMsg( $msg ) {
1385  if ( !$msg instanceof Message ) {
1386  $msg = $this->msg( $msg );
1387  }
1388  $this->setSubmitText( $msg->text() );
1389 
1390  return $this;
1391  }
1392 
1397  public function getSubmitText() {
1398  return $this->mSubmitText ?: $this->msg( 'htmlform-submit' )->text();
1399  }
1400 
1406  public function setSubmitName( $name ) {
1407  $this->mSubmitName = $name;
1408 
1409  return $this;
1410  }
1411 
1417  public function setSubmitTooltip( $name ) {
1418  $this->mSubmitTooltip = $name;
1419 
1420  return $this;
1421  }
1422 
1431  public function setSubmitID( $t ) {
1432  $this->mSubmitID = $t;
1433 
1434  return $this;
1435  }
1436 
1452  public function setFormIdentifier( $ident ) {
1453  $this->mFormIdentifier = $ident;
1454 
1455  return $this;
1456  }
1457 
1468  public function suppressDefaultSubmit( $suppressSubmit = true ) {
1469  $this->mShowSubmit = !$suppressSubmit;
1470 
1471  return $this;
1472  }
1473 
1480  public function showCancel( $show = true ) {
1481  $this->mShowCancel = $show;
1482  return $this;
1483  }
1484 
1491  public function setCancelTarget( $target ) {
1492  $this->mCancelTarget = $target;
1493  return $this;
1494  }
1495 
1505  public function setTableId( $id ) {
1506  $this->mTableId = $id;
1507 
1508  return $this;
1509  }
1510 
1516  public function setId( $id ) {
1517  $this->mId = $id;
1518 
1519  return $this;
1520  }
1521 
1526  public function setName( $name ) {
1527  $this->mName = $name;
1528 
1529  return $this;
1530  }
1531 
1543  public function setWrapperLegend( $legend ) {
1544  $this->mWrapperLegend = $legend;
1545 
1546  return $this;
1547  }
1548 
1556  public function setWrapperAttributes( $attributes ) {
1557  $this->mWrapperAttributes = $attributes;
1558 
1559  return $this;
1560  }
1561 
1571  public function setWrapperLegendMsg( $msg ) {
1572  if ( !$msg instanceof Message ) {
1573  $msg = $this->msg( $msg );
1574  }
1575  $this->setWrapperLegend( $msg->text() );
1576 
1577  return $this;
1578  }
1579 
1589  public function setMessagePrefix( $p ) {
1590  $this->mMessagePrefix = $p;
1591 
1592  return $this;
1593  }
1594 
1602  public function setTitle( $t ) {
1603  $this->mTitle = $t;
1604 
1605  return $this;
1606  }
1607 
1612  public function getTitle() {
1613  return $this->mTitle === false
1614  ? $this->getContext()->getTitle()
1615  : $this->mTitle;
1616  }
1617 
1625  public function setMethod( $method = 'post' ) {
1626  $this->mMethod = strtolower( $method );
1627 
1628  return $this;
1629  }
1630 
1634  public function getMethod() {
1635  return $this->mMethod;
1636  }
1637 
1647  protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1648  return Xml::fieldset( $legend, $section, $attributes ) . "\n";
1649  }
1650 
1667  public function displaySection( $fields,
1668  $sectionName = '',
1669  $fieldsetIDPrefix = '',
1670  &$hasUserVisibleFields = false
1671  ) {
1672  if ( $this->mFieldData === null ) {
1673  throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1674  . 'You probably called displayForm() without calling prepareForm() first.' );
1675  }
1676 
1677  $displayFormat = $this->getDisplayFormat();
1678 
1679  $html = [];
1680  $subsectionHtml = '';
1681  $hasLabel = false;
1682 
1683  // Conveniently, PHP method names are case-insensitive.
1684  // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1685  $getFieldHtmlMethod = $displayFormat === 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1686 
1687  foreach ( $fields as $key => $value ) {
1688  if ( $value instanceof HTMLFormField ) {
1689  $v = array_key_exists( $key, $this->mFieldData )
1690  ? $this->mFieldData[$key]
1691  : $value->getDefault();
1692 
1693  $retval = $value->$getFieldHtmlMethod( $v );
1694 
1695  // check, if the form field should be added to
1696  // the output.
1697  if ( $value->hasVisibleOutput() ) {
1698  $html[] = $retval;
1699 
1700  $labelValue = trim( $value->getLabel() );
1701  if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
1702  $hasLabel = true;
1703  }
1704 
1705  $hasUserVisibleFields = true;
1706  }
1707  } elseif ( is_array( $value ) ) {
1708  $subsectionHasVisibleFields = false;
1709  $section =
1710  $this->displaySection( $value,
1711  "mw-htmlform-$key",
1712  "$fieldsetIDPrefix$key-",
1713  $subsectionHasVisibleFields );
1714  $legend = null;
1715 
1716  if ( $subsectionHasVisibleFields === true ) {
1717  // Display the section with various niceties.
1718  $hasUserVisibleFields = true;
1719 
1720  $legend = $this->getLegend( $key );
1721 
1722  $section = $this->getHeaderText( $key ) .
1723  $section .
1724  $this->getFooterText( $key );
1725 
1726  $attributes = [];
1727  if ( $fieldsetIDPrefix ) {
1728  $attributes['id'] = Sanitizer::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1729  }
1730  $subsectionHtml .= $this->wrapFieldSetSection(
1731  $legend, $section, $attributes, $fields === $this->mFieldTree
1732  );
1733  } else {
1734  // Just return the inputs, nothing fancy.
1735  $subsectionHtml .= $section;
1736  }
1737  }
1738  }
1739 
1740  $html = $this->formatSection( $html, $sectionName, $hasLabel );
1741 
1742  if ( $subsectionHtml ) {
1743  if ( $this->mSubSectionBeforeFields ) {
1744  return $subsectionHtml . "\n" . $html;
1745  } else {
1746  return $html . "\n" . $subsectionHtml;
1747  }
1748  } else {
1749  return $html;
1750  }
1751  }
1752 
1760  protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1761  if ( !$fieldsHtml ) {
1762  // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1763  // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1764  return '';
1765  }
1766 
1767  $displayFormat = $this->getDisplayFormat();
1768  $html = implode( '', $fieldsHtml );
1769 
1770  if ( $displayFormat === 'raw' ) {
1771  return $html;
1772  }
1773 
1774  $classes = [];
1775 
1776  if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1777  $classes[] = 'mw-htmlform-nolabel';
1778  }
1779 
1780  $attribs = [
1781  'class' => implode( ' ', $classes ),
1782  ];
1783 
1784  if ( $sectionName ) {
1785  $attribs['id'] = Sanitizer::escapeIdForAttribute( $sectionName );
1786  }
1787 
1788  if ( $displayFormat === 'table' ) {
1789  return Html::rawElement( 'table',
1790  $attribs,
1791  Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1792  } elseif ( $displayFormat === 'inline' ) {
1793  return Html::rawElement( 'span', $attribs, "\n$html\n" );
1794  } else {
1795  return Html::rawElement( 'div', $attribs, "\n$html\n" );
1796  }
1797  }
1798 
1802  public function loadData() {
1803  $fieldData = [];
1804 
1805  foreach ( $this->mFlatFields as $fieldname => $field ) {
1806  $request = $this->getRequest();
1807  if ( $field->skipLoadData( $request ) ) {
1808  continue;
1809  } elseif ( !empty( $field->mParams['disabled'] ) ) {
1810  $fieldData[$fieldname] = $field->getDefault();
1811  } else {
1812  $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1813  }
1814  }
1815 
1816  # Filter data.
1817  foreach ( $fieldData as $name => &$value ) {
1818  $field = $this->mFlatFields[$name];
1819  $value = $field->filter( $value, $this->mFlatFields );
1820  }
1821 
1822  $this->mFieldData = $fieldData;
1823  }
1824 
1832  public function suppressReset( $suppressReset = true ) {
1833  $this->mShowReset = !$suppressReset;
1834 
1835  return $this;
1836  }
1837 
1847  public function filterDataForSubmit( $data ) {
1848  return $data;
1849  }
1850 
1859  public function getLegend( $key ) {
1860  return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1861  }
1862 
1873  public function setAction( $action ) {
1874  $this->mAction = $action;
1875 
1876  return $this;
1877  }
1878 
1886  public function getAction() {
1887  // If an action is alredy provided, return it
1888  if ( $this->mAction !== false ) {
1889  return $this->mAction;
1890  }
1891 
1892  $articlePath = $this->getConfig()->get( 'ArticlePath' );
1893  // Check whether we are in GET mode and the ArticlePath contains a "?"
1894  // meaning that getLocalURL() would return something like "index.php?title=...".
1895  // As browser remove the query string before submitting GET forms,
1896  // it means that the title would be lost. In such case use wfScript() instead
1897  // and put title in an hidden field (see getHiddenFields()).
1898  if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1899  return wfScript();
1900  }
1901 
1902  return $this->getTitle()->getLocalURL();
1903  }
1904 
1915  public function setAutocomplete( $autocomplete ) {
1916  $this->mAutocomplete = $autocomplete;
1917 
1918  return $this;
1919  }
1920 
1927  protected function getMessage( $value ) {
1928  return Message::newFromSpecifier( $value )->setContext( $this );
1929  }
1930 
1940  public function needsJSForHtml5FormValidation() {
1941  foreach ( $this->mFlatFields as $fieldname => $field ) {
1942  if ( $field->needsJSForHtml5FormValidation() ) {
1943  return true;
1944  }
1945  }
1946  return false;
1947  }
1948 }
HTMLFormField [] $mFlatFields
Definition: HTMLForm.php:183
setContext(IContextSource $context)
string [] $mSubmitFlags
Definition: HTMLForm.php:188
showAlways()
Same as self::show with the difference, that the form will be added to the output, no matter, if the validation was good or not.
Definition: HTMLForm.php:611
string null $mAutocomplete
Form attribute autocomplete.
Definition: HTMLForm.php:241
needsJSForHtml5FormValidation()
Whether this form, with its current fields, requires the user agent to have JavaScript enabled for th...
Definition: HTMLForm.php:1940
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1972
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
static $typeMappings
Definition: HTMLForm.php:133
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
prepareForm()
Prepare form for submission.
Definition: HTMLForm.php:532
setSubmitID( $t)
Set the id for the submit button.
Definition: HTMLForm.php:1431
$mWasSubmitted
Definition: HTMLForm.php:213
static getClassFromDescriptor( $fieldname, &$descriptor)
Get the HTMLFormField subclass for this descriptor.
Definition: HTMLForm.php:478
setPostText( $msg)
Set text at the end of the display.
Definition: HTMLForm.php:923
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:656
$mWrapperLegend
Definition: HTMLForm.php:247
wrapFieldSetSection( $legend, $section, $attributes, $isRoot)
Wraps the given $section into an user-visible fieldset.
Definition: HTMLForm.php:1647
getAction()
Get the value for the action attribute of the form.
Definition: HTMLForm.php:1886
setSubmitName( $name)
Definition: HTMLForm.php:1406
showCancel( $show=true)
Show a cancel button (or prevent it).
Definition: HTMLForm.php:1480
setFooterText( $msg, $section=null)
Set footer text, inside the form.
Definition: HTMLForm.php:878
getDisplayFormat()
Getter for displayFormat.
Definition: HTMLForm.php:457
$mUseMultipart
Definition: HTMLForm.php:243
setTokenSalt( $salt)
Set the salt for the edit token.
Definition: HTMLForm.php:1028
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
addFooterText( $msg, $section=null)
Add footer text, inside the form.
Definition: HTMLForm.php:856
trySubmit()
Validate all the fields, and call the submission callback function if everything is kosher...
Definition: HTMLForm.php:632
setSubmitTooltip( $name)
Definition: HTMLForm.php:1417
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
$mHiddenFields
Definition: HTMLForm.php:244
addButton( $data)
Add a button to the form.
Definition: HTMLForm.php:987
$value
bool $mCollapsed
Whether the form is collapsed by default.
Definition: HTMLForm.php:234
getLegend( $key)
Get a string to go in the "<legend>" of a section fieldset.
Definition: HTMLForm.php:1859
hasField( $fieldname)
Definition: HTMLForm.php:396
displaySection( $fields, $sectionName='', $fieldsetIDPrefix='', &$hasUserVisibleFields=false)
Definition: HTMLForm.php:1667
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
$mSubmitCallback
Definition: HTMLForm.php:192
static factory( $displayFormat)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:299
$mSubmitTooltip
Definition: HTMLForm.php:208
IContextSource $context
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
setCollapsibleOptions( $collapsedByDefault=false)
Enable collapsible mode, and set whether the form is collapsed by default.
Definition: HTMLForm.php:1085
setId( $id)
Definition: HTMLForm.php:1516
array $availableDisplayFormats
Available formats in which to display the form.
Definition: HTMLForm.php:276
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1970
getHiddenFields()
Get the hidden fields that should go inside the form.
Definition: HTMLForm.php:1147
string array $mTokenSalt
Salt for the edit token.
Definition: HTMLForm.php:254
addHiddenFields(array $fields)
Add an array of hidden fields to the output.
Definition: HTMLForm.php:955
if( $line===false) $args
Definition: cdb.php:64
bool string $mAction
Form action URL.
Definition: HTMLForm.php:220
setMethod( $method='post')
Set the method used to submit the form.
Definition: HTMLForm.php:1625
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
$mValidationErrorMessage
Definition: HTMLForm.php:193
static loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition: HTMLForm.php:507
__construct( $descriptor, $context=null, $messagePrefix='')
Build a new HTMLForm from an array of field attributes.
Definition: HTMLForm.php:324
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1244
displayForm( $submitResult)
Display the form (sending to the context&#39;s OutputPage object), with an appropriate error message or s...
Definition: HTMLForm.php:1046
string $displayFormat
Format in which to display form.
Definition: HTMLForm.php:270
setSubmitText( $t)
Set the text for the submit button.
Definition: HTMLForm.php:1358
show()
The here&#39;s-one-I-made-earlier option: do the submission if posted, or display the form with or withou...
Definition: HTMLForm.php:593
static $mFieldData
Definition: HTMLForm.php:135
setCancelTarget( $target)
Sets the target where the user is redirected to after clicking cancel.
Definition: HTMLForm.php:1491
addHiddenField( $name, $value, array $attribs=[])
Add a hidden field to the output.
Definition: HTMLForm.php:938
setSubmitDestructive()
Identify that the submit button in the form has a destructive action.
Definition: HTMLForm.php:1370
getHTML( $submitResult)
Returns the raw HTML generated by the form.
Definition: HTMLForm.php:1058
getMessage( $value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a name + parameters array) into a Message.
Definition: HTMLForm.php:1927
$mWrapperAttributes
Definition: HTMLForm.php:248
static escapeIdForAttribute( $id, $mode=self::ID_PRIMARY)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid HTM...
Definition: Sanitizer.php:1295
setFormIdentifier( $ident)
Set an internal identifier for this form.
Definition: HTMLForm.php:1452
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition: Xml.php:609
setTableId( $id)
Set the id of the <table> or outermost <div> element.
Definition: HTMLForm.php:1505
$res
Definition: database.txt:21
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
getTitle()
Get the title.
Definition: HTMLForm.php:1612
setHeaderText( $msg, $section=null)
Set header text, inside the form.
Definition: HTMLForm.php:823
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:459
formatErrors( $errors)
Format a stack of error messages into a single HTML string.
Definition: HTMLForm.php:1335
wrapForm( $html)
Wrap the form innards in an actual "<form>" element.
Definition: HTMLForm.php:1129
getContext()
Get the base IContextSource object.
getFormAttributes()
Get HTML attributes for the <form> tag.
Definition: HTMLForm.php:1095
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:1972
filterDataForSubmit( $data)
Overload this if you want to apply special filtration routines to the form as a whole, after it&#39;s submitted but before it&#39;s processed.
Definition: HTMLForm.php:1847
setValidationErrorMessage( $msg)
Set a message to display on a validation error.
Definition: HTMLForm.php:736
formatSection(array $fieldsHtml, $sectionName, $anyFieldHasLabel)
Put a form section together from the individual fields&#39; HTML, merging it and wrapping.
Definition: HTMLForm.php:1760
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
array $availableSubclassDisplayFormats
Available formats in which to display the form.
Definition: HTMLForm.php:287
addPreText( $msg)
Add HTML to introductory message.
Definition: HTMLForm.php:776
setMessagePrefix( $p)
Set the prefix for various default messages.
Definition: HTMLForm.php:1589
setSubmitCallback( $cb)
Set a callback to a function to do something with the form once it&#39;s been successfully validated...
Definition: HTMLForm.php:722
getSubmitText()
Get the text for the submit button, either customised or a default.
Definition: HTMLForm.php:1397
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:3039
$mCancelTarget
Definition: HTMLForm.php:190
wasSubmitted()
Test whether the form was considered to have been submitted or not, i.e.
Definition: HTMLForm.php:708
$mFormIdentifier
Definition: HTMLForm.php:210
setWrapperAttributes( $attributes)
For internal use only.
Definition: HTMLForm.php:1556
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Compact stacked vertical format for forms.
getField( $fieldname)
Definition: HTMLForm.php:405
$mSectionFooters
Definition: HTMLForm.php:199
getPreText()
Get the introductory message HTML.
Definition: HTMLForm.php:789
$parent
Definition: pageupdater.txt:71
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:429
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
addFields( $descriptor)
Add fields to the form.
Definition: HTMLForm.php:359
loadData()
Construct the form fields from the Descriptor array.
Definition: HTMLForm.php:1802
setAction( $action)
Set the value for the action attribute of the form.
Definition: HTMLForm.php:1873
suppressReset( $suppressReset=true)
Stop a reset button being shown for this form.
Definition: HTMLForm.php:1832
getFooterText( $section=null)
Get footer text.
Definition: HTMLForm.php:895
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:796
getErrorsOrWarnings( $elements, $elementsType)
Returns a formatted list of errors or warnings from the given elements.
Definition: HTMLForm.php:1302
getHeaderText( $section=null)
Get header text.
Definition: HTMLForm.php:840
tryAuthorizedSubmit()
Try submitting, with edit token check first.
Definition: HTMLForm.php:555
Compact stacked vertical format for forms, implemented using OOUI widgets.
setIntro( $msg)
Set the introductory message, overwriting any existing message.
Definition: HTMLForm.php:749
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1384
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
$mSectionHeaders
Definition: HTMLForm.php:198
setAutocomplete( $autocomplete)
Set the value for the autocomplete attribute of the form.
Definition: HTMLForm.php:1915
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element...
Definition: HTMLForm.php:1571
$mMessagePrefix
Definition: HTMLForm.php:180
getBody()
Get the whole body of the form.
Definition: HTMLForm.php:1290
setPreText( $msg)
Set the introductory message HTML, overwriting any existing message.
Definition: HTMLForm.php:763
suppressDefaultSubmit( $suppressSubmit=true)
Stop a default submit button being shown for this form.
Definition: HTMLForm.php:1468
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2188
addHeaderText( $msg, $section=null)
Add HTML to the header, inside the form.
Definition: HTMLForm.php:801
getButtons()
Get the submit and (potentially) reset buttons.
Definition: HTMLForm.php:1181
setDisplayFormat( $format)
Set format in which to display the form.
Definition: HTMLForm.php:422
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2621
bool $mCollapsible
Whether the form can be collapsed.
Definition: HTMLForm.php:227
$mSubSectionBeforeFields
If true, sections that contain both fields and subsections will render their subsections before their...
Definition: HTMLForm.php:263
addPostText( $msg)
Add text to the end of the display.
Definition: HTMLForm.php:910
setName( $name)
Definition: HTMLForm.php:1526
setWrapperLegend( $legend)
Prompt the whole form to be wrapped in a "<fieldset>", with this text as its "<legend>" element...
Definition: HTMLForm.php:1543
setTitle( $t)
Set the title for form submission.
Definition: HTMLForm.php:1602