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