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