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