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