Merge "Don't trigger MessageBlobStore during tests"
[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 * 'options' -- associative array mapping labels to values.
55 * Some field types support multi-level arrays.
56 * 'options-messages' -- associative array mapping message keys to values.
57 * Some field types support multi-level arrays.
58 * 'options-message' -- message key to be parsed to extract the list of
59 * options (like 'ipbreason-dropdown').
60 * 'label-message' -- message key for a message to use as the label.
61 * can be an array of msg key and then parameters to
62 * the message.
63 * 'label' -- alternatively, a raw text message. Overridden by
64 * label-message
65 * 'help' -- message text for a message to use as a help text.
66 * 'help-message' -- message key for a message to use as a help text.
67 * can be an array of msg key and then parameters to
68 * the message.
69 * Overwrites 'help-messages' and 'help'.
70 * 'help-messages' -- array of message key. As above, each item can
71 * be an array of msg key and then parameters.
72 * Overwrites 'help'.
73 * 'required' -- passed through to the object, indicating that it
74 * is a required field.
75 * 'size' -- the length of text fields
76 * 'filter-callback -- a function name to give you the chance to
77 * massage the inputted value before it's processed.
78 * @see HTMLForm::filter()
79 * 'validation-callback' -- a function name to give you the chance
80 * to impose extra validation on the field input.
81 * @see HTMLForm::validate()
82 * 'name' -- By default, the 'name' attribute of the input field
83 * is "wp{$fieldname}". If you want a different name
84 * (eg one without the "wp" prefix), specify it here and
85 * it will be used without modification.
86 *
87 * Since 1.20, you can chain mutators to ease the form generation:
88 * @par Example:
89 * @code
90 * $form = new HTMLForm( $someFields );
91 * $form->setMethod( 'get' )
92 * ->setWrapperLegendMsg( 'message-key' )
93 * ->prepareForm()
94 * ->displayForm( '' );
95 * @endcode
96 * Note that you will have prepareForm and displayForm at the end. Other
97 * methods call done after that would simply not be part of the form :(
98 *
99 * @todo Document 'section' / 'subsection' stuff
100 */
101 class HTMLForm extends ContextSource {
102 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
103 public static $typeMappings = array(
104 'api' => 'HTMLApiField',
105 'text' => 'HTMLTextField',
106 'textarea' => 'HTMLTextAreaField',
107 'select' => 'HTMLSelectField',
108 'radio' => 'HTMLRadioField',
109 'multiselect' => 'HTMLMultiSelectField',
110 'limitselect' => 'HTMLSelectLimitField',
111 'check' => 'HTMLCheckField',
112 'toggle' => 'HTMLCheckField',
113 'int' => 'HTMLIntField',
114 'float' => 'HTMLFloatField',
115 'info' => 'HTMLInfoField',
116 'selectorother' => 'HTMLSelectOrOtherField',
117 'selectandother' => 'HTMLSelectAndOtherField',
118 'namespaceselect' => 'HTMLSelectNamespace',
119 'tagfilter' => 'HTMLTagFilter',
120 'submit' => 'HTMLSubmitField',
121 'hidden' => 'HTMLHiddenField',
122 'edittools' => 'HTMLEditTools',
123 'checkmatrix' => 'HTMLCheckMatrix',
124 'cloner' => 'HTMLFormFieldCloner',
125 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
126 // HTMLTextField will output the correct type="" attribute automagically.
127 // There are about four zillion other HTML5 input types, like range, but
128 // we don't use those at the moment, so no point in adding all of them.
129 'email' => 'HTMLTextField',
130 'password' => 'HTMLTextField',
131 'url' => 'HTMLTextField',
132 );
133
134 public $mFieldData;
135
136 protected $mMessagePrefix;
137
138 /** @var HTMLFormField[] */
139 protected $mFlatFields;
140
141 protected $mFieldTree;
142 protected $mShowReset = false;
143 protected $mShowSubmit = true;
144 protected $mSubmitModifierClass = 'mw-ui-constructive';
145
146 protected $mSubmitCallback;
147 protected $mValidationErrorMessage;
148
149 protected $mPre = '';
150 protected $mHeader = '';
151 protected $mFooter = '';
152 protected $mSectionHeaders = array();
153 protected $mSectionFooters = array();
154 protected $mPost = '';
155 protected $mId;
156 protected $mTableId = '';
157
158 protected $mSubmitID;
159 protected $mSubmitName;
160 protected $mSubmitText;
161 protected $mSubmitTooltip;
162
163 protected $mTitle;
164 protected $mMethod = 'post';
165 protected $mWasSubmitted = false;
166
167 /**
168 * Form action URL. false means we will use the URL to set Title
169 * @since 1.19
170 * @var bool|string
171 */
172 protected $mAction = false;
173
174 protected $mUseMultipart = false;
175 protected $mHiddenFields = array();
176 protected $mButtons = array();
177
178 protected $mWrapperLegend = false;
179
180 /**
181 * Salt for the edit token.
182 * @var string|array
183 */
184 protected $mTokenSalt = '';
185
186 /**
187 * If true, sections that contain both fields and subsections will
188 * render their subsections before their fields.
189 *
190 * Subclasses may set this to false to render subsections after fields
191 * instead.
192 */
193 protected $mSubSectionBeforeFields = true;
194
195 /**
196 * Format in which to display form. For viable options,
197 * @see $availableDisplayFormats
198 * @var string
199 */
200 protected $displayFormat = 'table';
201
202 /**
203 * Available formats in which to display the form
204 * @var array
205 */
206 protected $availableDisplayFormats = array(
207 'table',
208 'div',
209 'raw',
210 'inline',
211 );
212
213 /**
214 * Available formats in which to display the form
215 * @var array
216 */
217 protected $availableSubclassDisplayFormats = array(
218 'vform',
219 );
220
221 /**
222 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
223 *
224 * @throws MWException When the display format requested is not known
225 * @param string $displayFormat
226 * @param mixed $arguments... Additional arguments to pass to the constructor.
227 * @return HTMLForm
228 */
229 public static function factory( $displayFormat/*, $arguments...*/ ) {
230 $arguments = func_get_args();
231 array_shift( $arguments );
232
233 switch ( $displayFormat ) {
234 case 'vform':
235 $reflector = new ReflectionClass( 'VFormHTMLForm' );
236 return $reflector->newInstanceArgs( $arguments );
237 default:
238 $reflector = new ReflectionClass( 'HTMLForm' );
239 $form = $reflector->newInstanceArgs( $arguments );
240 $form->setDisplayFormat( $displayFormat );
241 return $form;
242 }
243 }
244
245 /**
246 * Build a new HTMLForm from an array of field attributes
247 *
248 * @param array $descriptor Array of Field constructs, as described above
249 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
250 * Obviates the need to call $form->setTitle()
251 * @param string $messagePrefix A prefix to go in front of default messages
252 */
253 public function __construct( $descriptor, /*IContextSource*/ $context = null,
254 $messagePrefix = ''
255 ) {
256 if ( $context instanceof IContextSource ) {
257 $this->setContext( $context );
258 $this->mTitle = false; // We don't need them to set a title
259 $this->mMessagePrefix = $messagePrefix;
260 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
261 $this->mMessagePrefix = $messagePrefix;
262 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
263 // B/C since 1.18
264 // it's actually $messagePrefix
265 $this->mMessagePrefix = $context;
266 }
267
268 // Evil hack for mobile :(
269 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $this->displayFormat === 'table' ) {
270 $this->displayFormat = 'div';
271 }
272
273 // Expand out into a tree.
274 $loadedDescriptor = array();
275 $this->mFlatFields = array();
276
277 foreach ( $descriptor as $fieldname => $info ) {
278 $section = isset( $info['section'] )
279 ? $info['section']
280 : '';
281
282 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
283 $this->mUseMultipart = true;
284 }
285
286 $field = static::loadInputFromParameters( $fieldname, $info, $this );
287
288 $setSection =& $loadedDescriptor;
289 if ( $section ) {
290 $sectionParts = explode( '/', $section );
291
292 while ( count( $sectionParts ) ) {
293 $newName = array_shift( $sectionParts );
294
295 if ( !isset( $setSection[$newName] ) ) {
296 $setSection[$newName] = array();
297 }
298
299 $setSection =& $setSection[$newName];
300 }
301 }
302
303 $setSection[$fieldname] = $field;
304 $this->mFlatFields[$fieldname] = $field;
305 }
306
307 $this->mFieldTree = $loadedDescriptor;
308 }
309
310 /**
311 * Set format in which to display the form
312 *
313 * @param string $format The name of the format to use, must be one of
314 * $this->availableDisplayFormats
315 *
316 * @throws MWException
317 * @since 1.20
318 * @return HTMLForm $this for chaining calls (since 1.20)
319 */
320 public function setDisplayFormat( $format ) {
321 if (
322 in_array( $format, $this->availableSubclassDisplayFormats ) ||
323 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats )
324 ) {
325 throw new MWException( 'Cannot change display format after creation, ' .
326 'use HTMLForm::factory() instead' );
327 }
328
329 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
330 throw new MWException( 'Display format must be one of ' .
331 print_r( $this->availableDisplayFormats, true ) );
332 }
333
334 // Evil hack for mobile :(
335 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
336 $format = 'div';
337 }
338
339 $this->displayFormat = $format;
340
341 return $this;
342 }
343
344 /**
345 * Getter for displayFormat
346 * @since 1.20
347 * @return string
348 */
349 public function getDisplayFormat() {
350 return $this->displayFormat;
351 }
352
353 /**
354 * Test if displayFormat is 'vform'
355 * @since 1.22
356 * @deprecated since 1.25
357 * @return bool
358 */
359 public function isVForm() {
360 return false;
361 }
362
363 /**
364 * Get the HTMLFormField subclass for this descriptor.
365 *
366 * The descriptor can be passed either 'class' which is the name of
367 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
368 * This makes sure the 'class' is always set, and also is returned by
369 * this function for ease.
370 *
371 * @since 1.23
372 *
373 * @param string $fieldname Name of the field
374 * @param array $descriptor Input Descriptor, as described above
375 *
376 * @throws MWException
377 * @return string Name of a HTMLFormField subclass
378 */
379 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
380 if ( isset( $descriptor['class'] ) ) {
381 $class = $descriptor['class'];
382 } elseif ( isset( $descriptor['type'] ) ) {
383 $class = static::$typeMappings[$descriptor['type']];
384 $descriptor['class'] = $class;
385 } else {
386 $class = null;
387 }
388
389 if ( !$class ) {
390 throw new MWException( "Descriptor with no class for $fieldname: "
391 . print_r( $descriptor, true ) );
392 }
393
394 return $class;
395 }
396
397 /**
398 * Initialise a new Object for the field
399 *
400 * @param string $fieldname Name of the field
401 * @param array $descriptor Input Descriptor, as described above
402 * @param HTMLForm|null $parent Parent instance of HTMLForm
403 *
404 * @throws MWException
405 * @return HTMLFormField Instance of a subclass of HTMLFormField
406 */
407 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent = null ) {
408 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
409
410 $descriptor['fieldname'] = $fieldname;
411 if ( $parent ) {
412 $descriptor['parent'] = $parent;
413 }
414
415 # @todo This will throw a fatal error whenever someone try to use
416 # 'class' to feed a CSS class instead of 'cssclass'. Would be
417 # great to avoid the fatal error and show a nice error.
418 $obj = new $class( $descriptor );
419
420 return $obj;
421 }
422
423 /**
424 * Prepare form for submission.
425 *
426 * @attention When doing method chaining, that should be the very last
427 * method call before displayForm().
428 *
429 * @throws MWException
430 * @return HTMLForm $this for chaining calls (since 1.20)
431 */
432 function prepareForm() {
433 # Check if we have the info we need
434 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
435 throw new MWException( "You must call setTitle() on an HTMLForm" );
436 }
437
438 # Load data from the request.
439 $this->loadData();
440
441 return $this;
442 }
443
444 /**
445 * Try submitting, with edit token check first
446 * @return Status|bool
447 */
448 function tryAuthorizedSubmit() {
449 $result = false;
450
451 $submit = false;
452 if ( $this->getMethod() != 'post' ) {
453 $submit = true; // no session check needed
454 } elseif ( $this->getRequest()->wasPosted() ) {
455 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
456 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
457 // Session tokens for logged-out users have no security value.
458 // However, if the user gave one, check it in order to give a nice
459 // "session expired" error instead of "permission denied" or such.
460 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
461 } else {
462 $submit = true;
463 }
464 }
465
466 if ( $submit ) {
467 $this->mWasSubmitted = true;
468 $result = $this->trySubmit();
469 }
470
471 return $result;
472 }
473
474 /**
475 * The here's-one-I-made-earlier option: do the submission if
476 * posted, or display the form with or without funky validation
477 * errors
478 * @return bool|Status Whether submission was successful.
479 */
480 function show() {
481 $this->prepareForm();
482
483 $result = $this->tryAuthorizedSubmit();
484 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
485 return $result;
486 }
487
488 $this->displayForm( $result );
489
490 return false;
491 }
492
493 /**
494 * Validate all the fields, and call the submission callback
495 * function if everything is kosher.
496 * @throws MWException
497 * @return bool|string|array|Status
498 * - Bool true or a good Status object indicates success,
499 * - Bool false indicates no submission was attempted,
500 * - Anything else indicates failure. The value may be a fatal Status
501 * object, an HTML string, or an array of arrays (message keys and
502 * params) or strings (message keys)
503 */
504 function trySubmit() {
505 $this->mWasSubmitted = true;
506
507 # Check for cancelled submission
508 foreach ( $this->mFlatFields as $fieldname => $field ) {
509 if ( !empty( $field->mParams['nodata'] ) ) {
510 continue;
511 }
512 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
513 $this->mWasSubmitted = false;
514 return false;
515 }
516 }
517
518 # Check for validation
519 foreach ( $this->mFlatFields as $fieldname => $field ) {
520 if ( !empty( $field->mParams['nodata'] ) ) {
521 continue;
522 }
523 if ( $field->isHidden( $this->mFieldData ) ) {
524 continue;
525 }
526 if ( $field->validate(
527 $this->mFieldData[$fieldname],
528 $this->mFieldData )
529 !== true
530 ) {
531 return isset( $this->mValidationErrorMessage )
532 ? $this->mValidationErrorMessage
533 : array( 'htmlform-invalid-input' );
534 }
535 }
536
537 $callback = $this->mSubmitCallback;
538 if ( !is_callable( $callback ) ) {
539 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
540 'setSubmitCallback() to set one.' );
541 }
542
543 $data = $this->filterDataForSubmit( $this->mFieldData );
544
545 $res = call_user_func( $callback, $data, $this );
546 if ( $res === false ) {
547 $this->mWasSubmitted = false;
548 }
549
550 return $res;
551 }
552
553 /**
554 * Test whether the form was considered to have been submitted or not, i.e.
555 * whether the last call to tryAuthorizedSubmit or trySubmit returned
556 * non-false.
557 *
558 * This will return false until HTMLForm::tryAuthorizedSubmit or
559 * HTMLForm::trySubmit is called.
560 *
561 * @since 1.23
562 * @return bool
563 */
564 function wasSubmitted() {
565 return $this->mWasSubmitted;
566 }
567
568 /**
569 * Set a callback to a function to do something with the form
570 * once it's been successfully validated.
571 *
572 * @param callable $cb The function will be passed the output from
573 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
574 * return as documented for HTMLForm::trySubmit
575 *
576 * @return HTMLForm $this for chaining calls (since 1.20)
577 */
578 function setSubmitCallback( $cb ) {
579 $this->mSubmitCallback = $cb;
580
581 return $this;
582 }
583
584 /**
585 * Set a message to display on a validation error.
586 *
587 * @param string|array $msg String or Array of valid inputs to wfMessage()
588 * (so each entry can be either a String or Array)
589 *
590 * @return HTMLForm $this for chaining calls (since 1.20)
591 */
592 function setValidationErrorMessage( $msg ) {
593 $this->mValidationErrorMessage = $msg;
594
595 return $this;
596 }
597
598 /**
599 * Set the introductory message, overwriting any existing message.
600 *
601 * @param string $msg Complete text of message to display
602 *
603 * @return HTMLForm $this for chaining calls (since 1.20)
604 */
605 function setIntro( $msg ) {
606 $this->setPreText( $msg );
607
608 return $this;
609 }
610
611 /**
612 * Set the introductory message, overwriting any existing message.
613 * @since 1.19
614 *
615 * @param string $msg Complete text of message to display
616 *
617 * @return HTMLForm $this for chaining calls (since 1.20)
618 */
619 function setPreText( $msg ) {
620 $this->mPre = $msg;
621
622 return $this;
623 }
624
625 /**
626 * Add introductory text.
627 *
628 * @param string $msg Complete text of message to display
629 *
630 * @return HTMLForm $this for chaining calls (since 1.20)
631 */
632 function addPreText( $msg ) {
633 $this->mPre .= $msg;
634
635 return $this;
636 }
637
638 /**
639 * Add header text, inside the form.
640 *
641 * @param string $msg Complete text of message to display
642 * @param string|null $section The section to add the header to
643 *
644 * @return HTMLForm $this for chaining calls (since 1.20)
645 */
646 function addHeaderText( $msg, $section = null ) {
647 if ( is_null( $section ) ) {
648 $this->mHeader .= $msg;
649 } else {
650 if ( !isset( $this->mSectionHeaders[$section] ) ) {
651 $this->mSectionHeaders[$section] = '';
652 }
653 $this->mSectionHeaders[$section] .= $msg;
654 }
655
656 return $this;
657 }
658
659 /**
660 * Set header text, inside the form.
661 * @since 1.19
662 *
663 * @param string $msg Complete text of message to display
664 * @param string|null $section The section to add the header to
665 *
666 * @return HTMLForm $this for chaining calls (since 1.20)
667 */
668 function setHeaderText( $msg, $section = null ) {
669 if ( is_null( $section ) ) {
670 $this->mHeader = $msg;
671 } else {
672 $this->mSectionHeaders[$section] = $msg;
673 }
674
675 return $this;
676 }
677
678 /**
679 * Add footer text, inside the form.
680 *
681 * @param string $msg Complete text of message to display
682 * @param string|null $section The section to add the footer text to
683 *
684 * @return HTMLForm $this for chaining calls (since 1.20)
685 */
686 function addFooterText( $msg, $section = null ) {
687 if ( is_null( $section ) ) {
688 $this->mFooter .= $msg;
689 } else {
690 if ( !isset( $this->mSectionFooters[$section] ) ) {
691 $this->mSectionFooters[$section] = '';
692 }
693 $this->mSectionFooters[$section] .= $msg;
694 }
695
696 return $this;
697 }
698
699 /**
700 * Set footer text, inside the form.
701 * @since 1.19
702 *
703 * @param string $msg Complete text of message to display
704 * @param string|null $section The section to add the footer text to
705 *
706 * @return HTMLForm $this for chaining calls (since 1.20)
707 */
708 function setFooterText( $msg, $section = null ) {
709 if ( is_null( $section ) ) {
710 $this->mFooter = $msg;
711 } else {
712 $this->mSectionFooters[$section] = $msg;
713 }
714
715 return $this;
716 }
717
718 /**
719 * Add text to the end of the display.
720 *
721 * @param string $msg Complete text of message to display
722 *
723 * @return HTMLForm $this for chaining calls (since 1.20)
724 */
725 function addPostText( $msg ) {
726 $this->mPost .= $msg;
727
728 return $this;
729 }
730
731 /**
732 * Set text at the end of the display.
733 *
734 * @param string $msg Complete text of message to display
735 *
736 * @return HTMLForm $this for chaining calls (since 1.20)
737 */
738 function setPostText( $msg ) {
739 $this->mPost = $msg;
740
741 return $this;
742 }
743
744 /**
745 * Add a hidden field to the output
746 *
747 * @param string $name Field name. This will be used exactly as entered
748 * @param string $value Field value
749 * @param array $attribs
750 *
751 * @return HTMLForm $this for chaining calls (since 1.20)
752 */
753 public function addHiddenField( $name, $value, $attribs = array() ) {
754 $attribs += array( 'name' => $name );
755 $this->mHiddenFields[] = array( $value, $attribs );
756
757 return $this;
758 }
759
760 /**
761 * Add an array of hidden fields to the output
762 *
763 * @since 1.22
764 *
765 * @param array $fields Associative array of fields to add;
766 * mapping names to their values
767 *
768 * @return HTMLForm $this for chaining calls
769 */
770 public function addHiddenFields( array $fields ) {
771 foreach ( $fields as $name => $value ) {
772 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
773 }
774
775 return $this;
776 }
777
778 /**
779 * Add a button to the form
780 *
781 * @param string $name Field name.
782 * @param string $value Field value
783 * @param string $id DOM id for the button (default: null)
784 * @param array $attribs
785 *
786 * @return HTMLForm $this for chaining calls (since 1.20)
787 */
788 public function addButton( $name, $value, $id = null, $attribs = null ) {
789 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
790
791 return $this;
792 }
793
794 /**
795 * Set the salt for the edit token.
796 *
797 * Only useful when the method is "post".
798 *
799 * @since 1.24
800 * @param string|array $salt Salt to use
801 * @return HTMLForm $this For chaining calls
802 */
803 public function setTokenSalt( $salt ) {
804 $this->mTokenSalt = $salt;
805
806 return $this;
807 }
808
809 /**
810 * Display the form (sending to the context's OutputPage object), with an
811 * appropriate error message or stack of messages, and any validation errors, etc.
812 *
813 * @attention You should call prepareForm() before calling this function.
814 * Moreover, when doing method chaining this should be the very last method
815 * call just after prepareForm().
816 *
817 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
818 *
819 * @return void Nothing, should be last call
820 */
821 function displayForm( $submitResult ) {
822 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
823 }
824
825 /**
826 * Returns the raw HTML generated by the form
827 *
828 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
829 *
830 * @return string
831 */
832 function getHTML( $submitResult ) {
833 # For good measure (it is the default)
834 $this->getOutput()->preventClickjacking();
835 $this->getOutput()->addModules( 'mediawiki.htmlform' );
836
837 $html = ''
838 . $this->getErrors( $submitResult )
839 . $this->mHeader
840 . $this->getBody()
841 . $this->getHiddenFields()
842 . $this->getButtons()
843 . $this->mFooter;
844
845 $html = $this->wrapForm( $html );
846
847 return '' . $this->mPre . $html . $this->mPost;
848 }
849
850 /**
851 * Get HTML attributes for the `<form>` tag.
852 * @return array
853 */
854 protected function getFormAttributes() {
855 # Use multipart/form-data
856 $encType = $this->mUseMultipart
857 ? 'multipart/form-data'
858 : 'application/x-www-form-urlencoded';
859 # Attributes
860 $attribs = array(
861 'action' => $this->getAction(),
862 'method' => $this->getMethod(),
863 'class' => array( 'visualClear' ),
864 'enctype' => $encType,
865 );
866 if ( !empty( $this->mId ) ) {
867 $attribs['id'] = $this->mId;
868 }
869 return $attribs;
870 }
871
872 /**
873 * Wrap the form innards in an actual "<form>" element
874 *
875 * @param string $html HTML contents to wrap.
876 *
877 * @return string Wrapped HTML.
878 */
879 function wrapForm( $html ) {
880 # Include a <fieldset> wrapper for style, if requested.
881 if ( $this->mWrapperLegend !== false ) {
882 $html = Xml::fieldset( $this->mWrapperLegend, $html );
883 }
884
885 return Html::rawElement( 'form', $this->getFormAttributes(), $html );
886 }
887
888 /**
889 * Get the hidden fields that should go inside the form.
890 * @return string HTML.
891 */
892 function getHiddenFields() {
893 $html = '';
894 if ( $this->getMethod() == 'post' ) {
895 $html .= Html::hidden(
896 'wpEditToken',
897 $this->getUser()->getEditToken( $this->mTokenSalt ),
898 array( 'id' => 'wpEditToken' )
899 ) . "\n";
900 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
901 }
902
903 $articlePath = $this->getConfig()->get( 'ArticlePath' );
904 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
905 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
906 }
907
908 foreach ( $this->mHiddenFields as $data ) {
909 list( $value, $attribs ) = $data;
910 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
911 }
912
913 return $html;
914 }
915
916 /**
917 * Get the submit and (potentially) reset buttons.
918 * @return string HTML.
919 */
920 function getButtons() {
921 $buttons = '';
922 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
923
924 if ( $this->mShowSubmit ) {
925 $attribs = array();
926
927 if ( isset( $this->mSubmitID ) ) {
928 $attribs['id'] = $this->mSubmitID;
929 }
930
931 if ( isset( $this->mSubmitName ) ) {
932 $attribs['name'] = $this->mSubmitName;
933 }
934
935 if ( isset( $this->mSubmitTooltip ) ) {
936 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
937 }
938
939 $attribs['class'] = array( 'mw-htmlform-submit' );
940
941 if ( $useMediaWikiUIEverywhere ) {
942 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass );
943 }
944
945 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
946 }
947
948 if ( $this->mShowReset ) {
949 $buttons .= Html::element(
950 'input',
951 array(
952 'type' => 'reset',
953 'value' => $this->msg( 'htmlform-reset' )->text(),
954 'class' => ( $useMediaWikiUIEverywhere ? 'mw-ui-button' : null ),
955 )
956 ) . "\n";
957 }
958
959 foreach ( $this->mButtons as $button ) {
960 $attrs = array(
961 'type' => 'submit',
962 'name' => $button['name'],
963 'value' => $button['value']
964 );
965
966 if ( $button['attribs'] ) {
967 $attrs += $button['attribs'];
968 }
969
970 if ( isset( $button['id'] ) ) {
971 $attrs['id'] = $button['id'];
972 }
973
974 if ( $useMediaWikiUIEverywhere ) {
975 $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : array();
976 $attrs['class'][] = 'mw-ui-button';
977 }
978
979 $buttons .= Html::element( 'input', $attrs ) . "\n";
980 }
981
982 $html = Html::rawElement( 'span',
983 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
984
985 return $html;
986 }
987
988 /**
989 * Get the whole body of the form.
990 * @return string
991 */
992 function getBody() {
993 return $this->displaySection( $this->mFieldTree, $this->mTableId );
994 }
995
996 /**
997 * Format and display an error message stack.
998 *
999 * @param string|array|Status $errors
1000 *
1001 * @return string
1002 */
1003 function getErrors( $errors ) {
1004 if ( $errors instanceof Status ) {
1005 if ( $errors->isOK() ) {
1006 $errorstr = '';
1007 } else {
1008 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1009 }
1010 } elseif ( is_array( $errors ) ) {
1011 $errorstr = $this->formatErrors( $errors );
1012 } else {
1013 $errorstr = $errors;
1014 }
1015
1016 return $errorstr
1017 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1018 : '';
1019 }
1020
1021 /**
1022 * Format a stack of error messages into a single HTML string
1023 *
1024 * @param array $errors Array of message keys/values
1025 *
1026 * @return string HTML, a "<ul>" list of errors
1027 */
1028 public function formatErrors( $errors ) {
1029 $errorstr = '';
1030
1031 foreach ( $errors as $error ) {
1032 if ( is_array( $error ) ) {
1033 $msg = array_shift( $error );
1034 } else {
1035 $msg = $error;
1036 $error = array();
1037 }
1038
1039 $errorstr .= Html::rawElement(
1040 'li',
1041 array(),
1042 $this->msg( $msg, $error )->parse()
1043 );
1044 }
1045
1046 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1047
1048 return $errorstr;
1049 }
1050
1051 /**
1052 * Set the text for the submit button
1053 *
1054 * @param string $t Plaintext
1055 *
1056 * @return HTMLForm $this for chaining calls (since 1.20)
1057 */
1058 function setSubmitText( $t ) {
1059 $this->mSubmitText = $t;
1060
1061 return $this;
1062 }
1063
1064 /**
1065 * Identify that the submit button in the form has a destructive action
1066 * @since 1.24
1067 */
1068 public function setSubmitDestructive() {
1069 $this->mSubmitModifierClass = 'mw-ui-destructive';
1070 }
1071
1072 /**
1073 * Identify that the submit button in the form has a progressive action
1074 * @since 1.25
1075 */
1076 public function setSubmitProgressive() {
1077 $this->mSubmitModifierClass = 'mw-ui-progressive';
1078 }
1079
1080 /**
1081 * Set the text for the submit button to a message
1082 * @since 1.19
1083 *
1084 * @param string|Message $msg Message key or Message object
1085 *
1086 * @return HTMLForm $this for chaining calls (since 1.20)
1087 */
1088 public function setSubmitTextMsg( $msg ) {
1089 if ( !$msg instanceof Message ) {
1090 $msg = $this->msg( $msg );
1091 }
1092 $this->setSubmitText( $msg->text() );
1093
1094 return $this;
1095 }
1096
1097 /**
1098 * Get the text for the submit button, either customised or a default.
1099 * @return string
1100 */
1101 function getSubmitText() {
1102 return $this->mSubmitText
1103 ? $this->mSubmitText
1104 : $this->msg( 'htmlform-submit' )->text();
1105 }
1106
1107 /**
1108 * @param string $name Submit button name
1109 *
1110 * @return HTMLForm $this for chaining calls (since 1.20)
1111 */
1112 public function setSubmitName( $name ) {
1113 $this->mSubmitName = $name;
1114
1115 return $this;
1116 }
1117
1118 /**
1119 * @param string $name Tooltip for the submit button
1120 *
1121 * @return HTMLForm $this for chaining calls (since 1.20)
1122 */
1123 public function setSubmitTooltip( $name ) {
1124 $this->mSubmitTooltip = $name;
1125
1126 return $this;
1127 }
1128
1129 /**
1130 * Set the id for the submit button.
1131 *
1132 * @param string $t
1133 *
1134 * @todo FIXME: Integrity of $t is *not* validated
1135 * @return HTMLForm $this for chaining calls (since 1.20)
1136 */
1137 function setSubmitID( $t ) {
1138 $this->mSubmitID = $t;
1139
1140 return $this;
1141 }
1142
1143 /**
1144 * Stop a default submit button being shown for this form. This implies that an
1145 * alternate submit method must be provided manually.
1146 *
1147 * @since 1.22
1148 *
1149 * @param bool $suppressSubmit Set to false to re-enable the button again
1150 *
1151 * @return HTMLForm $this for chaining calls
1152 */
1153 function suppressDefaultSubmit( $suppressSubmit = true ) {
1154 $this->mShowSubmit = !$suppressSubmit;
1155
1156 return $this;
1157 }
1158
1159 /**
1160 * Set the id of the \<table\> or outermost \<div\> element.
1161 *
1162 * @since 1.22
1163 *
1164 * @param string $id New value of the id attribute, or "" to remove
1165 *
1166 * @return HTMLForm $this for chaining calls
1167 */
1168 public function setTableId( $id ) {
1169 $this->mTableId = $id;
1170
1171 return $this;
1172 }
1173
1174 /**
1175 * @param string $id DOM id for the form
1176 *
1177 * @return HTMLForm $this for chaining calls (since 1.20)
1178 */
1179 public function setId( $id ) {
1180 $this->mId = $id;
1181
1182 return $this;
1183 }
1184
1185 /**
1186 * Prompt the whole form to be wrapped in a "<fieldset>", with
1187 * this text as its "<legend>" element.
1188 *
1189 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1190 * false for no <legend>
1191 * Will be escaped
1192 *
1193 * @return HTMLForm $this for chaining calls (since 1.20)
1194 */
1195 public function setWrapperLegend( $legend ) {
1196 $this->mWrapperLegend = $legend;
1197
1198 return $this;
1199 }
1200
1201 /**
1202 * Prompt the whole form to be wrapped in a "<fieldset>", with
1203 * this message as its "<legend>" element.
1204 * @since 1.19
1205 *
1206 * @param string|Message $msg Message key or Message object
1207 *
1208 * @return HTMLForm $this for chaining calls (since 1.20)
1209 */
1210 public function setWrapperLegendMsg( $msg ) {
1211 if ( !$msg instanceof Message ) {
1212 $msg = $this->msg( $msg );
1213 }
1214 $this->setWrapperLegend( $msg->text() );
1215
1216 return $this;
1217 }
1218
1219 /**
1220 * Set the prefix for various default messages
1221 * @todo Currently only used for the "<fieldset>" legend on forms
1222 * with multiple sections; should be used elsewhere?
1223 *
1224 * @param string $p
1225 *
1226 * @return HTMLForm $this for chaining calls (since 1.20)
1227 */
1228 function setMessagePrefix( $p ) {
1229 $this->mMessagePrefix = $p;
1230
1231 return $this;
1232 }
1233
1234 /**
1235 * Set the title for form submission
1236 *
1237 * @param Title $t Title of page the form is on/should be posted to
1238 *
1239 * @return HTMLForm $this for chaining calls (since 1.20)
1240 */
1241 function setTitle( $t ) {
1242 $this->mTitle = $t;
1243
1244 return $this;
1245 }
1246
1247 /**
1248 * Get the title
1249 * @return Title
1250 */
1251 function getTitle() {
1252 return $this->mTitle === false
1253 ? $this->getContext()->getTitle()
1254 : $this->mTitle;
1255 }
1256
1257 /**
1258 * Set the method used to submit the form
1259 *
1260 * @param string $method
1261 *
1262 * @return HTMLForm $this for chaining calls (since 1.20)
1263 */
1264 public function setMethod( $method = 'post' ) {
1265 $this->mMethod = $method;
1266
1267 return $this;
1268 }
1269
1270 public function getMethod() {
1271 return $this->mMethod;
1272 }
1273
1274 /**
1275 * @todo Document
1276 *
1277 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1278 * objects).
1279 * @param string $sectionName ID attribute of the "<table>" tag for this
1280 * section, ignored if empty.
1281 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1282 * each subsection, ignored if empty.
1283 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1284 *
1285 * @return string
1286 */
1287 public function displaySection( $fields,
1288 $sectionName = '',
1289 $fieldsetIDPrefix = '',
1290 &$hasUserVisibleFields = false ) {
1291 $displayFormat = $this->getDisplayFormat();
1292
1293 $html = '';
1294 $subsectionHtml = '';
1295 $hasLabel = false;
1296
1297 // Conveniently, PHP method names are case-insensitive.
1298 $getFieldHtmlMethod = $displayFormat == 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1299
1300 foreach ( $fields as $key => $value ) {
1301 if ( $value instanceof HTMLFormField ) {
1302 $v = empty( $value->mParams['nodata'] )
1303 ? $this->mFieldData[$key]
1304 : $value->getDefault();
1305 $html .= $value->$getFieldHtmlMethod( $v );
1306
1307 $labelValue = trim( $value->getLabel() );
1308 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1309 $hasLabel = true;
1310 }
1311
1312 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1313 get_class( $value ) !== 'HTMLApiField'
1314 ) {
1315 $hasUserVisibleFields = true;
1316 }
1317 } elseif ( is_array( $value ) ) {
1318 $subsectionHasVisibleFields = false;
1319 $section =
1320 $this->displaySection( $value,
1321 "mw-htmlform-$key",
1322 "$fieldsetIDPrefix$key-",
1323 $subsectionHasVisibleFields );
1324 $legend = null;
1325
1326 if ( $subsectionHasVisibleFields === true ) {
1327 // Display the section with various niceties.
1328 $hasUserVisibleFields = true;
1329
1330 $legend = $this->getLegend( $key );
1331
1332 if ( isset( $this->mSectionHeaders[$key] ) ) {
1333 $section = $this->mSectionHeaders[$key] . $section;
1334 }
1335 if ( isset( $this->mSectionFooters[$key] ) ) {
1336 $section .= $this->mSectionFooters[$key];
1337 }
1338
1339 $attributes = array();
1340 if ( $fieldsetIDPrefix ) {
1341 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1342 }
1343 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1344 } else {
1345 // Just return the inputs, nothing fancy.
1346 $subsectionHtml .= $section;
1347 }
1348 }
1349 }
1350
1351 if ( $displayFormat !== 'raw' ) {
1352 $classes = array();
1353
1354 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1355 $classes[] = 'mw-htmlform-nolabel';
1356 }
1357
1358 $attribs = array(
1359 'class' => implode( ' ', $classes ),
1360 );
1361
1362 if ( $sectionName ) {
1363 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1364 }
1365
1366 if ( $displayFormat === 'table' ) {
1367 $html = Html::rawElement( 'table',
1368 $attribs,
1369 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1370 } elseif ( $displayFormat === 'inline' ) {
1371 $html = Html::rawElement( 'span', $attribs, "\n$html\n" );
1372 } else {
1373 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1374 }
1375 }
1376
1377 if ( $this->mSubSectionBeforeFields ) {
1378 return $subsectionHtml . "\n" . $html;
1379 } else {
1380 return $html . "\n" . $subsectionHtml;
1381 }
1382 }
1383
1384 /**
1385 * Construct the form fields from the Descriptor array
1386 */
1387 function loadData() {
1388 $fieldData = array();
1389
1390 foreach ( $this->mFlatFields as $fieldname => $field ) {
1391 if ( !empty( $field->mParams['nodata'] ) ) {
1392 continue;
1393 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1394 $fieldData[$fieldname] = $field->getDefault();
1395 } else {
1396 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1397 }
1398 }
1399
1400 # Filter data.
1401 foreach ( $fieldData as $name => &$value ) {
1402 $field = $this->mFlatFields[$name];
1403 $value = $field->filter( $value, $this->mFlatFields );
1404 }
1405
1406 $this->mFieldData = $fieldData;
1407 }
1408
1409 /**
1410 * Stop a reset button being shown for this form
1411 *
1412 * @param bool $suppressReset Set to false to re-enable the button again
1413 *
1414 * @return HTMLForm $this for chaining calls (since 1.20)
1415 */
1416 function suppressReset( $suppressReset = true ) {
1417 $this->mShowReset = !$suppressReset;
1418
1419 return $this;
1420 }
1421
1422 /**
1423 * Overload this if you want to apply special filtration routines
1424 * to the form as a whole, after it's submitted but before it's
1425 * processed.
1426 *
1427 * @param array $data
1428 *
1429 * @return array
1430 */
1431 function filterDataForSubmit( $data ) {
1432 return $data;
1433 }
1434
1435 /**
1436 * Get a string to go in the "<legend>" of a section fieldset.
1437 * Override this if you want something more complicated.
1438 *
1439 * @param string $key
1440 *
1441 * @return string
1442 */
1443 public function getLegend( $key ) {
1444 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1445 }
1446
1447 /**
1448 * Set the value for the action attribute of the form.
1449 * When set to false (which is the default state), the set title is used.
1450 *
1451 * @since 1.19
1452 *
1453 * @param string|bool $action
1454 *
1455 * @return HTMLForm $this for chaining calls (since 1.20)
1456 */
1457 public function setAction( $action ) {
1458 $this->mAction = $action;
1459
1460 return $this;
1461 }
1462
1463 /**
1464 * Get the value for the action attribute of the form.
1465 *
1466 * @since 1.22
1467 *
1468 * @return string
1469 */
1470 public function getAction() {
1471 // If an action is alredy provided, return it
1472 if ( $this->mAction !== false ) {
1473 return $this->mAction;
1474 }
1475
1476 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1477 // Check whether we are in GET mode and the ArticlePath contains a "?"
1478 // meaning that getLocalURL() would return something like "index.php?title=...".
1479 // As browser remove the query string before submitting GET forms,
1480 // it means that the title would be lost. In such case use wfScript() instead
1481 // and put title in an hidden field (see getHiddenFields()).
1482 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1483 return wfScript();
1484 }
1485
1486 return $this->getTitle()->getLocalURL();
1487 }
1488 }