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