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