MediaWiki  1.30.0
HTMLForm.php
Go to the documentation of this file.
1 <?php
2 
128 class HTMLForm extends ContextSource {
129  // A mapping of 'type' inputs onto standard HTMLFormField subclasses
130  public static $typeMappings = [
131  'api' => 'HTMLApiField',
132  'text' => 'HTMLTextField',
133  'textwithbutton' => 'HTMLTextFieldWithButton',
134  'textarea' => 'HTMLTextAreaField',
135  'select' => 'HTMLSelectField',
136  'combobox' => 'HTMLComboboxField',
137  'radio' => 'HTMLRadioField',
138  'multiselect' => 'HTMLMultiSelectField',
139  'limitselect' => 'HTMLSelectLimitField',
140  'check' => 'HTMLCheckField',
141  'toggle' => 'HTMLCheckField',
142  'int' => 'HTMLIntField',
143  'float' => 'HTMLFloatField',
144  'info' => 'HTMLInfoField',
145  'selectorother' => 'HTMLSelectOrOtherField',
146  'selectandother' => 'HTMLSelectAndOtherField',
147  'namespaceselect' => 'HTMLSelectNamespace',
148  'namespaceselectwithbutton' => 'HTMLSelectNamespaceWithButton',
149  'tagfilter' => 'HTMLTagFilter',
150  'sizefilter' => 'HTMLSizeFilterField',
151  'submit' => 'HTMLSubmitField',
152  'hidden' => 'HTMLHiddenField',
153  'edittools' => 'HTMLEditTools',
154  'checkmatrix' => 'HTMLCheckMatrix',
155  'cloner' => 'HTMLFormFieldCloner',
156  'autocompleteselect' => 'HTMLAutoCompleteSelectField',
157  'date' => 'HTMLDateTimeField',
158  'time' => 'HTMLDateTimeField',
159  'datetime' => 'HTMLDateTimeField',
160  // HTMLTextField will output the correct type="" attribute automagically.
161  // There are about four zillion other HTML5 input types, like range, but
162  // we don't use those at the moment, so no point in adding all of them.
163  'email' => 'HTMLTextField',
164  'password' => 'HTMLTextField',
165  'url' => 'HTMLTextField',
166  'title' => 'HTMLTitleTextField',
167  'user' => 'HTMLUserTextField',
168  'usersmultiselect' => 'HTMLUsersMultiselectField',
169  ];
170 
171  public $mFieldData;
172 
173  protected $mMessagePrefix;
174 
176  protected $mFlatFields;
177 
178  protected $mFieldTree;
179  protected $mShowReset = false;
180  protected $mShowSubmit = true;
181  protected $mSubmitFlags = [ 'primary', 'progressive' ];
182  protected $mShowCancel = false;
183  protected $mCancelTarget;
184 
185  protected $mSubmitCallback;
187 
188  protected $mPre = '';
189  protected $mHeader = '';
190  protected $mFooter = '';
191  protected $mSectionHeaders = [];
192  protected $mSectionFooters = [];
193  protected $mPost = '';
194  protected $mId;
195  protected $mName;
196  protected $mTableId = '';
197 
198  protected $mSubmitID;
199  protected $mSubmitName;
200  protected $mSubmitText;
201  protected $mSubmitTooltip;
202 
203  protected $mFormIdentifier;
204  protected $mTitle;
205  protected $mMethod = 'post';
206  protected $mWasSubmitted = false;
207 
213  protected $mAction = false;
214 
220  protected $mAutocomplete = false;
221 
222  protected $mUseMultipart = false;
223  protected $mHiddenFields = [];
224  protected $mButtons = [];
225 
226  protected $mWrapperLegend = false;
227 
232  protected $mTokenSalt = '';
233 
241  protected $mSubSectionBeforeFields = true;
242 
248  protected $displayFormat = 'table';
249 
255  'table',
256  'div',
257  'raw',
258  'inline',
259  ];
260 
266  'vform',
267  'ooui',
268  ];
269 
277  public static function factory( $displayFormat/*, $arguments...*/ ) {
278  $arguments = func_get_args();
279  array_shift( $arguments );
280 
281  switch ( $displayFormat ) {
282  case 'vform':
284  case 'ooui':
286  default:
288  $form = ObjectFactory::constructClassInstance( self::class, $arguments );
289  $form->setDisplayFormat( $displayFormat );
290  return $form;
291  }
292  }
293 
302  public function __construct( $descriptor, /*IContextSource*/ $context = null,
303  $messagePrefix = ''
304  ) {
305  if ( $context instanceof IContextSource ) {
306  $this->setContext( $context );
307  $this->mTitle = false; // We don't need them to set a title
308  $this->mMessagePrefix = $messagePrefix;
309  } elseif ( $context === null && $messagePrefix !== '' ) {
310  $this->mMessagePrefix = $messagePrefix;
311  } elseif ( is_string( $context ) && $messagePrefix === '' ) {
312  // B/C since 1.18
313  // it's actually $messagePrefix
314  $this->mMessagePrefix = $context;
315  }
316 
317  // Evil hack for mobile :(
318  if (
319  !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
320  && $this->displayFormat === 'table'
321  ) {
322  $this->displayFormat = 'div';
323  }
324 
325  // Expand out into a tree.
326  $loadedDescriptor = [];
327  $this->mFlatFields = [];
328 
329  foreach ( $descriptor as $fieldname => $info ) {
330  $section = isset( $info['section'] )
331  ? $info['section']
332  : '';
333 
334  if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
335  $this->mUseMultipart = true;
336  }
337 
338  $field = static::loadInputFromParameters( $fieldname, $info, $this );
339 
340  $setSection =& $loadedDescriptor;
341  if ( $section ) {
342  $sectionParts = explode( '/', $section );
343 
344  while ( count( $sectionParts ) ) {
345  $newName = array_shift( $sectionParts );
346 
347  if ( !isset( $setSection[$newName] ) ) {
348  $setSection[$newName] = [];
349  }
350 
351  $setSection =& $setSection[$newName];
352  }
353  }
354 
355  $setSection[$fieldname] = $field;
356  $this->mFlatFields[$fieldname] = $field;
357  }
358 
359  $this->mFieldTree = $loadedDescriptor;
360  }
361 
366  public function hasField( $fieldname ) {
367  return isset( $this->mFlatFields[$fieldname] );
368  }
369 
375  public function getField( $fieldname ) {
376  if ( !$this->hasField( $fieldname ) ) {
377  throw new DomainException( __METHOD__ . ': no field named ' . $fieldname );
378  }
379  return $this->mFlatFields[$fieldname];
380  }
381 
392  public function setDisplayFormat( $format ) {
393  if (
394  in_array( $format, $this->availableSubclassDisplayFormats, true ) ||
395  in_array( $this->displayFormat, $this->availableSubclassDisplayFormats, true )
396  ) {
397  throw new MWException( 'Cannot change display format after creation, ' .
398  'use HTMLForm::factory() instead' );
399  }
400 
401  if ( !in_array( $format, $this->availableDisplayFormats, true ) ) {
402  throw new MWException( 'Display format must be one of ' .
403  print_r(
404  array_merge(
405  $this->availableDisplayFormats,
406  $this->availableSubclassDisplayFormats
407  ),
408  true
409  ) );
410  }
411 
412  // Evil hack for mobile :(
413  if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
414  $format = 'div';
415  }
416 
417  $this->displayFormat = $format;
418 
419  return $this;
420  }
421 
427  public function getDisplayFormat() {
428  return $this->displayFormat;
429  }
430 
437  public function isVForm() {
438  wfDeprecated( __METHOD__, '1.25' );
439  return false;
440  }
441 
458  public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
459  if ( isset( $descriptor['class'] ) ) {
460  $class = $descriptor['class'];
461  } elseif ( isset( $descriptor['type'] ) ) {
462  $class = static::$typeMappings[$descriptor['type']];
463  $descriptor['class'] = $class;
464  } else {
465  $class = null;
466  }
467 
468  if ( !$class ) {
469  throw new MWException( "Descriptor with no class for $fieldname: "
470  . print_r( $descriptor, true ) );
471  }
472 
473  return $class;
474  }
475 
486  public static function loadInputFromParameters( $fieldname, $descriptor,
487  HTMLForm $parent = null
488  ) {
489  $class = static::getClassFromDescriptor( $fieldname, $descriptor );
490 
491  $descriptor['fieldname'] = $fieldname;
492  if ( $parent ) {
493  $descriptor['parent'] = $parent;
494  }
495 
496  # @todo This will throw a fatal error whenever someone try to use
497  # 'class' to feed a CSS class instead of 'cssclass'. Would be
498  # great to avoid the fatal error and show a nice error.
499  return new $class( $descriptor );
500  }
501 
511  public function prepareForm() {
512  # Check if we have the info we need
513  if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
514  throw new MWException( 'You must call setTitle() on an HTMLForm' );
515  }
516 
517  # Load data from the request.
518  if (
519  $this->mFormIdentifier === null ||
520  $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
521  ) {
522  $this->loadData();
523  } else {
524  $this->mFieldData = [];
525  }
526 
527  return $this;
528  }
529 
534  public function tryAuthorizedSubmit() {
535  $result = false;
536 
537  $identOkay = false;
538  if ( $this->mFormIdentifier === null ) {
539  $identOkay = true;
540  } else {
541  $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier;
542  }
543 
544  $tokenOkay = false;
545  if ( $this->getMethod() !== 'post' ) {
546  $tokenOkay = true; // no session check needed
547  } elseif ( $this->getRequest()->wasPosted() ) {
548  $editToken = $this->getRequest()->getVal( 'wpEditToken' );
549  if ( $this->getUser()->isLoggedIn() || $editToken !== null ) {
550  // Session tokens for logged-out users have no security value.
551  // However, if the user gave one, check it in order to give a nice
552  // "session expired" error instead of "permission denied" or such.
553  $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
554  } else {
555  $tokenOkay = true;
556  }
557  }
558 
559  if ( $tokenOkay && $identOkay ) {
560  $this->mWasSubmitted = true;
561  $result = $this->trySubmit();
562  }
563 
564  return $result;
565  }
566 
573  public function show() {
574  $this->prepareForm();
575 
576  $result = $this->tryAuthorizedSubmit();
577  if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
578  return $result;
579  }
580 
581  $this->displayForm( $result );
582 
583  return false;
584  }
585 
591  public function showAlways() {
592  $this->prepareForm();
593 
594  $result = $this->tryAuthorizedSubmit();
595 
596  $this->displayForm( $result );
597 
598  return $result;
599  }
600 
612  public function trySubmit() {
613  $valid = true;
614  $hoistedErrors = Status::newGood();
615  if ( $this->mValidationErrorMessage ) {
616  foreach ( (array)$this->mValidationErrorMessage as $error ) {
617  call_user_func_array( [ $hoistedErrors, 'fatal' ], $error );
618  }
619  } else {
620  $hoistedErrors->fatal( 'htmlform-invalid-input' );
621  }
622 
623  $this->mWasSubmitted = true;
624 
625  # Check for cancelled submission
626  foreach ( $this->mFlatFields as $fieldname => $field ) {
627  if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
628  continue;
629  }
630  if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
631  $this->mWasSubmitted = false;
632  return false;
633  }
634  }
635 
636  # Check for validation
637  foreach ( $this->mFlatFields as $fieldname => $field ) {
638  if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
639  continue;
640  }
641  if ( $field->isHidden( $this->mFieldData ) ) {
642  continue;
643  }
644  $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
645  if ( $res !== true ) {
646  $valid = false;
647  if ( $res !== false && !$field->canDisplayErrors() ) {
648  if ( is_string( $res ) ) {
649  $hoistedErrors->fatal( 'rawmessage', $res );
650  } else {
651  $hoistedErrors->fatal( $res );
652  }
653  }
654  }
655  }
656 
657  if ( !$valid ) {
658  return $hoistedErrors;
659  }
660 
661  $callback = $this->mSubmitCallback;
662  if ( !is_callable( $callback ) ) {
663  throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
664  'setSubmitCallback() to set one.' );
665  }
666 
667  $data = $this->filterDataForSubmit( $this->mFieldData );
668 
669  $res = call_user_func( $callback, $data, $this );
670  if ( $res === false ) {
671  $this->mWasSubmitted = false;
672  }
673 
674  return $res;
675  }
676 
688  public function wasSubmitted() {
689  return $this->mWasSubmitted;
690  }
691 
702  public function setSubmitCallback( $cb ) {
703  $this->mSubmitCallback = $cb;
704 
705  return $this;
706  }
707 
716  public function setValidationErrorMessage( $msg ) {
717  $this->mValidationErrorMessage = $msg;
718 
719  return $this;
720  }
721 
729  public function setIntro( $msg ) {
730  $this->setPreText( $msg );
731 
732  return $this;
733  }
734 
743  public function setPreText( $msg ) {
744  $this->mPre = $msg;
745 
746  return $this;
747  }
748 
756  public function addPreText( $msg ) {
757  $this->mPre .= $msg;
758 
759  return $this;
760  }
761 
770  public function addHeaderText( $msg, $section = null ) {
771  if ( $section === null ) {
772  $this->mHeader .= $msg;
773  } else {
774  if ( !isset( $this->mSectionHeaders[$section] ) ) {
775  $this->mSectionHeaders[$section] = '';
776  }
777  $this->mSectionHeaders[$section] .= $msg;
778  }
779 
780  return $this;
781  }
782 
792  public function setHeaderText( $msg, $section = null ) {
793  if ( $section === null ) {
794  $this->mHeader = $msg;
795  } else {
796  $this->mSectionHeaders[$section] = $msg;
797  }
798 
799  return $this;
800  }
801 
809  public function getHeaderText( $section = null ) {
810  if ( $section === null ) {
811  return $this->mHeader;
812  } else {
813  return isset( $this->mSectionHeaders[$section] ) ? $this->mSectionHeaders[$section] : '';
814  }
815  }
816 
825  public function addFooterText( $msg, $section = null ) {
826  if ( $section === null ) {
827  $this->mFooter .= $msg;
828  } else {
829  if ( !isset( $this->mSectionFooters[$section] ) ) {
830  $this->mSectionFooters[$section] = '';
831  }
832  $this->mSectionFooters[$section] .= $msg;
833  }
834 
835  return $this;
836  }
837 
847  public function setFooterText( $msg, $section = null ) {
848  if ( $section === null ) {
849  $this->mFooter = $msg;
850  } else {
851  $this->mSectionFooters[$section] = $msg;
852  }
853 
854  return $this;
855  }
856 
864  public function getFooterText( $section = null ) {
865  if ( $section === null ) {
866  return $this->mFooter;
867  } else {
868  return isset( $this->mSectionFooters[$section] ) ? $this->mSectionFooters[$section] : '';
869  }
870  }
871 
879  public function addPostText( $msg ) {
880  $this->mPost .= $msg;
881 
882  return $this;
883  }
884 
892  public function setPostText( $msg ) {
893  $this->mPost = $msg;
894 
895  return $this;
896  }
897 
907  public function addHiddenField( $name, $value, array $attribs = [] ) {
908  $attribs += [ 'name' => $name ];
909  $this->mHiddenFields[] = [ $value, $attribs ];
910 
911  return $this;
912  }
913 
924  public function addHiddenFields( array $fields ) {
925  foreach ( $fields as $name => $value ) {
926  $this->mHiddenFields[] = [ $value, [ 'name' => $name ] ];
927  }
928 
929  return $this;
930  }
931 
956  public function addButton( $data ) {
957  if ( !is_array( $data ) ) {
958  $args = func_get_args();
959  if ( count( $args ) < 2 || count( $args ) > 4 ) {
960  throw new InvalidArgumentException(
961  'Incorrect number of arguments for deprecated calling style'
962  );
963  }
964  $data = [
965  'name' => $args[0],
966  'value' => $args[1],
967  'id' => isset( $args[2] ) ? $args[2] : null,
968  'attribs' => isset( $args[3] ) ? $args[3] : null,
969  ];
970  } else {
971  if ( !isset( $data['name'] ) ) {
972  throw new InvalidArgumentException( 'A name is required' );
973  }
974  if ( !isset( $data['value'] ) ) {
975  throw new InvalidArgumentException( 'A value is required' );
976  }
977  }
978  $this->mButtons[] = $data + [
979  'id' => null,
980  'attribs' => null,
981  'flags' => null,
982  'framed' => true,
983  ];
984 
985  return $this;
986  }
987 
997  public function setTokenSalt( $salt ) {
998  $this->mTokenSalt = $salt;
999 
1000  return $this;
1001  }
1002 
1015  public function displayForm( $submitResult ) {
1016  $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1017  }
1018 
1026  public function getHTML( $submitResult ) {
1027  # For good measure (it is the default)
1028  $this->getOutput()->preventClickjacking();
1029  $this->getOutput()->addModules( 'mediawiki.htmlform' );
1030  $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1031 
1032  $html = ''
1033  . $this->getErrorsOrWarnings( $submitResult, 'error' )
1034  . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1035  . $this->getHeaderText()
1036  . $this->getBody()
1037  . $this->getHiddenFields()
1038  . $this->getButtons()
1039  . $this->getFooterText();
1040 
1041  $html = $this->wrapForm( $html );
1042 
1043  return '' . $this->mPre . $html . $this->mPost;
1044  }
1045 
1050  protected function getFormAttributes() {
1051  # Use multipart/form-data
1052  $encType = $this->mUseMultipart
1053  ? 'multipart/form-data'
1054  : 'application/x-www-form-urlencoded';
1055  # Attributes
1056  $attribs = [
1057  'class' => 'mw-htmlform',
1058  'action' => $this->getAction(),
1059  'method' => $this->getMethod(),
1060  'enctype' => $encType,
1061  ];
1062  if ( $this->mId ) {
1063  $attribs['id'] = $this->mId;
1064  }
1065  if ( $this->mAutocomplete ) {
1066  $attribs['autocomplete'] = $this->mAutocomplete;
1067  }
1068  if ( $this->mName ) {
1069  $attribs['name'] = $this->mName;
1070  }
1071  if ( $this->needsJSForHtml5FormValidation() ) {
1072  $attribs['novalidate'] = true;
1073  }
1074  return $attribs;
1075  }
1076 
1084  public function wrapForm( $html ) {
1085  # Include a <fieldset> wrapper for style, if requested.
1086  if ( $this->mWrapperLegend !== false ) {
1087  $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend : false;
1088  $html = Xml::fieldset( $legend, $html );
1089  }
1090 
1091  return Html::rawElement(
1092  'form',
1093  $this->getFormAttributes(),
1094  $html
1095  );
1096  }
1097 
1102  public function getHiddenFields() {
1103  $html = '';
1104  if ( $this->mFormIdentifier !== null ) {
1105  $html .= Html::hidden(
1106  'wpFormIdentifier',
1107  $this->mFormIdentifier
1108  ) . "\n";
1109  }
1110  if ( $this->getMethod() === 'post' ) {
1111  $html .= Html::hidden(
1112  'wpEditToken',
1113  $this->getUser()->getEditToken( $this->mTokenSalt ),
1114  [ 'id' => 'wpEditToken' ]
1115  ) . "\n";
1116  $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1117  }
1118 
1119  $articlePath = $this->getConfig()->get( 'ArticlePath' );
1120  if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1121  $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1122  }
1123 
1124  foreach ( $this->mHiddenFields as $data ) {
1125  list( $value, $attribs ) = $data;
1126  $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
1127  }
1128 
1129  return $html;
1130  }
1131 
1136  public function getButtons() {
1137  $buttons = '';
1138  $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1139 
1140  if ( $this->mShowSubmit ) {
1141  $attribs = [];
1142 
1143  if ( isset( $this->mSubmitID ) ) {
1144  $attribs['id'] = $this->mSubmitID;
1145  }
1146 
1147  if ( isset( $this->mSubmitName ) ) {
1148  $attribs['name'] = $this->mSubmitName;
1149  }
1150 
1151  if ( isset( $this->mSubmitTooltip ) ) {
1152  $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1153  }
1154 
1155  $attribs['class'] = [ 'mw-htmlform-submit' ];
1156 
1157  if ( $useMediaWikiUIEverywhere ) {
1158  foreach ( $this->mSubmitFlags as $flag ) {
1159  $attribs['class'][] = 'mw-ui-' . $flag;
1160  }
1161  $attribs['class'][] = 'mw-ui-button';
1162  }
1163 
1164  $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1165  }
1166 
1167  if ( $this->mShowReset ) {
1168  $buttons .= Html::element(
1169  'input',
1170  [
1171  'type' => 'reset',
1172  'value' => $this->msg( 'htmlform-reset' )->text(),
1173  'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1174  ]
1175  ) . "\n";
1176  }
1177 
1178  if ( $this->mShowCancel ) {
1179  $target = $this->mCancelTarget ?: Title::newMainPage();
1180  if ( $target instanceof Title ) {
1181  $target = $target->getLocalURL();
1182  }
1183  $buttons .= Html::element(
1184  'a',
1185  [
1186  'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1187  'href' => $target,
1188  ],
1189  $this->msg( 'cancel' )->text()
1190  ) . "\n";
1191  }
1192 
1193  // IE<8 has bugs with <button>, so we'll need to avoid them.
1194  $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1195 
1196  foreach ( $this->mButtons as $button ) {
1197  $attrs = [
1198  'type' => 'submit',
1199  'name' => $button['name'],
1200  'value' => $button['value']
1201  ];
1202 
1203  if ( isset( $button['label-message'] ) ) {
1204  $label = $this->getMessage( $button['label-message'] )->parse();
1205  } elseif ( isset( $button['label'] ) ) {
1206  $label = htmlspecialchars( $button['label'] );
1207  } elseif ( isset( $button['label-raw'] ) ) {
1208  $label = $button['label-raw'];
1209  } else {
1210  $label = htmlspecialchars( $button['value'] );
1211  }
1212 
1213  if ( $button['attribs'] ) {
1214  $attrs += $button['attribs'];
1215  }
1216 
1217  if ( isset( $button['id'] ) ) {
1218  $attrs['id'] = $button['id'];
1219  }
1220 
1221  if ( $useMediaWikiUIEverywhere ) {
1222  $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : [];
1223  $attrs['class'][] = 'mw-ui-button';
1224  }
1225 
1226  if ( $isBadIE ) {
1227  $buttons .= Html::element( 'input', $attrs ) . "\n";
1228  } else {
1229  $buttons .= Html::rawElement( 'button', $attrs, $label ) . "\n";
1230  }
1231  }
1232 
1233  if ( !$buttons ) {
1234  return '';
1235  }
1236 
1237  return Html::rawElement( 'span',
1238  [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1239  }
1240 
1245  public function getBody() {
1246  return $this->displaySection( $this->mFieldTree, $this->mTableId );
1247  }
1248 
1258  public function getErrors( $errors ) {
1259  wfDeprecated( __METHOD__ );
1260  return $this->getErrorsOrWarnings( $errors, 'error' );
1261  }
1262 
1271  public function getErrorsOrWarnings( $elements, $elementsType ) {
1272  if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1273  throw new DomainException( $elementsType . ' is not a valid type.' );
1274  }
1275  $elementstr = false;
1276  if ( $elements instanceof Status ) {
1277  list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1278  $status = $elementsType === 'error' ? $errorStatus : $warningStatus;
1279  if ( $status->isGood() ) {
1280  $elementstr = '';
1281  } else {
1282  $elementstr = $this->getOutput()->parse(
1283  $status->getWikiText()
1284  );
1285  }
1286  } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1287  $elementstr = $this->formatErrors( $elements );
1288  } elseif ( $elementsType === 'error' ) {
1289  $elementstr = $elements;
1290  }
1291 
1292  return $elementstr
1293  ? Html::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1294  : '';
1295  }
1296 
1304  public function formatErrors( $errors ) {
1305  $errorstr = '';
1306 
1307  foreach ( $errors as $error ) {
1308  $errorstr .= Html::rawElement(
1309  'li',
1310  [],
1311  $this->getMessage( $error )->parse()
1312  );
1313  }
1314 
1315  $errorstr = Html::rawElement( 'ul', [], $errorstr );
1316 
1317  return $errorstr;
1318  }
1319 
1327  public function setSubmitText( $t ) {
1328  $this->mSubmitText = $t;
1329 
1330  return $this;
1331  }
1332 
1339  public function setSubmitDestructive() {
1340  $this->mSubmitFlags = [ 'destructive', 'primary' ];
1341 
1342  return $this;
1343  }
1344 
1351  public function setSubmitProgressive() {
1352  $this->mSubmitFlags = [ 'progressive', 'primary' ];
1353 
1354  return $this;
1355  }
1356 
1365  public function setSubmitTextMsg( $msg ) {
1366  if ( !$msg instanceof Message ) {
1367  $msg = $this->msg( $msg );
1368  }
1369  $this->setSubmitText( $msg->text() );
1370 
1371  return $this;
1372  }
1373 
1378  public function getSubmitText() {
1379  return $this->mSubmitText ?: $this->msg( 'htmlform-submit' )->text();
1380  }
1381 
1387  public function setSubmitName( $name ) {
1388  $this->mSubmitName = $name;
1389 
1390  return $this;
1391  }
1392 
1398  public function setSubmitTooltip( $name ) {
1399  $this->mSubmitTooltip = $name;
1400 
1401  return $this;
1402  }
1403 
1412  public function setSubmitID( $t ) {
1413  $this->mSubmitID = $t;
1414 
1415  return $this;
1416  }
1417 
1433  public function setFormIdentifier( $ident ) {
1434  $this->mFormIdentifier = $ident;
1435 
1436  return $this;
1437  }
1438 
1449  public function suppressDefaultSubmit( $suppressSubmit = true ) {
1450  $this->mShowSubmit = !$suppressSubmit;
1451 
1452  return $this;
1453  }
1454 
1461  public function showCancel( $show = true ) {
1462  $this->mShowCancel = $show;
1463  return $this;
1464  }
1465 
1472  public function setCancelTarget( $target ) {
1473  $this->mCancelTarget = $target;
1474  return $this;
1475  }
1476 
1486  public function setTableId( $id ) {
1487  $this->mTableId = $id;
1488 
1489  return $this;
1490  }
1491 
1497  public function setId( $id ) {
1498  $this->mId = $id;
1499 
1500  return $this;
1501  }
1502 
1507  public function setName( $name ) {
1508  $this->mName = $name;
1509 
1510  return $this;
1511  }
1512 
1524  public function setWrapperLegend( $legend ) {
1525  $this->mWrapperLegend = $legend;
1526 
1527  return $this;
1528  }
1529 
1539  public function setWrapperLegendMsg( $msg ) {
1540  if ( !$msg instanceof Message ) {
1541  $msg = $this->msg( $msg );
1542  }
1543  $this->setWrapperLegend( $msg->text() );
1544 
1545  return $this;
1546  }
1547 
1557  public function setMessagePrefix( $p ) {
1558  $this->mMessagePrefix = $p;
1559 
1560  return $this;
1561  }
1562 
1570  public function setTitle( $t ) {
1571  $this->mTitle = $t;
1572 
1573  return $this;
1574  }
1575 
1580  public function getTitle() {
1581  return $this->mTitle === false
1582  ? $this->getContext()->getTitle()
1583  : $this->mTitle;
1584  }
1585 
1593  public function setMethod( $method = 'post' ) {
1594  $this->mMethod = strtolower( $method );
1595 
1596  return $this;
1597  }
1598 
1602  public function getMethod() {
1603  return $this->mMethod;
1604  }
1605 
1614  protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1615  return Xml::fieldset( $legend, $section, $attributes ) . "\n";
1616  }
1617 
1634  public function displaySection( $fields,
1635  $sectionName = '',
1636  $fieldsetIDPrefix = '',
1637  &$hasUserVisibleFields = false
1638  ) {
1639  if ( $this->mFieldData === null ) {
1640  throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1641  . 'You probably called displayForm() without calling prepareForm() first.' );
1642  }
1643 
1644  $displayFormat = $this->getDisplayFormat();
1645 
1646  $html = [];
1647  $subsectionHtml = '';
1648  $hasLabel = false;
1649 
1650  // Conveniently, PHP method names are case-insensitive.
1651  // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1652  $getFieldHtmlMethod = $displayFormat === 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1653 
1654  foreach ( $fields as $key => $value ) {
1655  if ( $value instanceof HTMLFormField ) {
1656  $v = array_key_exists( $key, $this->mFieldData )
1657  ? $this->mFieldData[$key]
1658  : $value->getDefault();
1659 
1660  $retval = $value->$getFieldHtmlMethod( $v );
1661 
1662  // check, if the form field should be added to
1663  // the output.
1664  if ( $value->hasVisibleOutput() ) {
1665  $html[] = $retval;
1666 
1667  $labelValue = trim( $value->getLabel() );
1668  if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
1669  $hasLabel = true;
1670  }
1671 
1672  $hasUserVisibleFields = true;
1673  }
1674  } elseif ( is_array( $value ) ) {
1675  $subsectionHasVisibleFields = false;
1676  $section =
1677  $this->displaySection( $value,
1678  "mw-htmlform-$key",
1679  "$fieldsetIDPrefix$key-",
1680  $subsectionHasVisibleFields );
1681  $legend = null;
1682 
1683  if ( $subsectionHasVisibleFields === true ) {
1684  // Display the section with various niceties.
1685  $hasUserVisibleFields = true;
1686 
1687  $legend = $this->getLegend( $key );
1688 
1689  $section = $this->getHeaderText( $key ) .
1690  $section .
1691  $this->getFooterText( $key );
1692 
1693  $attributes = [];
1694  if ( $fieldsetIDPrefix ) {
1695  $attributes['id'] = Sanitizer::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1696  }
1697  $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1698  } else {
1699  // Just return the inputs, nothing fancy.
1700  $subsectionHtml .= $section;
1701  }
1702  }
1703  }
1704 
1705  $html = $this->formatSection( $html, $sectionName, $hasLabel );
1706 
1707  if ( $subsectionHtml ) {
1708  if ( $this->mSubSectionBeforeFields ) {
1709  return $subsectionHtml . "\n" . $html;
1710  } else {
1711  return $html . "\n" . $subsectionHtml;
1712  }
1713  } else {
1714  return $html;
1715  }
1716  }
1717 
1725  protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1726  $displayFormat = $this->getDisplayFormat();
1727  $html = implode( '', $fieldsHtml );
1728 
1729  if ( $displayFormat === 'raw' ) {
1730  return $html;
1731  }
1732 
1733  $classes = [];
1734 
1735  if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1736  $classes[] = 'mw-htmlform-nolabel';
1737  }
1738 
1739  $attribs = [
1740  'class' => implode( ' ', $classes ),
1741  ];
1742 
1743  if ( $sectionName ) {
1744  $attribs['id'] = Sanitizer::escapeIdForAttribute( $sectionName );
1745  }
1746 
1747  if ( $displayFormat === 'table' ) {
1748  return Html::rawElement( 'table',
1749  $attribs,
1750  Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1751  } elseif ( $displayFormat === 'inline' ) {
1752  return Html::rawElement( 'span', $attribs, "\n$html\n" );
1753  } else {
1754  return Html::rawElement( 'div', $attribs, "\n$html\n" );
1755  }
1756  }
1757 
1761  public function loadData() {
1762  $fieldData = [];
1763 
1764  foreach ( $this->mFlatFields as $fieldname => $field ) {
1765  $request = $this->getRequest();
1766  if ( $field->skipLoadData( $request ) ) {
1767  continue;
1768  } elseif ( !empty( $field->mParams['disabled'] ) ) {
1769  $fieldData[$fieldname] = $field->getDefault();
1770  } else {
1771  $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1772  }
1773  }
1774 
1775  # Filter data.
1776  foreach ( $fieldData as $name => &$value ) {
1777  $field = $this->mFlatFields[$name];
1778  $value = $field->filter( $value, $this->mFlatFields );
1779  }
1780 
1781  $this->mFieldData = $fieldData;
1782  }
1783 
1791  public function suppressReset( $suppressReset = true ) {
1792  $this->mShowReset = !$suppressReset;
1793 
1794  return $this;
1795  }
1796 
1806  public function filterDataForSubmit( $data ) {
1807  return $data;
1808  }
1809 
1818  public function getLegend( $key ) {
1819  return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1820  }
1821 
1832  public function setAction( $action ) {
1833  $this->mAction = $action;
1834 
1835  return $this;
1836  }
1837 
1845  public function getAction() {
1846  // If an action is alredy provided, return it
1847  if ( $this->mAction !== false ) {
1848  return $this->mAction;
1849  }
1850 
1851  $articlePath = $this->getConfig()->get( 'ArticlePath' );
1852  // Check whether we are in GET mode and the ArticlePath contains a "?"
1853  // meaning that getLocalURL() would return something like "index.php?title=...".
1854  // As browser remove the query string before submitting GET forms,
1855  // it means that the title would be lost. In such case use wfScript() instead
1856  // and put title in an hidden field (see getHiddenFields()).
1857  if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1858  return wfScript();
1859  }
1860 
1861  return $this->getTitle()->getLocalURL();
1862  }
1863 
1874  public function setAutocomplete( $autocomplete ) {
1875  $this->mAutocomplete = $autocomplete;
1876 
1877  return $this;
1878  }
1879 
1886  protected function getMessage( $value ) {
1887  return Message::newFromSpecifier( $value )->setContext( $this );
1888  }
1889 
1899  public function needsJSForHtml5FormValidation() {
1900  foreach ( $this->mFlatFields as $fieldname => $field ) {
1901  if ( $field->needsJSForHtml5FormValidation() ) {
1902  return true;
1903  }
1904  }
1905  return false;
1906  }
1907 }
HTMLForm\$mSubSectionBeforeFields
$mSubSectionBeforeFields
If true, sections that contain both fields and subsections will render their subsections before their...
Definition: HTMLForm.php:241
HTMLForm\getLegend
getLegend( $key)
Get a string to go in the "<legend>" of a section fieldset.
Definition: HTMLForm.php:1818
HTMLForm\$mTokenSalt
string array $mTokenSalt
Salt for the edit token.
Definition: HTMLForm.php:232
HTMLForm\$typeMappings
static $typeMappings
Definition: HTMLForm.php:130
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:34
ContextSource\getConfig
getConfig()
Get the Config object.
Definition: ContextSource.php:68
HTMLForm\setPostText
setPostText( $msg)
Set text at the end of the display.
Definition: HTMLForm.php:892
HTMLForm\setAutocomplete
setAutocomplete( $autocomplete)
Set the value for the autocomplete attribute of the form.
Definition: HTMLForm.php:1874
HTMLForm\$mSubmitText
$mSubmitText
Definition: HTMLForm.php:200
HTMLForm\prepareForm
prepareForm()
Prepare form for submission.
Definition: HTMLForm.php:511
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:41
HTMLForm\hasField
hasField( $fieldname)
Definition: HTMLForm.php:366
HTMLForm\setPreText
setPreText( $msg)
Set the introductory message HTML, overwriting any existing message.
Definition: HTMLForm.php:743
HTMLForm\suppressDefaultSubmit
suppressDefaultSubmit( $suppressSubmit=true)
Stop a default submit button being shown for this form.
Definition: HTMLForm.php:1449
HTMLForm\$mSectionHeaders
$mSectionHeaders
Definition: HTMLForm.php:191
HTMLForm\setSubmitName
setSubmitName( $name)
Definition: HTMLForm.php:1387
HTMLForm\setFooterText
setFooterText( $msg, $section=null)
Set footer text, inside the form.
Definition: HTMLForm.php:847
HTMLForm\$mFieldTree
$mFieldTree
Definition: HTMLForm.php:178
HTMLForm\setIntro
setIntro( $msg)
Set the introductory message, overwriting any existing message.
Definition: HTMLForm.php:729
HTMLForm\getErrors
getErrors( $errors)
Format and display an error message stack.
Definition: HTMLForm.php:1258
HTMLForm\tryAuthorizedSubmit
tryAuthorizedSubmit()
Try submitting, with edit token check first.
Definition: HTMLForm.php:534
HTMLForm\setSubmitTooltip
setSubmitTooltip( $name)
Definition: HTMLForm.php:1398
HTMLForm\addHeaderText
addHeaderText( $msg, $section=null)
Add HTML to the header, inside the form.
Definition: HTMLForm.php:770
HTMLForm\$mTitle
$mTitle
Definition: HTMLForm.php:204
captcha-old.count
count
Definition: captcha-old.py:249
HTMLForm\setDisplayFormat
setDisplayFormat( $format)
Set format in which to display the form.
Definition: HTMLForm.php:392
HTMLForm\wrapForm
wrapForm( $html)
Wrap the form innards in an actual "<form>" element.
Definition: HTMLForm.php:1084
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
ContextSource\msg
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:189
Title\newMainPage
static newMainPage()
Create a new Title for the Main Page.
Definition: Title.php:581
HTMLForm\getHiddenFields
getHiddenFields()
Get the hidden fields that should go inside the form.
Definition: HTMLForm.php:1102
$result
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. '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 '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1963
HTMLForm\getDisplayFormat
getDisplayFormat()
Getter for displayFormat.
Definition: HTMLForm.php:427
HTMLForm\$mWasSubmitted
$mWasSubmitted
Definition: HTMLForm.php:206
HTMLForm\$mFieldData
$mFieldData
Definition: HTMLForm.php:171
HTMLForm\setHeaderText
setHeaderText( $msg, $section=null)
Set header text, inside the form.
Definition: HTMLForm.php:792
HTMLForm\formatErrors
formatErrors( $errors)
Format a stack of error messages into a single HTML string.
Definition: HTMLForm.php:1304
$status
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. '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 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object '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). '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:1245
HTMLForm\getClassFromDescriptor
static getClassFromDescriptor( $fieldname, &$descriptor)
Get the HTMLFormField subclass for this descriptor.
Definition: HTMLForm.php:458
HTMLForm\showCancel
showCancel( $show=true)
Show a cancel button (or prevent it).
Definition: HTMLForm.php:1461
HTMLForm\$mWrapperLegend
$mWrapperLegend
Definition: HTMLForm.php:226
HTMLForm\$mUseMultipart
$mUseMultipart
Definition: HTMLForm.php:222
HTMLForm\$mShowSubmit
$mShowSubmit
Definition: HTMLForm.php:180
HTMLForm\$mCancelTarget
$mCancelTarget
Definition: HTMLForm.php:183
HTMLForm\setTokenSalt
setTokenSalt( $salt)
Set the salt for the edit token.
Definition: HTMLForm.php:997
HTMLForm\$mSubmitTooltip
$mSubmitTooltip
Definition: HTMLForm.php:201
HTMLForm\$displayFormat
string $displayFormat
Format in which to display form.
Definition: HTMLForm.php:248
HTMLForm\show
show()
The here's-one-I-made-earlier option: do the submission if posted, or display the form with or withou...
Definition: HTMLForm.php:573
HTMLForm\$mSubmitID
$mSubmitID
Definition: HTMLForm.php:198
HTMLForm\setCancelTarget
setCancelTarget( $target)
Sets the target where the user is redirected to after clicking cancel.
Definition: HTMLForm.php:1472
HTMLForm\getBody
getBody()
Get the whole body of the form.
Definition: HTMLForm.php:1245
$res
$res
Definition: database.txt:21
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
ContextSource\getRequest
getRequest()
Get the WebRequest object.
Definition: ContextSource.php:78
HTMLForm\$mShowReset
$mShowReset
Definition: HTMLForm.php:179
HTMLForm\$mTableId
$mTableId
Definition: HTMLForm.php:196
HTMLForm\$mSubmitName
$mSubmitName
Definition: HTMLForm.php:199
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:133
HTMLForm\getAction
getAction()
Get the value for the action attribute of the form.
Definition: HTMLForm.php:1845
HTMLForm\setSubmitProgressive
setSubmitProgressive()
Identify that the submit button in the form has a progressive action.
Definition: HTMLForm.php:1351
HTMLForm\setMethod
setMethod( $method='post')
Set the method used to submit the form.
Definition: HTMLForm.php:1593
HTMLForm\$mButtons
$mButtons
Definition: HTMLForm.php:224
php
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
HTMLForm\__construct
__construct( $descriptor, $context=null, $messagePrefix='')
Build a new HTMLForm from an array of field attributes.
Definition: HTMLForm.php:302
Status
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:40
Xml\fieldset
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition: Xml.php:609
HTMLForm\setSubmitText
setSubmitText( $t)
Set the text for the submit button.
Definition: HTMLForm.php:1327
HTMLForm\trySubmit
trySubmit()
Validate all the fields, and call the submission callback function if everything is kosher.
Definition: HTMLForm.php:612
StatusValue\isGood
isGood()
Returns whether the operation completed and didn't have any error or warnings.
Definition: StatusValue.php:121
HTMLForm\$mSubmitFlags
$mSubmitFlags
Definition: HTMLForm.php:181
$html
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:1965
MWException
MediaWiki exception.
Definition: MWException.php:26
HTMLForm\$mAction
bool string $mAction
Form action URL.
Definition: HTMLForm.php:213
HTMLForm\setFormIdentifier
setFormIdentifier( $ident)
Set an internal identifier for this form.
Definition: HTMLForm.php:1433
HTMLForm\wrapFieldSetSection
wrapFieldSetSection( $legend, $section, $attributes)
Wraps the given $section into an user-visible fieldset.
Definition: HTMLForm.php:1614
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1176
HTMLForm\getHeaderText
getHeaderText( $section=null)
Get header text.
Definition: HTMLForm.php:809
HTMLForm\addButton
addButton( $data)
Add a button to the form.
Definition: HTMLForm.php:956
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2934
HTMLForm\addHiddenField
addHiddenField( $name, $value, array $attribs=[])
Add a hidden field to the output.
Definition: HTMLForm.php:907
ContextSource\getOutput
getOutput()
Get the OutputPage object.
Definition: ContextSource.php:123
HTMLForm\setSubmitID
setSubmitID( $t)
Set the id for the submit button.
Definition: HTMLForm.php:1412
ContextSource
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
Definition: ContextSource.php:30
HTMLForm\factory
static factory( $displayFormat)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:277
HTMLFormField
The parent class to generate form fields.
Definition: HTMLFormField.php:7
$attribs
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:1965
HTMLForm\wasSubmitted
wasSubmitted()
Test whether the form was considered to have been submitted or not, i.e.
Definition: HTMLForm.php:688
HTMLForm\$mFormIdentifier
$mFormIdentifier
Definition: HTMLForm.php:203
HTMLForm\formatSection
formatSection(array $fieldsHtml, $sectionName, $anyFieldHasLabel)
Put a form section together from the individual fields' HTML, merging it and wrapping.
Definition: HTMLForm.php:1725
HTMLForm\setMessagePrefix
setMessagePrefix( $p)
Set the prefix for various default messages.
Definition: HTMLForm.php:1557
HTMLForm\setSubmitCallback
setSubmitCallback( $cb)
Set a callback to a function to do something with the form once it's been successfully validated.
Definition: HTMLForm.php:702
HTMLForm\isVForm
isVForm()
Test if displayFormat is 'vform'.
Definition: HTMLForm.php:437
HTMLForm\$mId
$mId
Definition: HTMLForm.php:194
HTMLForm\$mSectionFooters
$mSectionFooters
Definition: HTMLForm.php:192
HTMLForm\loadInputFromParameters
static loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition: HTMLForm.php:486
ContextSource\setContext
setContext(IContextSource $context)
Set the IContextSource object.
Definition: ContextSource.php:58
list
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
HTMLForm\$mPost
$mPost
Definition: HTMLForm.php:193
$request
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:2581
HTMLForm\getErrorsOrWarnings
getErrorsOrWarnings( $elements, $elementsType)
Returns a formatted list of errors or warnings from the given elements.
Definition: HTMLForm.php:1271
Html\hidden
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:725
HTMLForm\$mFooter
$mFooter
Definition: HTMLForm.php:190
HTMLForm\getFormAttributes
getFormAttributes()
Get HTML attributes for the <form> tag.
Definition: HTMLForm.php:1050
HTMLForm\$mMethod
$mMethod
Definition: HTMLForm.php:205
$value
$value
Definition: styleTest.css.php:45
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[])
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2111
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
HTMLForm\setId
setId( $id)
Definition: HTMLForm.php:1497
HTMLForm\$availableSubclassDisplayFormats
array $availableSubclassDisplayFormats
Available formats in which to display the form.
Definition: HTMLForm.php:265
HTMLForm\$availableDisplayFormats
array $availableDisplayFormats
Available formats in which to display the form.
Definition: HTMLForm.php:254
$retval
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account incomplete not yet checked for validity & $retval
Definition: hooks.txt:244
HTMLForm\setWrapperLegend
setWrapperLegend( $legend)
Prompt the whole form to be wrapped in a "<fieldset>", with this text as its "<legend>" element.
Definition: HTMLForm.php:1524
ObjectFactory\constructClassInstance
static constructClassInstance( $clazz, $args)
Construct an instance of the given class using the given arguments.
Definition: ObjectFactory.php:129
HTMLForm\displaySection
displaySection( $fields, $sectionName='', $fieldsetIDPrefix='', &$hasUserVisibleFields=false)
Definition: HTMLForm.php:1634
HTMLForm\$mSubmitCallback
$mSubmitCallback
Definition: HTMLForm.php:185
HTMLForm\loadData
loadData()
Construct the form fields from the Descriptor array.
Definition: HTMLForm.php:1761
HTMLForm\showAlways
showAlways()
Same as self::show with the difference, that the form will be added to the output,...
Definition: HTMLForm.php:591
HTMLForm\$mName
$mName
Definition: HTMLForm.php:195
HTMLForm\setSubmitDestructive
setSubmitDestructive()
Identify that the submit button in the form has a destructive action.
Definition: HTMLForm.php:1339
HTMLForm\setValidationErrorMessage
setValidationErrorMessage( $msg)
Set a message to display on a validation error.
Definition: HTMLForm.php:716
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:55
HTMLForm\setSubmitTextMsg
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1365
$args
if( $line===false) $args
Definition: cdb.php:63
Title
Represents a title within MediaWiki.
Definition: Title.php:39
HTMLForm\setName
setName( $name)
Definition: HTMLForm.php:1507
HTMLForm\$mPre
$mPre
Definition: HTMLForm.php:188
HTMLForm\getHTML
getHTML( $submitResult)
Returns the raw HTML generated by the form.
Definition: HTMLForm.php:1026
HTMLForm\getSubmitText
getSubmitText()
Get the text for the submit button, either customised or a default.
Definition: HTMLForm.php:1378
HTMLForm\getMessage
getMessage( $value)
Turns a *-message parameter (which could be a MessageSpecifier, or a message name,...
Definition: HTMLForm.php:1886
HTMLForm\addHiddenFields
addHiddenFields(array $fields)
Add an array of hidden fields to the output.
Definition: HTMLForm.php:924
HTMLForm\$mShowCancel
$mShowCancel
Definition: HTMLForm.php:182
HTMLForm\setWrapperLegendMsg
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element.
Definition: HTMLForm.php:1539
HTMLForm\$mValidationErrorMessage
$mValidationErrorMessage
Definition: HTMLForm.php:186
HTMLForm\setAction
setAction( $action)
Set the value for the action attribute of the form.
Definition: HTMLForm.php:1832
$section
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:2981
HTMLForm\$mHeader
$mHeader
Definition: HTMLForm.php:189
HTMLForm\setTitle
setTitle( $t)
Set the title for form submission.
Definition: HTMLForm.php:1570
as
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
HTMLForm\setTableId
setTableId( $id)
Set the id of the <table> or outermost <div> element.
Definition: HTMLForm.php:1486
HTMLForm\$mMessagePrefix
$mMessagePrefix
Definition: HTMLForm.php:173
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
HTMLForm\displayForm
displayForm( $submitResult)
Display the form (sending to the context's OutputPage object), with an appropriate error message or s...
Definition: HTMLForm.php:1015
HTMLForm\$mHiddenFields
$mHiddenFields
Definition: HTMLForm.php:223
HTMLForm\$mAutocomplete
bool string $mAutocomplete
Form attribute autocomplete.
Definition: HTMLForm.php:220
HTMLForm\getTitle
getTitle()
Get the title.
Definition: HTMLForm.php:1580
HTMLForm\filterDataForSubmit
filterDataForSubmit( $data)
Overload this if you want to apply special filtration routines to the form as a whole,...
Definition: HTMLForm.php:1806
HTMLForm\getMethod
getMethod()
Definition: HTMLForm.php:1602
HTMLForm\addPreText
addPreText( $msg)
Add HTML to introductory message.
Definition: HTMLForm.php:756
class
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
$t
$t
Definition: testCompression.php:67
HTMLForm\getField
getField( $fieldname)
Definition: HTMLForm.php:375
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
HTMLForm\addPostText
addPostText( $msg)
Add text to the end of the display.
Definition: HTMLForm.php:879
HTMLForm\suppressReset
suppressReset( $suppressReset=true)
Stop a reset button being shown for this form.
Definition: HTMLForm.php:1791
HTMLForm\getFooterText
getFooterText( $section=null)
Get footer text.
Definition: HTMLForm.php:864
HTMLForm\$mFlatFields
HTMLFormField[] $mFlatFields
Definition: HTMLForm.php:176
HTMLForm\getButtons
getButtons()
Get the submit and (potentially) reset buttons.
Definition: HTMLForm.php:1136
HTMLForm\addFooterText
addFooterText( $msg, $section=null)
Add footer text, inside the form.
Definition: HTMLForm.php:825
array
the array() calling protocol came about after MediaWiki 1.4rc1.
Xml\submitButton
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:459
HTMLForm\needsJSForHtml5FormValidation
needsJSForHtml5FormValidation()
Whether this form, with its current fields, requires the user agent to have JavaScript enabled for th...
Definition: HTMLForm.php:1899
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:128