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