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