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