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