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