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