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