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