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