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