Merge "Enforce partial blocks"
[lhc/web/wiklou.git] / includes / htmlform / HTMLForm.php
1 <?php
2
3 /**
4 * HTML form generation and submission handling.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 */
23
24 use Wikimedia\ObjectFactory;
25
26 /**
27 * Object handling generic submission, CSRF protection, layout and
28 * other logic for UI forms. in a reusable manner.
29 *
30 * In order to generate the form, the HTMLForm object takes an array
31 * structure detailing the form fields available. Each element of the
32 * array is a basic property-list, including the type of field, the
33 * label it is to be given in the form, callbacks for validation and
34 * 'filtering', and other pertinent information.
35 *
36 * Field types are implemented as subclasses of the generic HTMLFormField
37 * object, and typically implement at least getInputHTML, which generates
38 * the HTML for the input field to be placed in the table.
39 *
40 * You can find extensive documentation on the www.mediawiki.org wiki:
41 * - https://www.mediawiki.org/wiki/HTMLForm
42 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
43 *
44 * The constructor input is an associative array of $fieldname => $info,
45 * where $info is an Associative Array with any of the following:
46 *
47 * 'class' -- the subclass of HTMLFormField that will be used
48 * to create the object. *NOT* the CSS class!
49 * 'type' -- roughly translates into the <select> type attribute.
50 * if 'class' is not specified, this is used as a map
51 * through HTMLForm::$typeMappings to get the class name.
52 * 'default' -- default value when the form is displayed
53 * 'nodata' -- if set (to any value, which casts to true), the data
54 * for this field will not be loaded from the actual request. Instead,
55 * always the default data is set as the value of this field.
56 * 'id' -- HTML id attribute
57 * 'cssclass' -- CSS class
58 * 'csshelpclass' -- CSS class used to style help text
59 * 'dir' -- Direction of the element.
60 * 'options' -- associative array mapping raw text labels to values.
61 * Some field types support multi-level arrays.
62 * Overwrites 'options-message'.
63 * 'options-messages' -- associative array mapping message keys to values.
64 * Some field types support multi-level arrays.
65 * Overwrites 'options' and 'options-message'.
66 * 'options-message' -- message key or object to be parsed to extract the list of
67 * options (like 'ipbreason-dropdown').
68 * 'label-message' -- message key or object for a message to use as the label.
69 * can be an array of msg key and then parameters to
70 * the message.
71 * 'label' -- alternatively, a raw text message. Overridden by
72 * label-message
73 * 'help' -- message text for a message to use as a help text.
74 * 'help-message' -- message key or object for a message to use as a help text.
75 * can be an array of msg key and then parameters to
76 * the message.
77 * Overwrites 'help-messages' and 'help'.
78 * 'help-messages' -- array of message keys/objects. As above, each item can
79 * be an array of msg key and then parameters.
80 * Overwrites 'help'.
81 * 'help-inline' -- Whether help text (defined using options above) will be shown
82 * inline after the input field, rather than in a popup.
83 * Defaults to true. Only used by OOUI form fields.
84 * 'notice' -- (deprecated, use 'help' instead)
85 * 'notice-messages' -- (deprecated, use 'help-messages' instead)
86 * 'notice-message' -- (deprecated, use 'help-message' instead)
87 * 'required' -- passed through to the object, indicating that it
88 * is a required field.
89 * 'size' -- the length of text fields
90 * 'filter-callback' -- a function name to give you the chance to
91 * massage the inputted value before it's processed.
92 * @see HTMLFormField::filter()
93 * 'validation-callback' -- a function name to give you the chance
94 * to impose extra validation on the field input.
95 * @see HTMLFormField::validate()
96 * 'name' -- By default, the 'name' attribute of the input field
97 * is "wp{$fieldname}". If you want a different name
98 * (eg one without the "wp" prefix), specify it here and
99 * it will be used without modification.
100 * 'hide-if' -- expression given as an array stating when the field
101 * should be hidden. The first array value has to be the
102 * expression's logic operator. Supported expressions:
103 * 'NOT'
104 * [ 'NOT', array $expression ]
105 * To hide a field if a given expression is not true.
106 * '==='
107 * [ '===', string $fieldName, string $value ]
108 * To hide a field if another field identified by
109 * $field has the value $value.
110 * '!=='
111 * [ '!==', string $fieldName, string $value ]
112 * Same as [ 'NOT', [ '===', $fieldName, $value ]
113 * 'OR', 'AND', 'NOR', 'NAND'
114 * [ 'XXX', array $expression1, ..., array $expressionN ]
115 * To hide a field if one or more (OR), all (AND),
116 * neither (NOR) or not all (NAND) given expressions
117 * are evaluated as true.
118 * The expressions will be given to a JavaScript frontend
119 * module which will continually update the field's
120 * visibility.
121 *
122 * Since 1.20, you can chain mutators to ease the form generation:
123 * @par Example:
124 * @code
125 * $form = new HTMLForm( $someFields );
126 * $form->setMethod( 'get' )
127 * ->setWrapperLegendMsg( 'message-key' )
128 * ->prepareForm()
129 * ->displayForm( '' );
130 * @endcode
131 * Note that you will have prepareForm and displayForm at the end. Other
132 * methods call done after that would simply not be part of the form :(
133 *
134 * @todo Document 'section' / 'subsection' stuff
135 */
136 class HTMLForm extends ContextSource {
137 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
138 public static $typeMappings = [
139 'api' => HTMLApiField::class,
140 'text' => HTMLTextField::class,
141 'textwithbutton' => HTMLTextFieldWithButton::class,
142 'textarea' => HTMLTextAreaField::class,
143 'select' => HTMLSelectField::class,
144 'combobox' => HTMLComboboxField::class,
145 'radio' => HTMLRadioField::class,
146 'multiselect' => HTMLMultiSelectField::class,
147 'limitselect' => HTMLSelectLimitField::class,
148 'check' => HTMLCheckField::class,
149 'toggle' => HTMLCheckField::class,
150 'int' => HTMLIntField::class,
151 'float' => HTMLFloatField::class,
152 'info' => HTMLInfoField::class,
153 'selectorother' => HTMLSelectOrOtherField::class,
154 'selectandother' => HTMLSelectAndOtherField::class,
155 'namespaceselect' => HTMLSelectNamespace::class,
156 'namespaceselectwithbutton' => HTMLSelectNamespaceWithButton::class,
157 'tagfilter' => HTMLTagFilter::class,
158 'sizefilter' => HTMLSizeFilterField::class,
159 'submit' => HTMLSubmitField::class,
160 'hidden' => HTMLHiddenField::class,
161 'edittools' => HTMLEditTools::class,
162 'checkmatrix' => HTMLCheckMatrix::class,
163 'cloner' => HTMLFormFieldCloner::class,
164 'autocompleteselect' => HTMLAutoCompleteSelectField::class,
165 'date' => HTMLDateTimeField::class,
166 'time' => HTMLDateTimeField::class,
167 'datetime' => HTMLDateTimeField::class,
168 'expiry' => HTMLExpiryField::class,
169 // HTMLTextField will output the correct type="" attribute automagically.
170 // There are about four zillion other HTML5 input types, like range, but
171 // we don't use those at the moment, so no point in adding all of them.
172 'email' => HTMLTextField::class,
173 'password' => HTMLTextField::class,
174 'url' => HTMLTextField::class,
175 'title' => HTMLTitleTextField::class,
176 'user' => HTMLUserTextField::class,
177 'usersmultiselect' => HTMLUsersMultiselectField::class,
178 'titlesmultiselect' => HTMLTitlesMultiselectField::class,
179 ];
180
181 public $mFieldData;
182
183 protected $mMessagePrefix;
184
185 /** @var HTMLFormField[] */
186 protected $mFlatFields;
187
188 protected $mFieldTree;
189 protected $mShowReset = false;
190 protected $mShowSubmit = true;
191 protected $mSubmitFlags = [ 'primary', 'progressive' ];
192 protected $mShowCancel = false;
193 protected $mCancelTarget;
194
195 protected $mSubmitCallback;
196 protected $mValidationErrorMessage;
197
198 protected $mPre = '';
199 protected $mHeader = '';
200 protected $mFooter = '';
201 protected $mSectionHeaders = [];
202 protected $mSectionFooters = [];
203 protected $mPost = '';
204 protected $mId;
205 protected $mName;
206 protected $mTableId = '';
207
208 protected $mSubmitID;
209 protected $mSubmitName;
210 protected $mSubmitText;
211 protected $mSubmitTooltip;
212
213 protected $mFormIdentifier;
214 protected $mTitle;
215 protected $mMethod = 'post';
216 protected $mWasSubmitted = false;
217
218 /**
219 * Form action URL. false means we will use the URL to set Title
220 * @since 1.19
221 * @var bool|string
222 */
223 protected $mAction = false;
224
225 /**
226 * Form attribute autocomplete. A typical value is "off". null does not set the attribute
227 * @since 1.27
228 * @var string|null
229 */
230 protected $mAutocomplete = null;
231
232 protected $mUseMultipart = false;
233 protected $mHiddenFields = [];
234 protected $mButtons = [];
235
236 protected $mWrapperLegend = false;
237
238 /**
239 * Salt for the edit token.
240 * @var string|array
241 */
242 protected $mTokenSalt = '';
243
244 /**
245 * If true, sections that contain both fields and subsections will
246 * render their subsections before their fields.
247 *
248 * Subclasses may set this to false to render subsections after fields
249 * instead.
250 */
251 protected $mSubSectionBeforeFields = true;
252
253 /**
254 * Format in which to display form. For viable options,
255 * @see $availableDisplayFormats
256 * @var string
257 */
258 protected $displayFormat = 'table';
259
260 /**
261 * Available formats in which to display the form
262 * @var array
263 */
264 protected $availableDisplayFormats = [
265 'table',
266 'div',
267 'raw',
268 'inline',
269 ];
270
271 /**
272 * Available formats in which to display the form
273 * @var array
274 */
275 protected $availableSubclassDisplayFormats = [
276 'vform',
277 'ooui',
278 ];
279
280 /**
281 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
282 *
283 * @param string $displayFormat
284 * @param mixed $arguments,... Additional arguments to pass to the constructor.
285 * @return HTMLForm
286 */
287 public static function factory( $displayFormat/*, $arguments...*/ ) {
288 $arguments = func_get_args();
289 array_shift( $arguments );
290
291 switch ( $displayFormat ) {
292 case 'vform':
293 return ObjectFactory::constructClassInstance( VFormHTMLForm::class, $arguments );
294 case 'ooui':
295 return ObjectFactory::constructClassInstance( OOUIHTMLForm::class, $arguments );
296 default:
297 /** @var HTMLForm $form */
298 $form = ObjectFactory::constructClassInstance( self::class, $arguments );
299 $form->setDisplayFormat( $displayFormat );
300 return $form;
301 }
302 }
303
304 /**
305 * Build a new HTMLForm from an array of field attributes
306 *
307 * @param array $descriptor Array of Field constructs, as described above
308 * @param IContextSource|null $context Available since 1.18, will become compulsory in 1.18.
309 * Obviates the need to call $form->setTitle()
310 * @param string $messagePrefix A prefix to go in front of default messages
311 */
312 public function __construct( $descriptor, /*IContextSource*/ $context = null,
313 $messagePrefix = ''
314 ) {
315 if ( $context instanceof IContextSource ) {
316 $this->setContext( $context );
317 $this->mTitle = false; // We don't need them to set a title
318 $this->mMessagePrefix = $messagePrefix;
319 } elseif ( $context === null && $messagePrefix !== '' ) {
320 $this->mMessagePrefix = $messagePrefix;
321 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
322 // B/C since 1.18
323 // it's actually $messagePrefix
324 $this->mMessagePrefix = $context;
325 }
326
327 // Evil hack for mobile :(
328 if (
329 !$this->getConfig()->get( 'HTMLFormAllowTableFormat' )
330 && $this->displayFormat === 'table'
331 ) {
332 $this->displayFormat = 'div';
333 }
334
335 // Expand out into a tree.
336 $loadedDescriptor = [];
337 $this->mFlatFields = [];
338
339 foreach ( $descriptor as $fieldname => $info ) {
340 $section = $info['section'] ?? '';
341
342 if ( isset( $info['type'] ) && $info['type'] === 'file' ) {
343 $this->mUseMultipart = true;
344 }
345
346 $field = static::loadInputFromParameters( $fieldname, $info, $this );
347
348 $setSection =& $loadedDescriptor;
349 if ( $section ) {
350 $sectionParts = explode( '/', $section );
351
352 while ( count( $sectionParts ) ) {
353 $newName = array_shift( $sectionParts );
354
355 if ( !isset( $setSection[$newName] ) ) {
356 $setSection[$newName] = [];
357 }
358
359 $setSection =& $setSection[$newName];
360 }
361 }
362
363 $setSection[$fieldname] = $field;
364 $this->mFlatFields[$fieldname] = $field;
365 }
366
367 $this->mFieldTree = $loadedDescriptor;
368 }
369
370 /**
371 * @param string $fieldname
372 * @return bool
373 */
374 public function hasField( $fieldname ) {
375 return isset( $this->mFlatFields[$fieldname] );
376 }
377
378 /**
379 * @param string $fieldname
380 * @return HTMLFormField
381 * @throws DomainException on invalid field name
382 */
383 public function getField( $fieldname ) {
384 if ( !$this->hasField( $fieldname ) ) {
385 throw new DomainException( __METHOD__ . ': no field named ' . $fieldname );
386 }
387 return $this->mFlatFields[$fieldname];
388 }
389
390 /**
391 * Set format in which to display the form
392 *
393 * @param string $format The name of the format to use, must be one of
394 * $this->availableDisplayFormats
395 *
396 * @throws MWException
397 * @since 1.20
398 * @return HTMLForm $this for chaining calls (since 1.20)
399 */
400 public function setDisplayFormat( $format ) {
401 if (
402 in_array( $format, $this->availableSubclassDisplayFormats, true ) ||
403 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats, true )
404 ) {
405 throw new MWException( 'Cannot change display format after creation, ' .
406 'use HTMLForm::factory() instead' );
407 }
408
409 if ( !in_array( $format, $this->availableDisplayFormats, true ) ) {
410 throw new MWException( 'Display format must be one of ' .
411 print_r(
412 array_merge(
413 $this->availableDisplayFormats,
414 $this->availableSubclassDisplayFormats
415 ),
416 true
417 ) );
418 }
419
420 // Evil hack for mobile :(
421 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
422 $format = 'div';
423 }
424
425 $this->displayFormat = $format;
426
427 return $this;
428 }
429
430 /**
431 * Getter for displayFormat
432 * @since 1.20
433 * @return string
434 */
435 public function getDisplayFormat() {
436 return $this->displayFormat;
437 }
438
439 /**
440 * Get the HTMLFormField subclass for this descriptor.
441 *
442 * The descriptor can be passed either 'class' which is the name of
443 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
444 * This makes sure the 'class' is always set, and also is returned by
445 * this function for ease.
446 *
447 * @since 1.23
448 *
449 * @param string $fieldname Name of the field
450 * @param array &$descriptor Input Descriptor, as described above
451 *
452 * @throws MWException
453 * @return string Name of a HTMLFormField subclass
454 */
455 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
456 if ( isset( $descriptor['class'] ) ) {
457 $class = $descriptor['class'];
458 } elseif ( isset( $descriptor['type'] ) ) {
459 $class = static::$typeMappings[$descriptor['type']];
460 $descriptor['class'] = $class;
461 } else {
462 $class = null;
463 }
464
465 if ( !$class ) {
466 throw new MWException( "Descriptor with no class for $fieldname: "
467 . print_r( $descriptor, true ) );
468 }
469
470 return $class;
471 }
472
473 /**
474 * Initialise a new Object for the field
475 *
476 * @param string $fieldname Name of the field
477 * @param array $descriptor Input Descriptor, as described above
478 * @param HTMLForm|null $parent Parent instance of HTMLForm
479 *
480 * @throws MWException
481 * @return HTMLFormField Instance of a subclass of HTMLFormField
482 */
483 public static function loadInputFromParameters( $fieldname, $descriptor,
484 HTMLForm $parent = null
485 ) {
486 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
487
488 $descriptor['fieldname'] = $fieldname;
489 if ( $parent ) {
490 $descriptor['parent'] = $parent;
491 }
492
493 # @todo This will throw a fatal error whenever someone try to use
494 # 'class' to feed a CSS class instead of 'cssclass'. Would be
495 # great to avoid the fatal error and show a nice error.
496 return new $class( $descriptor );
497 }
498
499 /**
500 * Prepare form for submission.
501 *
502 * @warning When doing method chaining, that should be the very last
503 * method call before displayForm().
504 *
505 * @throws MWException
506 * @return HTMLForm $this for chaining calls (since 1.20)
507 */
508 public function prepareForm() {
509 # Check if we have the info we need
510 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
511 throw new MWException( 'You must call setTitle() on an HTMLForm' );
512 }
513
514 # Load data from the request.
515 if (
516 $this->mFormIdentifier === null ||
517 $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier
518 ) {
519 $this->loadData();
520 } else {
521 $this->mFieldData = [];
522 }
523
524 return $this;
525 }
526
527 /**
528 * Try submitting, with edit token check first
529 * @return Status|bool
530 */
531 public function tryAuthorizedSubmit() {
532 $result = false;
533
534 $identOkay = false;
535 if ( $this->mFormIdentifier === null ) {
536 $identOkay = true;
537 } else {
538 $identOkay = $this->getRequest()->getVal( 'wpFormIdentifier' ) === $this->mFormIdentifier;
539 }
540
541 $tokenOkay = false;
542 if ( $this->getMethod() !== 'post' ) {
543 $tokenOkay = true; // no session check needed
544 } elseif ( $this->getRequest()->wasPosted() ) {
545 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
546 if ( $this->getUser()->isLoggedIn() || $editToken !== null ) {
547 // Session tokens for logged-out users have no security value.
548 // However, if the user gave one, check it in order to give a nice
549 // "session expired" error instead of "permission denied" or such.
550 $tokenOkay = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
551 } else {
552 $tokenOkay = true;
553 }
554 }
555
556 if ( $tokenOkay && $identOkay ) {
557 $this->mWasSubmitted = true;
558 $result = $this->trySubmit();
559 }
560
561 return $result;
562 }
563
564 /**
565 * The here's-one-I-made-earlier option: do the submission if
566 * posted, or display the form with or without funky validation
567 * errors
568 * @return bool|Status Whether submission was successful.
569 */
570 public function show() {
571 $this->prepareForm();
572
573 $result = $this->tryAuthorizedSubmit();
574 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
575 return $result;
576 }
577
578 $this->displayForm( $result );
579
580 return false;
581 }
582
583 /**
584 * Same as self::show with the difference, that the form will be
585 * added to the output, no matter, if the validation was good or not.
586 * @return bool|Status Whether submission was successful.
587 */
588 public function showAlways() {
589 $this->prepareForm();
590
591 $result = $this->tryAuthorizedSubmit();
592
593 $this->displayForm( $result );
594
595 return $result;
596 }
597
598 /**
599 * Validate all the fields, and call the submission callback
600 * function if everything is kosher.
601 * @throws MWException
602 * @return bool|string|array|Status
603 * - Bool true or a good Status object indicates success,
604 * - Bool false indicates no submission was attempted,
605 * - Anything else indicates failure. The value may be a fatal Status
606 * object, an HTML string, or an array of arrays (message keys and
607 * params) or strings (message keys)
608 */
609 public function trySubmit() {
610 $valid = true;
611 $hoistedErrors = Status::newGood();
612 if ( $this->mValidationErrorMessage ) {
613 foreach ( (array)$this->mValidationErrorMessage as $error ) {
614 $hoistedErrors->fatal( ...$error );
615 }
616 } else {
617 $hoistedErrors->fatal( 'htmlform-invalid-input' );
618 }
619
620 $this->mWasSubmitted = true;
621
622 # Check for cancelled submission
623 foreach ( $this->mFlatFields as $fieldname => $field ) {
624 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
625 continue;
626 }
627 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
628 $this->mWasSubmitted = false;
629 return false;
630 }
631 }
632
633 # Check for validation
634 foreach ( $this->mFlatFields as $fieldname => $field ) {
635 if ( !array_key_exists( $fieldname, $this->mFieldData ) ) {
636 continue;
637 }
638 if ( $field->isHidden( $this->mFieldData ) ) {
639 continue;
640 }
641 $res = $field->validate( $this->mFieldData[$fieldname], $this->mFieldData );
642 if ( $res !== true ) {
643 $valid = false;
644 if ( $res !== false && !$field->canDisplayErrors() ) {
645 if ( is_string( $res ) ) {
646 $hoistedErrors->fatal( 'rawmessage', $res );
647 } else {
648 $hoistedErrors->fatal( $res );
649 }
650 }
651 }
652 }
653
654 if ( !$valid ) {
655 return $hoistedErrors;
656 }
657
658 $callback = $this->mSubmitCallback;
659 if ( !is_callable( $callback ) ) {
660 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
661 'setSubmitCallback() to set one.' );
662 }
663
664 $data = $this->filterDataForSubmit( $this->mFieldData );
665
666 $res = call_user_func( $callback, $data, $this );
667 if ( $res === false ) {
668 $this->mWasSubmitted = false;
669 }
670
671 return $res;
672 }
673
674 /**
675 * Test whether the form was considered to have been submitted or not, i.e.
676 * whether the last call to tryAuthorizedSubmit or trySubmit returned
677 * non-false.
678 *
679 * This will return false until HTMLForm::tryAuthorizedSubmit or
680 * HTMLForm::trySubmit is called.
681 *
682 * @since 1.23
683 * @return bool
684 */
685 public function wasSubmitted() {
686 return $this->mWasSubmitted;
687 }
688
689 /**
690 * Set a callback to a function to do something with the form
691 * once it's been successfully validated.
692 *
693 * @param callable $cb The function will be passed the output from
694 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
695 * return as documented for HTMLForm::trySubmit
696 *
697 * @return HTMLForm $this for chaining calls (since 1.20)
698 */
699 public function setSubmitCallback( $cb ) {
700 $this->mSubmitCallback = $cb;
701
702 return $this;
703 }
704
705 /**
706 * Set a message to display on a validation error.
707 *
708 * @param string|array $msg String or Array of valid inputs to wfMessage()
709 * (so each entry can be either a String or Array)
710 *
711 * @return HTMLForm $this for chaining calls (since 1.20)
712 */
713 public function setValidationErrorMessage( $msg ) {
714 $this->mValidationErrorMessage = $msg;
715
716 return $this;
717 }
718
719 /**
720 * Set the introductory message, overwriting any existing message.
721 *
722 * @param string $msg Complete text of message to display
723 *
724 * @return HTMLForm $this for chaining calls (since 1.20)
725 */
726 public function setIntro( $msg ) {
727 $this->setPreText( $msg );
728
729 return $this;
730 }
731
732 /**
733 * Set the introductory message HTML, overwriting any existing message.
734 * @since 1.19
735 *
736 * @param string $msg Complete HTML of message to display
737 *
738 * @return HTMLForm $this for chaining calls (since 1.20)
739 */
740 public function setPreText( $msg ) {
741 $this->mPre = $msg;
742
743 return $this;
744 }
745
746 /**
747 * Add HTML to introductory message.
748 *
749 * @param string $msg Complete HTML of message to display
750 *
751 * @return HTMLForm $this for chaining calls (since 1.20)
752 */
753 public function addPreText( $msg ) {
754 $this->mPre .= $msg;
755
756 return $this;
757 }
758
759 /**
760 * Get the introductory message HTML.
761 *
762 * @since 1.32
763 *
764 * @return string
765 */
766 public function getPreText() {
767 return $this->mPre;
768 }
769
770 /**
771 * Add HTML to the header, inside the form.
772 *
773 * @param string $msg Additional HTML to display in header
774 * @param string|null $section The section to add the header to
775 *
776 * @return HTMLForm $this for chaining calls (since 1.20)
777 */
778 public function addHeaderText( $msg, $section = null ) {
779 if ( $section === null ) {
780 $this->mHeader .= $msg;
781 } else {
782 if ( !isset( $this->mSectionHeaders[$section] ) ) {
783 $this->mSectionHeaders[$section] = '';
784 }
785 $this->mSectionHeaders[$section] .= $msg;
786 }
787
788 return $this;
789 }
790
791 /**
792 * Set header text, inside the form.
793 * @since 1.19
794 *
795 * @param string $msg Complete HTML of header to display
796 * @param string|null $section The section to add the header to
797 *
798 * @return HTMLForm $this for chaining calls (since 1.20)
799 */
800 public function setHeaderText( $msg, $section = null ) {
801 if ( $section === null ) {
802 $this->mHeader = $msg;
803 } else {
804 $this->mSectionHeaders[$section] = $msg;
805 }
806
807 return $this;
808 }
809
810 /**
811 * Get header text.
812 *
813 * @param string|null $section The section to get the header text for
814 * @since 1.26
815 * @return string HTML
816 */
817 public function getHeaderText( $section = null ) {
818 if ( $section === null ) {
819 return $this->mHeader;
820 } else {
821 return $this->mSectionHeaders[$section] ?? '';
822 }
823 }
824
825 /**
826 * Add footer text, inside the form.
827 *
828 * @param string $msg Complete text of message to display
829 * @param string|null $section The section to add the footer text to
830 *
831 * @return HTMLForm $this for chaining calls (since 1.20)
832 */
833 public function addFooterText( $msg, $section = null ) {
834 if ( $section === null ) {
835 $this->mFooter .= $msg;
836 } else {
837 if ( !isset( $this->mSectionFooters[$section] ) ) {
838 $this->mSectionFooters[$section] = '';
839 }
840 $this->mSectionFooters[$section] .= $msg;
841 }
842
843 return $this;
844 }
845
846 /**
847 * Set footer text, inside the form.
848 * @since 1.19
849 *
850 * @param string $msg Complete text of message to display
851 * @param string|null $section The section to add the footer text to
852 *
853 * @return HTMLForm $this for chaining calls (since 1.20)
854 */
855 public function setFooterText( $msg, $section = null ) {
856 if ( $section === null ) {
857 $this->mFooter = $msg;
858 } else {
859 $this->mSectionFooters[$section] = $msg;
860 }
861
862 return $this;
863 }
864
865 /**
866 * Get footer text.
867 *
868 * @param string|null $section The section to get the footer text for
869 * @since 1.26
870 * @return string
871 */
872 public function getFooterText( $section = null ) {
873 if ( $section === null ) {
874 return $this->mFooter;
875 } else {
876 return $this->mSectionFooters[$section] ?? '';
877 }
878 }
879
880 /**
881 * Add text to the end of the display.
882 *
883 * @param string $msg Complete text of message to display
884 *
885 * @return HTMLForm $this for chaining calls (since 1.20)
886 */
887 public function addPostText( $msg ) {
888 $this->mPost .= $msg;
889
890 return $this;
891 }
892
893 /**
894 * Set text at the end of the display.
895 *
896 * @param string $msg Complete text of message to display
897 *
898 * @return HTMLForm $this for chaining calls (since 1.20)
899 */
900 public function setPostText( $msg ) {
901 $this->mPost = $msg;
902
903 return $this;
904 }
905
906 /**
907 * Add a hidden field to the output
908 *
909 * @param string $name Field name. This will be used exactly as entered
910 * @param string $value Field value
911 * @param array $attribs
912 *
913 * @return HTMLForm $this for chaining calls (since 1.20)
914 */
915 public function addHiddenField( $name, $value, array $attribs = [] ) {
916 $attribs += [ 'name' => $name ];
917 $this->mHiddenFields[] = [ $value, $attribs ];
918
919 return $this;
920 }
921
922 /**
923 * Add an array of hidden fields to the output
924 *
925 * @since 1.22
926 *
927 * @param array $fields Associative array of fields to add;
928 * mapping names to their values
929 *
930 * @return HTMLForm $this for chaining calls
931 */
932 public function addHiddenFields( array $fields ) {
933 foreach ( $fields as $name => $value ) {
934 $this->mHiddenFields[] = [ $value, [ 'name' => $name ] ];
935 }
936
937 return $this;
938 }
939
940 /**
941 * Add a button to the form
942 *
943 * @since 1.27 takes an array as shown. Earlier versions accepted
944 * 'name', 'value', 'id', and 'attribs' as separate parameters in that
945 * order.
946 * @note Custom labels ('label', 'label-message', 'label-raw') are not
947 * supported for IE6 and IE7 due to bugs in those browsers. If detected,
948 * they will be served buttons using 'value' as the button label.
949 * @param array $data Data to define the button:
950 * - name: (string) Button name.
951 * - value: (string) Button value.
952 * - label-message: (string, optional) Button label message key to use
953 * instead of 'value'. Overrides 'label' and 'label-raw'.
954 * - label: (string, optional) Button label text to use instead of
955 * 'value'. Overrides 'label-raw'.
956 * - label-raw: (string, optional) Button label HTML to use instead of
957 * 'value'.
958 * - id: (string, optional) DOM id for the button.
959 * - attribs: (array, optional) Additional HTML attributes.
960 * - flags: (string|string[], optional) OOUI flags.
961 * - framed: (boolean=true, optional) OOUI framed attribute.
962 * @return HTMLForm $this for chaining calls (since 1.20)
963 */
964 public function addButton( $data ) {
965 if ( !is_array( $data ) ) {
966 $args = func_get_args();
967 if ( count( $args ) < 2 || count( $args ) > 4 ) {
968 throw new InvalidArgumentException(
969 'Incorrect number of arguments for deprecated calling style'
970 );
971 }
972 $data = [
973 'name' => $args[0],
974 'value' => $args[1],
975 'id' => $args[2] ?? null,
976 'attribs' => $args[3] ?? null,
977 ];
978 } else {
979 if ( !isset( $data['name'] ) ) {
980 throw new InvalidArgumentException( 'A name is required' );
981 }
982 if ( !isset( $data['value'] ) ) {
983 throw new InvalidArgumentException( 'A value is required' );
984 }
985 }
986 $this->mButtons[] = $data + [
987 'id' => null,
988 'attribs' => null,
989 'flags' => null,
990 'framed' => true,
991 ];
992
993 return $this;
994 }
995
996 /**
997 * Set the salt for the edit token.
998 *
999 * Only useful when the method is "post".
1000 *
1001 * @since 1.24
1002 * @param string|array $salt Salt to use
1003 * @return HTMLForm $this For chaining calls
1004 */
1005 public function setTokenSalt( $salt ) {
1006 $this->mTokenSalt = $salt;
1007
1008 return $this;
1009 }
1010
1011 /**
1012 * Display the form (sending to the context's OutputPage object), with an
1013 * appropriate error message or stack of messages, and any validation errors, etc.
1014 *
1015 * @warning You should call prepareForm() before calling this function.
1016 * Moreover, when doing method chaining this should be the very last method
1017 * call just after prepareForm().
1018 *
1019 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1020 *
1021 * @return void Nothing, should be last call
1022 */
1023 public function displayForm( $submitResult ) {
1024 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
1025 }
1026
1027 /**
1028 * Returns the raw HTML generated by the form
1029 *
1030 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
1031 *
1032 * @return string HTML
1033 * @return-taint escaped
1034 */
1035 public function getHTML( $submitResult ) {
1036 # For good measure (it is the default)
1037 $this->getOutput()->preventClickjacking();
1038 $this->getOutput()->addModules( 'mediawiki.htmlform' );
1039 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
1040
1041 $html = ''
1042 . $this->getErrorsOrWarnings( $submitResult, 'error' )
1043 . $this->getErrorsOrWarnings( $submitResult, 'warning' )
1044 . $this->getHeaderText()
1045 . $this->getBody()
1046 . $this->getHiddenFields()
1047 . $this->getButtons()
1048 . $this->getFooterText();
1049
1050 $html = $this->wrapForm( $html );
1051
1052 return '' . $this->mPre . $html . $this->mPost;
1053 }
1054
1055 /**
1056 * Get HTML attributes for the `<form>` tag.
1057 * @return array
1058 */
1059 protected function getFormAttributes() {
1060 # Use multipart/form-data
1061 $encType = $this->mUseMultipart
1062 ? 'multipart/form-data'
1063 : 'application/x-www-form-urlencoded';
1064 # Attributes
1065 $attribs = [
1066 'class' => 'mw-htmlform',
1067 'action' => $this->getAction(),
1068 'method' => $this->getMethod(),
1069 'enctype' => $encType,
1070 ];
1071 if ( $this->mId ) {
1072 $attribs['id'] = $this->mId;
1073 }
1074 if ( is_string( $this->mAutocomplete ) ) {
1075 $attribs['autocomplete'] = $this->mAutocomplete;
1076 }
1077 if ( $this->mName ) {
1078 $attribs['name'] = $this->mName;
1079 }
1080 if ( $this->needsJSForHtml5FormValidation() ) {
1081 $attribs['novalidate'] = true;
1082 }
1083 return $attribs;
1084 }
1085
1086 /**
1087 * Wrap the form innards in an actual "<form>" element
1088 *
1089 * @param string $html HTML contents to wrap.
1090 *
1091 * @return string Wrapped HTML.
1092 */
1093 public function wrapForm( $html ) {
1094 # Include a <fieldset> wrapper for style, if requested.
1095 if ( $this->mWrapperLegend !== false ) {
1096 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend : false;
1097 $html = Xml::fieldset( $legend, $html );
1098 }
1099
1100 return Html::rawElement(
1101 'form',
1102 $this->getFormAttributes(),
1103 $html
1104 );
1105 }
1106
1107 /**
1108 * Get the hidden fields that should go inside the form.
1109 * @return string HTML.
1110 */
1111 public function getHiddenFields() {
1112 $html = '';
1113 if ( $this->mFormIdentifier !== null ) {
1114 $html .= Html::hidden(
1115 'wpFormIdentifier',
1116 $this->mFormIdentifier
1117 ) . "\n";
1118 }
1119 if ( $this->getMethod() === 'post' ) {
1120 $html .= Html::hidden(
1121 'wpEditToken',
1122 $this->getUser()->getEditToken( $this->mTokenSalt ),
1123 [ 'id' => 'wpEditToken' ]
1124 ) . "\n";
1125 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1126 }
1127
1128 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1129 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1130 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1131 }
1132
1133 foreach ( $this->mHiddenFields as $data ) {
1134 list( $value, $attribs ) = $data;
1135 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
1136 }
1137
1138 return $html;
1139 }
1140
1141 /**
1142 * Get the submit and (potentially) reset buttons.
1143 * @return string HTML.
1144 */
1145 public function getButtons() {
1146 $buttons = '';
1147 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1148
1149 if ( $this->mShowSubmit ) {
1150 $attribs = [];
1151
1152 if ( isset( $this->mSubmitID ) ) {
1153 $attribs['id'] = $this->mSubmitID;
1154 }
1155
1156 if ( isset( $this->mSubmitName ) ) {
1157 $attribs['name'] = $this->mSubmitName;
1158 }
1159
1160 if ( isset( $this->mSubmitTooltip ) ) {
1161 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1162 }
1163
1164 $attribs['class'] = [ 'mw-htmlform-submit' ];
1165
1166 if ( $useMediaWikiUIEverywhere ) {
1167 foreach ( $this->mSubmitFlags as $flag ) {
1168 $attribs['class'][] = 'mw-ui-' . $flag;
1169 }
1170 $attribs['class'][] = 'mw-ui-button';
1171 }
1172
1173 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1174 }
1175
1176 if ( $this->mShowReset ) {
1177 $buttons .= Html::element(
1178 'input',
1179 [
1180 'type' => 'reset',
1181 'value' => $this->msg( 'htmlform-reset' )->text(),
1182 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1183 ]
1184 ) . "\n";
1185 }
1186
1187 if ( $this->mShowCancel ) {
1188 $target = $this->mCancelTarget ?: Title::newMainPage();
1189 if ( $target instanceof Title ) {
1190 $target = $target->getLocalURL();
1191 }
1192 $buttons .= Html::element(
1193 'a',
1194 [
1195 'class' => $useMediaWikiUIEverywhere ? 'mw-ui-button' : null,
1196 'href' => $target,
1197 ],
1198 $this->msg( 'cancel' )->text()
1199 ) . "\n";
1200 }
1201
1202 // IE<8 has bugs with <button>, so we'll need to avoid them.
1203 $isBadIE = preg_match( '/MSIE [1-7]\./i', $this->getRequest()->getHeader( 'User-Agent' ) );
1204
1205 foreach ( $this->mButtons as $button ) {
1206 $attrs = [
1207 'type' => 'submit',
1208 'name' => $button['name'],
1209 'value' => $button['value']
1210 ];
1211
1212 if ( isset( $button['label-message'] ) ) {
1213 $label = $this->getMessage( $button['label-message'] )->parse();
1214 } elseif ( isset( $button['label'] ) ) {
1215 $label = htmlspecialchars( $button['label'] );
1216 } elseif ( isset( $button['label-raw'] ) ) {
1217 $label = $button['label-raw'];
1218 } else {
1219 $label = htmlspecialchars( $button['value'] );
1220 }
1221
1222 if ( $button['attribs'] ) {
1223 $attrs += $button['attribs'];
1224 }
1225
1226 if ( isset( $button['id'] ) ) {
1227 $attrs['id'] = $button['id'];
1228 }
1229
1230 if ( $useMediaWikiUIEverywhere ) {
1231 $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : [];
1232 $attrs['class'][] = 'mw-ui-button';
1233 }
1234
1235 if ( $isBadIE ) {
1236 $buttons .= Html::element( 'input', $attrs ) . "\n";
1237 } else {
1238 $buttons .= Html::rawElement( 'button', $attrs, $label ) . "\n";
1239 }
1240 }
1241
1242 if ( !$buttons ) {
1243 return '';
1244 }
1245
1246 return Html::rawElement( 'span',
1247 [ 'class' => 'mw-htmlform-submit-buttons' ], "\n$buttons" ) . "\n";
1248 }
1249
1250 /**
1251 * Get the whole body of the form.
1252 * @return string
1253 */
1254 public function getBody() {
1255 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1256 }
1257
1258 /**
1259 * Format and display an error message stack.
1260 *
1261 * @param string|array|Status $errors
1262 *
1263 * @deprecated since 1.28, use getErrorsOrWarnings() instead
1264 *
1265 * @return string
1266 */
1267 public function getErrors( $errors ) {
1268 wfDeprecated( __METHOD__ );
1269 return $this->getErrorsOrWarnings( $errors, 'error' );
1270 }
1271
1272 /**
1273 * Returns a formatted list of errors or warnings from the given elements.
1274 *
1275 * @param string|array|Status $elements The set of errors/warnings to process.
1276 * @param string $elementsType Should warnings or errors be returned. This is meant
1277 * for Status objects, all other valid types are always considered as errors.
1278 * @return string
1279 */
1280 public function getErrorsOrWarnings( $elements, $elementsType ) {
1281 if ( !in_array( $elementsType, [ 'error', 'warning' ], true ) ) {
1282 throw new DomainException( $elementsType . ' is not a valid type.' );
1283 }
1284 $elementstr = false;
1285 if ( $elements instanceof Status ) {
1286 list( $errorStatus, $warningStatus ) = $elements->splitByErrorType();
1287 $status = $elementsType === 'error' ? $errorStatus : $warningStatus;
1288 if ( $status->isGood() ) {
1289 $elementstr = '';
1290 } else {
1291 $elementstr = $this->getOutput()->parse(
1292 $status->getWikiText()
1293 );
1294 }
1295 } elseif ( is_array( $elements ) && $elementsType === 'error' ) {
1296 $elementstr = $this->formatErrors( $elements );
1297 } elseif ( $elementsType === 'error' ) {
1298 $elementstr = $elements;
1299 }
1300
1301 return $elementstr
1302 ? Html::rawElement( 'div', [ 'class' => $elementsType ], $elementstr )
1303 : '';
1304 }
1305
1306 /**
1307 * Format a stack of error messages into a single HTML string
1308 *
1309 * @param array $errors Array of message keys/values
1310 *
1311 * @return string HTML, a "<ul>" list of errors
1312 */
1313 public function formatErrors( $errors ) {
1314 $errorstr = '';
1315
1316 foreach ( $errors as $error ) {
1317 $errorstr .= Html::rawElement(
1318 'li',
1319 [],
1320 $this->getMessage( $error )->parse()
1321 );
1322 }
1323
1324 $errorstr = Html::rawElement( 'ul', [], $errorstr );
1325
1326 return $errorstr;
1327 }
1328
1329 /**
1330 * Set the text for the submit button
1331 *
1332 * @param string $t Plaintext
1333 *
1334 * @return HTMLForm $this for chaining calls (since 1.20)
1335 */
1336 public function setSubmitText( $t ) {
1337 $this->mSubmitText = $t;
1338
1339 return $this;
1340 }
1341
1342 /**
1343 * Identify that the submit button in the form has a destructive action
1344 * @since 1.24
1345 *
1346 * @return HTMLForm $this for chaining calls (since 1.28)
1347 */
1348 public function setSubmitDestructive() {
1349 $this->mSubmitFlags = [ 'destructive', 'primary' ];
1350
1351 return $this;
1352 }
1353
1354 /**
1355 * Identify that the submit button in the form has a progressive action
1356 * @since 1.25
1357 * @deprecated since 1.32, No need to call. Submit button already
1358 * has a progressive action form.
1359 *
1360 * @return HTMLForm $this for chaining calls (since 1.28)
1361 */
1362 public function setSubmitProgressive() {
1363 wfDeprecated( __METHOD__, '1.32' );
1364 $this->mSubmitFlags = [ 'progressive', 'primary' ];
1365
1366 return $this;
1367 }
1368
1369 /**
1370 * Set the text for the submit button to a message
1371 * @since 1.19
1372 *
1373 * @param string|Message $msg Message key or Message object
1374 *
1375 * @return HTMLForm $this for chaining calls (since 1.20)
1376 */
1377 public function setSubmitTextMsg( $msg ) {
1378 if ( !$msg instanceof Message ) {
1379 $msg = $this->msg( $msg );
1380 }
1381 $this->setSubmitText( $msg->text() );
1382
1383 return $this;
1384 }
1385
1386 /**
1387 * Get the text for the submit button, either customised or a default.
1388 * @return string
1389 */
1390 public function getSubmitText() {
1391 return $this->mSubmitText ?: $this->msg( 'htmlform-submit' )->text();
1392 }
1393
1394 /**
1395 * @param string $name Submit button name
1396 *
1397 * @return HTMLForm $this for chaining calls (since 1.20)
1398 */
1399 public function setSubmitName( $name ) {
1400 $this->mSubmitName = $name;
1401
1402 return $this;
1403 }
1404
1405 /**
1406 * @param string $name Tooltip for the submit button
1407 *
1408 * @return HTMLForm $this for chaining calls (since 1.20)
1409 */
1410 public function setSubmitTooltip( $name ) {
1411 $this->mSubmitTooltip = $name;
1412
1413 return $this;
1414 }
1415
1416 /**
1417 * Set the id for the submit button.
1418 *
1419 * @param string $t
1420 *
1421 * @todo FIXME: Integrity of $t is *not* validated
1422 * @return HTMLForm $this for chaining calls (since 1.20)
1423 */
1424 public function setSubmitID( $t ) {
1425 $this->mSubmitID = $t;
1426
1427 return $this;
1428 }
1429
1430 /**
1431 * Set an internal identifier for this form. It will be submitted as a hidden form field, allowing
1432 * HTMLForm to determine whether the form was submitted (or merely viewed). Setting this serves
1433 * two purposes:
1434 *
1435 * - If you use two or more forms on one page, it allows HTMLForm to identify which of the forms
1436 * was submitted, and not attempt to validate the other ones.
1437 * - If you use checkbox or multiselect fields inside a form using the GET method, it allows
1438 * HTMLForm to distinguish between the initial page view and a form submission with all
1439 * checkboxes or select options unchecked.
1440 *
1441 * @since 1.28
1442 * @param string $ident
1443 * @return $this
1444 */
1445 public function setFormIdentifier( $ident ) {
1446 $this->mFormIdentifier = $ident;
1447
1448 return $this;
1449 }
1450
1451 /**
1452 * Stop a default submit button being shown for this form. This implies that an
1453 * alternate submit method must be provided manually.
1454 *
1455 * @since 1.22
1456 *
1457 * @param bool $suppressSubmit Set to false to re-enable the button again
1458 *
1459 * @return HTMLForm $this for chaining calls
1460 */
1461 public function suppressDefaultSubmit( $suppressSubmit = true ) {
1462 $this->mShowSubmit = !$suppressSubmit;
1463
1464 return $this;
1465 }
1466
1467 /**
1468 * Show a cancel button (or prevent it). The button is not shown by default.
1469 * @param bool $show
1470 * @return HTMLForm $this for chaining calls
1471 * @since 1.27
1472 */
1473 public function showCancel( $show = true ) {
1474 $this->mShowCancel = $show;
1475 return $this;
1476 }
1477
1478 /**
1479 * Sets the target where the user is redirected to after clicking cancel.
1480 * @param Title|string $target Target as a Title object or an URL
1481 * @return HTMLForm $this for chaining calls
1482 * @since 1.27
1483 */
1484 public function setCancelTarget( $target ) {
1485 $this->mCancelTarget = $target;
1486 return $this;
1487 }
1488
1489 /**
1490 * Set the id of the \<table\> or outermost \<div\> element.
1491 *
1492 * @since 1.22
1493 *
1494 * @param string $id New value of the id attribute, or "" to remove
1495 *
1496 * @return HTMLForm $this for chaining calls
1497 */
1498 public function setTableId( $id ) {
1499 $this->mTableId = $id;
1500
1501 return $this;
1502 }
1503
1504 /**
1505 * @param string $id DOM id for the form
1506 *
1507 * @return HTMLForm $this for chaining calls (since 1.20)
1508 */
1509 public function setId( $id ) {
1510 $this->mId = $id;
1511
1512 return $this;
1513 }
1514
1515 /**
1516 * @param string $name 'name' attribute for the form
1517 * @return HTMLForm $this for chaining calls
1518 */
1519 public function setName( $name ) {
1520 $this->mName = $name;
1521
1522 return $this;
1523 }
1524
1525 /**
1526 * Prompt the whole form to be wrapped in a "<fieldset>", with
1527 * this text as its "<legend>" element.
1528 *
1529 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1530 * If true, a wrapper will be displayed, but no legend.
1531 * If a string, a wrapper will be displayed with that string as a legend.
1532 * The string will be escaped before being output (this doesn't support HTML).
1533 *
1534 * @return HTMLForm $this for chaining calls (since 1.20)
1535 */
1536 public function setWrapperLegend( $legend ) {
1537 $this->mWrapperLegend = $legend;
1538
1539 return $this;
1540 }
1541
1542 /**
1543 * Prompt the whole form to be wrapped in a "<fieldset>", with
1544 * this message as its "<legend>" element.
1545 * @since 1.19
1546 *
1547 * @param string|Message $msg Message key or Message object
1548 *
1549 * @return HTMLForm $this for chaining calls (since 1.20)
1550 */
1551 public function setWrapperLegendMsg( $msg ) {
1552 if ( !$msg instanceof Message ) {
1553 $msg = $this->msg( $msg );
1554 }
1555 $this->setWrapperLegend( $msg->text() );
1556
1557 return $this;
1558 }
1559
1560 /**
1561 * Set the prefix for various default messages
1562 * @todo Currently only used for the "<fieldset>" legend on forms
1563 * with multiple sections; should be used elsewhere?
1564 *
1565 * @param string $p
1566 *
1567 * @return HTMLForm $this for chaining calls (since 1.20)
1568 */
1569 public function setMessagePrefix( $p ) {
1570 $this->mMessagePrefix = $p;
1571
1572 return $this;
1573 }
1574
1575 /**
1576 * Set the title for form submission
1577 *
1578 * @param Title $t Title of page the form is on/should be posted to
1579 *
1580 * @return HTMLForm $this for chaining calls (since 1.20)
1581 */
1582 public function setTitle( $t ) {
1583 $this->mTitle = $t;
1584
1585 return $this;
1586 }
1587
1588 /**
1589 * Get the title
1590 * @return Title
1591 */
1592 public function getTitle() {
1593 return $this->mTitle === false
1594 ? $this->getContext()->getTitle()
1595 : $this->mTitle;
1596 }
1597
1598 /**
1599 * Set the method used to submit the form
1600 *
1601 * @param string $method
1602 *
1603 * @return HTMLForm $this for chaining calls (since 1.20)
1604 */
1605 public function setMethod( $method = 'post' ) {
1606 $this->mMethod = strtolower( $method );
1607
1608 return $this;
1609 }
1610
1611 /**
1612 * @return string Always lowercase
1613 */
1614 public function getMethod() {
1615 return $this->mMethod;
1616 }
1617
1618 /**
1619 * Wraps the given $section into an user-visible fieldset.
1620 *
1621 * @param string $legend Legend text for the fieldset
1622 * @param string $section The section content in plain Html
1623 * @param array $attributes Additional attributes for the fieldset
1624 * @param bool $isRoot Section is at the root of the tree
1625 * @return string The fieldset's Html
1626 */
1627 protected function wrapFieldSetSection( $legend, $section, $attributes, $isRoot ) {
1628 return Xml::fieldset( $legend, $section, $attributes ) . "\n";
1629 }
1630
1631 /**
1632 * @todo Document
1633 *
1634 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1635 * objects).
1636 * @param string $sectionName ID attribute of the "<table>" tag for this
1637 * section, ignored if empty.
1638 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1639 * each subsection, ignored if empty.
1640 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1641 * @throws LogicException When called on uninitialized field data, e.g. When
1642 * HTMLForm::displayForm was called without calling HTMLForm::prepareForm
1643 * first.
1644 *
1645 * @return string
1646 */
1647 public function displaySection( $fields,
1648 $sectionName = '',
1649 $fieldsetIDPrefix = '',
1650 &$hasUserVisibleFields = false
1651 ) {
1652 if ( $this->mFieldData === null ) {
1653 throw new LogicException( 'HTMLForm::displaySection() called on uninitialized field data. '
1654 . 'You probably called displayForm() without calling prepareForm() first.' );
1655 }
1656
1657 $displayFormat = $this->getDisplayFormat();
1658
1659 $html = [];
1660 $subsectionHtml = '';
1661 $hasLabel = false;
1662
1663 // Conveniently, PHP method names are case-insensitive.
1664 // For grep: this can call getDiv, getRaw, getInline, getVForm, getOOUI
1665 $getFieldHtmlMethod = $displayFormat === 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1666
1667 foreach ( $fields as $key => $value ) {
1668 if ( $value instanceof HTMLFormField ) {
1669 $v = array_key_exists( $key, $this->mFieldData )
1670 ? $this->mFieldData[$key]
1671 : $value->getDefault();
1672
1673 $retval = $value->$getFieldHtmlMethod( $v );
1674
1675 // check, if the form field should be added to
1676 // the output.
1677 if ( $value->hasVisibleOutput() ) {
1678 $html[] = $retval;
1679
1680 $labelValue = trim( $value->getLabel() );
1681 if ( $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' && $labelValue !== '' ) {
1682 $hasLabel = true;
1683 }
1684
1685 $hasUserVisibleFields = true;
1686 }
1687 } elseif ( is_array( $value ) ) {
1688 $subsectionHasVisibleFields = false;
1689 $section =
1690 $this->displaySection( $value,
1691 "mw-htmlform-$key",
1692 "$fieldsetIDPrefix$key-",
1693 $subsectionHasVisibleFields );
1694 $legend = null;
1695
1696 if ( $subsectionHasVisibleFields === true ) {
1697 // Display the section with various niceties.
1698 $hasUserVisibleFields = true;
1699
1700 $legend = $this->getLegend( $key );
1701
1702 $section = $this->getHeaderText( $key ) .
1703 $section .
1704 $this->getFooterText( $key );
1705
1706 $attributes = [];
1707 if ( $fieldsetIDPrefix ) {
1708 $attributes['id'] = Sanitizer::escapeIdForAttribute( "$fieldsetIDPrefix$key" );
1709 }
1710 $subsectionHtml .= $this->wrapFieldSetSection(
1711 $legend, $section, $attributes, $fields === $this->mFieldTree
1712 );
1713 } else {
1714 // Just return the inputs, nothing fancy.
1715 $subsectionHtml .= $section;
1716 }
1717 }
1718 }
1719
1720 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1721
1722 if ( $subsectionHtml ) {
1723 if ( $this->mSubSectionBeforeFields ) {
1724 return $subsectionHtml . "\n" . $html;
1725 } else {
1726 return $html . "\n" . $subsectionHtml;
1727 }
1728 } else {
1729 return $html;
1730 }
1731 }
1732
1733 /**
1734 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1735 * @param array $fieldsHtml
1736 * @param string $sectionName
1737 * @param bool $anyFieldHasLabel
1738 * @return string HTML
1739 */
1740 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1741 if ( !$fieldsHtml ) {
1742 // Do not generate any wrappers for empty sections. Sections may be empty if they only have
1743 // subsections, but no fields. A legend will still be added in wrapFieldSetSection().
1744 return '';
1745 }
1746
1747 $displayFormat = $this->getDisplayFormat();
1748 $html = implode( '', $fieldsHtml );
1749
1750 if ( $displayFormat === 'raw' ) {
1751 return $html;
1752 }
1753
1754 $classes = [];
1755
1756 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1757 $classes[] = 'mw-htmlform-nolabel';
1758 }
1759
1760 $attribs = [
1761 'class' => implode( ' ', $classes ),
1762 ];
1763
1764 if ( $sectionName ) {
1765 $attribs['id'] = Sanitizer::escapeIdForAttribute( $sectionName );
1766 }
1767
1768 if ( $displayFormat === 'table' ) {
1769 return Html::rawElement( 'table',
1770 $attribs,
1771 Html::rawElement( 'tbody', [], "\n$html\n" ) ) . "\n";
1772 } elseif ( $displayFormat === 'inline' ) {
1773 return Html::rawElement( 'span', $attribs, "\n$html\n" );
1774 } else {
1775 return Html::rawElement( 'div', $attribs, "\n$html\n" );
1776 }
1777 }
1778
1779 /**
1780 * Construct the form fields from the Descriptor array
1781 */
1782 public function loadData() {
1783 $fieldData = [];
1784
1785 foreach ( $this->mFlatFields as $fieldname => $field ) {
1786 $request = $this->getRequest();
1787 if ( $field->skipLoadData( $request ) ) {
1788 continue;
1789 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1790 $fieldData[$fieldname] = $field->getDefault();
1791 } else {
1792 $fieldData[$fieldname] = $field->loadDataFromRequest( $request );
1793 }
1794 }
1795
1796 # Filter data.
1797 foreach ( $fieldData as $name => &$value ) {
1798 $field = $this->mFlatFields[$name];
1799 $value = $field->filter( $value, $this->mFlatFields );
1800 }
1801
1802 $this->mFieldData = $fieldData;
1803 }
1804
1805 /**
1806 * Stop a reset button being shown for this form
1807 *
1808 * @param bool $suppressReset Set to false to re-enable the button again
1809 *
1810 * @return HTMLForm $this for chaining calls (since 1.20)
1811 */
1812 public function suppressReset( $suppressReset = true ) {
1813 $this->mShowReset = !$suppressReset;
1814
1815 return $this;
1816 }
1817
1818 /**
1819 * Overload this if you want to apply special filtration routines
1820 * to the form as a whole, after it's submitted but before it's
1821 * processed.
1822 *
1823 * @param array $data
1824 *
1825 * @return array
1826 */
1827 public function filterDataForSubmit( $data ) {
1828 return $data;
1829 }
1830
1831 /**
1832 * Get a string to go in the "<legend>" of a section fieldset.
1833 * Override this if you want something more complicated.
1834 *
1835 * @param string $key
1836 *
1837 * @return string Plain text (not HTML-escaped)
1838 */
1839 public function getLegend( $key ) {
1840 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1841 }
1842
1843 /**
1844 * Set the value for the action attribute of the form.
1845 * When set to false (which is the default state), the set title is used.
1846 *
1847 * @since 1.19
1848 *
1849 * @param string|bool $action
1850 *
1851 * @return HTMLForm $this for chaining calls (since 1.20)
1852 */
1853 public function setAction( $action ) {
1854 $this->mAction = $action;
1855
1856 return $this;
1857 }
1858
1859 /**
1860 * Get the value for the action attribute of the form.
1861 *
1862 * @since 1.22
1863 *
1864 * @return string
1865 */
1866 public function getAction() {
1867 // If an action is alredy provided, return it
1868 if ( $this->mAction !== false ) {
1869 return $this->mAction;
1870 }
1871
1872 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1873 // Check whether we are in GET mode and the ArticlePath contains a "?"
1874 // meaning that getLocalURL() would return something like "index.php?title=...".
1875 // As browser remove the query string before submitting GET forms,
1876 // it means that the title would be lost. In such case use wfScript() instead
1877 // and put title in an hidden field (see getHiddenFields()).
1878 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1879 return wfScript();
1880 }
1881
1882 return $this->getTitle()->getLocalURL();
1883 }
1884
1885 /**
1886 * Set the value for the autocomplete attribute of the form. A typical value is "off".
1887 * When set to null (which is the default state), the attribute get not set.
1888 *
1889 * @since 1.27
1890 *
1891 * @param string|null $autocomplete
1892 *
1893 * @return HTMLForm $this for chaining calls
1894 */
1895 public function setAutocomplete( $autocomplete ) {
1896 $this->mAutocomplete = $autocomplete;
1897
1898 return $this;
1899 }
1900
1901 /**
1902 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1903 * name + parameters array) into a Message.
1904 * @param mixed $value
1905 * @return Message
1906 */
1907 protected function getMessage( $value ) {
1908 return Message::newFromSpecifier( $value )->setContext( $this );
1909 }
1910
1911 /**
1912 * Whether this form, with its current fields, requires the user agent to have JavaScript enabled
1913 * for the client-side HTML5 form validation to work correctly. If this function returns true, a
1914 * 'novalidate' attribute will be added on the `<form>` element. It will be removed if the user
1915 * agent has JavaScript support, in htmlform.js.
1916 *
1917 * @return bool
1918 * @since 1.29
1919 */
1920 public function needsJSForHtml5FormValidation() {
1921 foreach ( $this->mFlatFields as $fieldname => $field ) {
1922 if ( $field->needsJSForHtml5FormValidation() ) {
1923 return true;
1924 }
1925 }
1926 return false;
1927 }
1928 }