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