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