Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / htmlform / HTMLForm.php
blob908fdf27fb4e5ba7afa3211c58e43d71b7d75ea3
1 <?php
3 /**
4 * HTML form generation and submission handling.
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.
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.
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
21 * @file
24 /**
25 * Object handling generic submission, CSRF protection, layout and
26 * other logic for UI forms. in a reusable manner.
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.
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.
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
42 * The constructor input is an associative array of $fieldname => $info,
43 * where $info is an Associative Array with any of the following:
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.
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 :(
99 * @todo Document 'section' / 'subsection' stuff
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',
134 public $mFieldData;
136 protected $mMessagePrefix;
138 /** @var HTMLFormField[] */
139 protected $mFlatFields;
141 protected $mFieldTree;
142 protected $mShowReset = false;
143 protected $mShowSubmit = true;
144 protected $mSubmitModifierClass = 'mw-ui-constructive';
146 protected $mSubmitCallback;
147 protected $mValidationErrorMessage;
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 = '';
158 protected $mSubmitID;
159 protected $mSubmitName;
160 protected $mSubmitText;
161 protected $mSubmitTooltip;
163 protected $mTitle;
164 protected $mMethod = 'post';
165 protected $mWasSubmitted = false;
168 * Form action URL. false means we will use the URL to set Title
169 * @since 1.19
170 * @var bool|string
172 protected $mAction = false;
174 protected $mUseMultipart = false;
175 protected $mHiddenFields = array();
176 protected $mButtons = array();
178 protected $mWrapperLegend = false;
181 * Salt for the edit token.
182 * @var string|array
184 protected $mTokenSalt = '';
187 * If true, sections that contain both fields and subsections will
188 * render their subsections before their fields.
190 * Subclasses may set this to false to render subsections after fields
191 * instead.
193 protected $mSubSectionBeforeFields = true;
196 * Format in which to display form. For viable options,
197 * @see $availableDisplayFormats
198 * @var string
200 protected $displayFormat = 'table';
203 * Available formats in which to display the form
204 * @var array
206 protected $availableDisplayFormats = array(
207 'table',
208 'div',
209 'raw',
213 * Available formats in which to display the form
214 * @var array
216 protected $availableSubclassDisplayFormats = array(
217 'vform',
221 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
223 * @throws MWException When the display format requested is not known
224 * @param string $displayFormat
225 * @param mixed $arguments... Additional arguments to pass to the constructor.
226 * @return HTMLForm
228 public static function factory( $displayFormat/*, $arguments...*/ ) {
229 $arguments = func_get_args();
230 array_shift( $arguments );
232 switch ( $displayFormat ) {
233 case 'vform':
234 $reflector = new ReflectionClass( 'VFormHTMLForm' );
235 return $reflector->newInstanceArgs( $arguments );
236 default:
237 $reflector = new ReflectionClass( 'HTMLForm' );
238 $form = $reflector->newInstanceArgs( $arguments );
239 $form->setDisplayFormat( $displayFormat );
240 return $form;
245 * Build a new HTMLForm from an array of field attributes
247 * @param array $descriptor Array of Field constructs, as described above
248 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
249 * Obviates the need to call $form->setTitle()
250 * @param string $messagePrefix A prefix to go in front of default messages
252 public function __construct( $descriptor, /*IContextSource*/ $context = null,
253 $messagePrefix = ''
255 if ( $context instanceof IContextSource ) {
256 $this->setContext( $context );
257 $this->mTitle = false; // We don't need them to set a title
258 $this->mMessagePrefix = $messagePrefix;
259 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
260 $this->mMessagePrefix = $messagePrefix;
261 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
262 // B/C since 1.18
263 // it's actually $messagePrefix
264 $this->mMessagePrefix = $context;
267 // Evil hack for mobile :(
268 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $this->displayFormat === 'table' ) {
269 $this->displayFormat = 'div';
272 // Expand out into a tree.
273 $loadedDescriptor = array();
274 $this->mFlatFields = array();
276 foreach ( $descriptor as $fieldname => $info ) {
277 $section = isset( $info['section'] )
278 ? $info['section']
279 : '';
281 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
282 $this->mUseMultipart = true;
285 $field = static::loadInputFromParameters( $fieldname, $info, $this );
287 $setSection =& $loadedDescriptor;
288 if ( $section ) {
289 $sectionParts = explode( '/', $section );
291 while ( count( $sectionParts ) ) {
292 $newName = array_shift( $sectionParts );
294 if ( !isset( $setSection[$newName] ) ) {
295 $setSection[$newName] = array();
298 $setSection =& $setSection[$newName];
302 $setSection[$fieldname] = $field;
303 $this->mFlatFields[$fieldname] = $field;
306 $this->mFieldTree = $loadedDescriptor;
310 * Set format in which to display the form
312 * @param string $format The name of the format to use, must be one of
313 * $this->availableDisplayFormats
315 * @throws MWException
316 * @since 1.20
317 * @return HTMLForm $this for chaining calls (since 1.20)
319 public function setDisplayFormat( $format ) {
320 if (
321 in_array( $format, $this->availableSubclassDisplayFormats ) ||
322 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats )
324 throw new MWException( 'Cannot change display format after creation, ' .
325 'use HTMLForm::factory() instead' );
328 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
329 throw new MWException( 'Display format must be one of ' .
330 print_r( $this->availableDisplayFormats, true ) );
333 // Evil hack for mobile :(
334 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
335 $format = 'div';
338 $this->displayFormat = $format;
340 return $this;
344 * Getter for displayFormat
345 * @since 1.20
346 * @return string
348 public function getDisplayFormat() {
349 return $this->displayFormat;
353 * Test if displayFormat is 'vform'
354 * @since 1.22
355 * @deprecated since 1.25
356 * @return bool
358 public function isVForm() {
359 return false;
363 * Get the HTMLFormField subclass for this descriptor.
365 * The descriptor can be passed either 'class' which is the name of
366 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
367 * This makes sure the 'class' is always set, and also is returned by
368 * this function for ease.
370 * @since 1.23
372 * @param string $fieldname Name of the field
373 * @param array $descriptor Input Descriptor, as described above
375 * @throws MWException
376 * @return string Name of a HTMLFormField subclass
378 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
379 if ( isset( $descriptor['class'] ) ) {
380 $class = $descriptor['class'];
381 } elseif ( isset( $descriptor['type'] ) ) {
382 $class = static::$typeMappings[$descriptor['type']];
383 $descriptor['class'] = $class;
384 } else {
385 $class = null;
388 if ( !$class ) {
389 throw new MWException( "Descriptor with no class for $fieldname: "
390 . print_r( $descriptor, true ) );
393 return $class;
397 * Initialise a new Object for the field
399 * @param string $fieldname Name of the field
400 * @param array $descriptor Input Descriptor, as described above
401 * @param HTMLForm|null $parent Parent instance of HTMLForm
403 * @throws MWException
404 * @return HTMLFormField Instance of a subclass of HTMLFormField
406 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent = null ) {
407 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
409 $descriptor['fieldname'] = $fieldname;
410 if ( $parent ) {
411 $descriptor['parent'] = $parent;
414 # @todo This will throw a fatal error whenever someone try to use
415 # 'class' to feed a CSS class instead of 'cssclass'. Would be
416 # great to avoid the fatal error and show a nice error.
417 $obj = new $class( $descriptor );
419 return $obj;
423 * Prepare form for submission.
425 * @attention When doing method chaining, that should be the very last
426 * method call before displayForm().
428 * @throws MWException
429 * @return HTMLForm $this for chaining calls (since 1.20)
431 function prepareForm() {
432 # Check if we have the info we need
433 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
434 throw new MWException( "You must call setTitle() on an HTMLForm" );
437 # Load data from the request.
438 $this->loadData();
440 return $this;
444 * Try submitting, with edit token check first
445 * @return Status|bool
447 function tryAuthorizedSubmit() {
448 $result = false;
450 $submit = false;
451 if ( $this->getMethod() != 'post' ) {
452 $submit = true; // no session check needed
453 } elseif ( $this->getRequest()->wasPosted() ) {
454 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
455 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
456 // Session tokens for logged-out users have no security value.
457 // However, if the user gave one, check it in order to give a nice
458 // "session expired" error instead of "permission denied" or such.
459 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
460 } else {
461 $submit = true;
465 if ( $submit ) {
466 $this->mWasSubmitted = true;
467 $result = $this->trySubmit();
470 return $result;
474 * The here's-one-I-made-earlier option: do the submission if
475 * posted, or display the form with or without funky validation
476 * errors
477 * @return bool|Status Whether submission was successful.
479 function show() {
480 $this->prepareForm();
482 $result = $this->tryAuthorizedSubmit();
483 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
484 return $result;
487 $this->displayForm( $result );
489 return false;
493 * Validate all the fields, and call the submission callback
494 * function if everything is kosher.
495 * @throws MWException
496 * @return bool|string|array|Status
497 * - Bool true or a good Status object indicates success,
498 * - Bool false indicates no submission was attempted,
499 * - Anything else indicates failure. The value may be a fatal Status
500 * object, an HTML string, or an array of arrays (message keys and
501 * params) or strings (message keys)
503 function trySubmit() {
504 $this->mWasSubmitted = true;
506 # Check for cancelled submission
507 foreach ( $this->mFlatFields as $fieldname => $field ) {
508 if ( !empty( $field->mParams['nodata'] ) ) {
509 continue;
511 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
512 $this->mWasSubmitted = false;
513 return false;
517 # Check for validation
518 foreach ( $this->mFlatFields as $fieldname => $field ) {
519 if ( !empty( $field->mParams['nodata'] ) ) {
520 continue;
522 if ( $field->isHidden( $this->mFieldData ) ) {
523 continue;
525 if ( $field->validate(
526 $this->mFieldData[$fieldname],
527 $this->mFieldData )
528 !== true
530 return isset( $this->mValidationErrorMessage )
531 ? $this->mValidationErrorMessage
532 : array( 'htmlform-invalid-input' );
536 $callback = $this->mSubmitCallback;
537 if ( !is_callable( $callback ) ) {
538 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
539 'setSubmitCallback() to set one.' );
542 $data = $this->filterDataForSubmit( $this->mFieldData );
544 $res = call_user_func( $callback, $data, $this );
545 if ( $res === false ) {
546 $this->mWasSubmitted = false;
549 return $res;
553 * Test whether the form was considered to have been submitted or not, i.e.
554 * whether the last call to tryAuthorizedSubmit or trySubmit returned
555 * non-false.
557 * This will return false until HTMLForm::tryAuthorizedSubmit or
558 * HTMLForm::trySubmit is called.
560 * @since 1.23
561 * @return bool
563 function wasSubmitted() {
564 return $this->mWasSubmitted;
568 * Set a callback to a function to do something with the form
569 * once it's been successfully validated.
571 * @param callable $cb The function will be passed the output from
572 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
573 * return as documented for HTMLForm::trySubmit
575 * @return HTMLForm $this for chaining calls (since 1.20)
577 function setSubmitCallback( $cb ) {
578 $this->mSubmitCallback = $cb;
580 return $this;
584 * Set a message to display on a validation error.
586 * @param string|array $msg String or Array of valid inputs to wfMessage()
587 * (so each entry can be either a String or Array)
589 * @return HTMLForm $this for chaining calls (since 1.20)
591 function setValidationErrorMessage( $msg ) {
592 $this->mValidationErrorMessage = $msg;
594 return $this;
598 * Set the introductory message, overwriting any existing message.
600 * @param string $msg Complete text of message to display
602 * @return HTMLForm $this for chaining calls (since 1.20)
604 function setIntro( $msg ) {
605 $this->setPreText( $msg );
607 return $this;
611 * Set the introductory message, overwriting any existing message.
612 * @since 1.19
614 * @param string $msg Complete text of message to display
616 * @return HTMLForm $this for chaining calls (since 1.20)
618 function setPreText( $msg ) {
619 $this->mPre = $msg;
621 return $this;
625 * Add introductory text.
627 * @param string $msg Complete text of message to display
629 * @return HTMLForm $this for chaining calls (since 1.20)
631 function addPreText( $msg ) {
632 $this->mPre .= $msg;
634 return $this;
638 * Add header text, inside the form.
640 * @param string $msg Complete text of message to display
641 * @param string|null $section The section to add the header to
643 * @return HTMLForm $this for chaining calls (since 1.20)
645 function addHeaderText( $msg, $section = null ) {
646 if ( is_null( $section ) ) {
647 $this->mHeader .= $msg;
648 } else {
649 if ( !isset( $this->mSectionHeaders[$section] ) ) {
650 $this->mSectionHeaders[$section] = '';
652 $this->mSectionHeaders[$section] .= $msg;
655 return $this;
659 * Set header text, inside the form.
660 * @since 1.19
662 * @param string $msg Complete text of message to display
663 * @param string|null $section The section to add the header to
665 * @return HTMLForm $this for chaining calls (since 1.20)
667 function setHeaderText( $msg, $section = null ) {
668 if ( is_null( $section ) ) {
669 $this->mHeader = $msg;
670 } else {
671 $this->mSectionHeaders[$section] = $msg;
674 return $this;
678 * Add footer text, inside the form.
680 * @param string $msg Complete text of message to display
681 * @param string|null $section The section to add the footer text to
683 * @return HTMLForm $this for chaining calls (since 1.20)
685 function addFooterText( $msg, $section = null ) {
686 if ( is_null( $section ) ) {
687 $this->mFooter .= $msg;
688 } else {
689 if ( !isset( $this->mSectionFooters[$section] ) ) {
690 $this->mSectionFooters[$section] = '';
692 $this->mSectionFooters[$section] .= $msg;
695 return $this;
699 * Set footer text, inside the form.
700 * @since 1.19
702 * @param string $msg Complete text of message to display
703 * @param string|null $section The section to add the footer text to
705 * @return HTMLForm $this for chaining calls (since 1.20)
707 function setFooterText( $msg, $section = null ) {
708 if ( is_null( $section ) ) {
709 $this->mFooter = $msg;
710 } else {
711 $this->mSectionFooters[$section] = $msg;
714 return $this;
718 * Add text to the end of the display.
720 * @param string $msg Complete text of message to display
722 * @return HTMLForm $this for chaining calls (since 1.20)
724 function addPostText( $msg ) {
725 $this->mPost .= $msg;
727 return $this;
731 * Set text at the end of the display.
733 * @param string $msg Complete text of message to display
735 * @return HTMLForm $this for chaining calls (since 1.20)
737 function setPostText( $msg ) {
738 $this->mPost = $msg;
740 return $this;
744 * Add a hidden field to the output
746 * @param string $name Field name. This will be used exactly as entered
747 * @param string $value Field value
748 * @param array $attribs
750 * @return HTMLForm $this for chaining calls (since 1.20)
752 public function addHiddenField( $name, $value, $attribs = array() ) {
753 $attribs += array( 'name' => $name );
754 $this->mHiddenFields[] = array( $value, $attribs );
756 return $this;
760 * Add an array of hidden fields to the output
762 * @since 1.22
764 * @param array $fields Associative array of fields to add;
765 * mapping names to their values
767 * @return HTMLForm $this for chaining calls
769 public function addHiddenFields( array $fields ) {
770 foreach ( $fields as $name => $value ) {
771 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
774 return $this;
778 * Add a button to the form
780 * @param string $name Field name.
781 * @param string $value Field value
782 * @param string $id DOM id for the button (default: null)
783 * @param array $attribs
785 * @return HTMLForm $this for chaining calls (since 1.20)
787 public function addButton( $name, $value, $id = null, $attribs = null ) {
788 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
790 return $this;
794 * Set the salt for the edit token.
796 * Only useful when the method is "post".
798 * @since 1.24
799 * @param string|array $salt Salt to use
800 * @return HTMLForm $this For chaining calls
802 public function setTokenSalt( $salt ) {
803 $this->mTokenSalt = $salt;
805 return $this;
809 * Display the form (sending to the context's OutputPage object), with an
810 * appropriate error message or stack of messages, and any validation errors, etc.
812 * @attention You should call prepareForm() before calling this function.
813 * Moreover, when doing method chaining this should be the very last method
814 * call just after prepareForm().
816 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
818 * @return void Nothing, should be last call
820 function displayForm( $submitResult ) {
821 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
825 * Returns the raw HTML generated by the form
827 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
829 * @return string
831 function getHTML( $submitResult ) {
832 # For good measure (it is the default)
833 $this->getOutput()->preventClickjacking();
834 $this->getOutput()->addModules( 'mediawiki.htmlform' );
836 $html = ''
837 . $this->getErrors( $submitResult )
838 . $this->mHeader
839 . $this->getBody()
840 . $this->getHiddenFields()
841 . $this->getButtons()
842 . $this->mFooter;
844 $html = $this->wrapForm( $html );
846 return '' . $this->mPre . $html . $this->mPost;
850 * Get HTML attributes for the `<form>` tag.
851 * @return array
853 protected function getFormAttributes() {
854 # Use multipart/form-data
855 $encType = $this->mUseMultipart
856 ? 'multipart/form-data'
857 : 'application/x-www-form-urlencoded';
858 # Attributes
859 $attribs = array(
860 'action' => $this->getAction(),
861 'method' => $this->getMethod(),
862 'class' => array( 'visualClear' ),
863 'enctype' => $encType,
865 if ( !empty( $this->mId ) ) {
866 $attribs['id'] = $this->mId;
868 return $attribs;
872 * Wrap the form innards in an actual "<form>" element
874 * @param string $html HTML contents to wrap.
876 * @return string Wrapped HTML.
878 function wrapForm( $html ) {
879 # Include a <fieldset> wrapper for style, if requested.
880 if ( $this->mWrapperLegend !== false ) {
881 $html = Xml::fieldset( $this->mWrapperLegend, $html );
884 return Html::rawElement( 'form', $this->getFormAttributes(), $html );
888 * Get the hidden fields that should go inside the form.
889 * @return string HTML.
891 function getHiddenFields() {
892 $html = '';
893 if ( $this->getMethod() == 'post' ) {
894 $html .= Html::hidden(
895 'wpEditToken',
896 $this->getUser()->getEditToken( $this->mTokenSalt ),
897 array( 'id' => 'wpEditToken' )
898 ) . "\n";
899 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
902 $articlePath = $this->getConfig()->get( 'ArticlePath' );
903 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
904 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
907 foreach ( $this->mHiddenFields as $data ) {
908 list( $value, $attribs ) = $data;
909 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
912 return $html;
916 * Get the submit and (potentially) reset buttons.
917 * @return string HTML.
919 function getButtons() {
920 $buttons = '';
921 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
923 if ( $this->mShowSubmit ) {
924 $attribs = array();
926 if ( isset( $this->mSubmitID ) ) {
927 $attribs['id'] = $this->mSubmitID;
930 if ( isset( $this->mSubmitName ) ) {
931 $attribs['name'] = $this->mSubmitName;
934 if ( isset( $this->mSubmitTooltip ) ) {
935 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
938 $attribs['class'] = array( 'mw-htmlform-submit' );
940 if ( $useMediaWikiUIEverywhere ) {
941 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass );
944 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
947 if ( $this->mShowReset ) {
948 $buttons .= Html::element(
949 'input',
950 array(
951 'type' => 'reset',
952 'value' => $this->msg( 'htmlform-reset' )->text(),
953 'class' => ( $useMediaWikiUIEverywhere ? 'mw-ui-button' : null ),
955 ) . "\n";
958 foreach ( $this->mButtons as $button ) {
959 $attrs = array(
960 'type' => 'submit',
961 'name' => $button['name'],
962 'value' => $button['value']
965 if ( $button['attribs'] ) {
966 $attrs += $button['attribs'];
969 if ( isset( $button['id'] ) ) {
970 $attrs['id'] = $button['id'];
973 if ( $useMediaWikiUIEverywhere ) {
974 $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : array();
975 $attrs['class'][] = 'mw-ui-button';
978 $buttons .= Html::element( 'input', $attrs ) . "\n";
981 $html = Html::rawElement( 'span',
982 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
984 return $html;
988 * Get the whole body of the form.
989 * @return string
991 function getBody() {
992 return $this->displaySection( $this->mFieldTree, $this->mTableId );
996 * Format and display an error message stack.
998 * @param string|array|Status $errors
1000 * @return string
1002 function getErrors( $errors ) {
1003 if ( $errors instanceof Status ) {
1004 if ( $errors->isOK() ) {
1005 $errorstr = '';
1006 } else {
1007 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1009 } elseif ( is_array( $errors ) ) {
1010 $errorstr = $this->formatErrors( $errors );
1011 } else {
1012 $errorstr = $errors;
1015 return $errorstr
1016 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1017 : '';
1021 * Format a stack of error messages into a single HTML string
1023 * @param array $errors Array of message keys/values
1025 * @return string HTML, a "<ul>" list of errors
1027 public function formatErrors( $errors ) {
1028 $errorstr = '';
1030 foreach ( $errors as $error ) {
1031 if ( is_array( $error ) ) {
1032 $msg = array_shift( $error );
1033 } else {
1034 $msg = $error;
1035 $error = array();
1038 $errorstr .= Html::rawElement(
1039 'li',
1040 array(),
1041 $this->msg( $msg, $error )->parse()
1045 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1047 return $errorstr;
1051 * Set the text for the submit button
1053 * @param string $t Plaintext
1055 * @return HTMLForm $this for chaining calls (since 1.20)
1057 function setSubmitText( $t ) {
1058 $this->mSubmitText = $t;
1060 return $this;
1064 * Identify that the submit button in the form has a destructive action
1065 * @since 1.24
1067 public function setSubmitDestructive() {
1068 $this->mSubmitModifierClass = 'mw-ui-destructive';
1072 * Identify that the submit button in the form has a progressive action
1073 * @since 1.25
1075 public function setSubmitProgressive() {
1076 $this->mSubmitModifierClass = 'mw-ui-progressive';
1080 * Set the text for the submit button to a message
1081 * @since 1.19
1083 * @param string|Message $msg Message key or Message object
1085 * @return HTMLForm $this for chaining calls (since 1.20)
1087 public function setSubmitTextMsg( $msg ) {
1088 if ( !$msg instanceof Message ) {
1089 $msg = $this->msg( $msg );
1091 $this->setSubmitText( $msg->text() );
1093 return $this;
1097 * Get the text for the submit button, either customised or a default.
1098 * @return string
1100 function getSubmitText() {
1101 return $this->mSubmitText
1102 ? $this->mSubmitText
1103 : $this->msg( 'htmlform-submit' )->text();
1107 * @param string $name Submit button name
1109 * @return HTMLForm $this for chaining calls (since 1.20)
1111 public function setSubmitName( $name ) {
1112 $this->mSubmitName = $name;
1114 return $this;
1118 * @param string $name Tooltip for the submit button
1120 * @return HTMLForm $this for chaining calls (since 1.20)
1122 public function setSubmitTooltip( $name ) {
1123 $this->mSubmitTooltip = $name;
1125 return $this;
1129 * Set the id for the submit button.
1131 * @param string $t
1133 * @todo FIXME: Integrity of $t is *not* validated
1134 * @return HTMLForm $this for chaining calls (since 1.20)
1136 function setSubmitID( $t ) {
1137 $this->mSubmitID = $t;
1139 return $this;
1143 * Stop a default submit button being shown for this form. This implies that an
1144 * alternate submit method must be provided manually.
1146 * @since 1.22
1148 * @param bool $suppressSubmit Set to false to re-enable the button again
1150 * @return HTMLForm $this for chaining calls
1152 function suppressDefaultSubmit( $suppressSubmit = true ) {
1153 $this->mShowSubmit = !$suppressSubmit;
1155 return $this;
1159 * Set the id of the \<table\> or outermost \<div\> element.
1161 * @since 1.22
1163 * @param string $id New value of the id attribute, or "" to remove
1165 * @return HTMLForm $this for chaining calls
1167 public function setTableId( $id ) {
1168 $this->mTableId = $id;
1170 return $this;
1174 * @param string $id DOM id for the form
1176 * @return HTMLForm $this for chaining calls (since 1.20)
1178 public function setId( $id ) {
1179 $this->mId = $id;
1181 return $this;
1185 * Prompt the whole form to be wrapped in a "<fieldset>", with
1186 * this text as its "<legend>" element.
1188 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1189 * false for no <legend>
1190 * Will be escaped
1192 * @return HTMLForm $this for chaining calls (since 1.20)
1194 public function setWrapperLegend( $legend ) {
1195 $this->mWrapperLegend = $legend;
1197 return $this;
1201 * Prompt the whole form to be wrapped in a "<fieldset>", with
1202 * this message as its "<legend>" element.
1203 * @since 1.19
1205 * @param string|Message $msg Message key or Message object
1207 * @return HTMLForm $this for chaining calls (since 1.20)
1209 public function setWrapperLegendMsg( $msg ) {
1210 if ( !$msg instanceof Message ) {
1211 $msg = $this->msg( $msg );
1213 $this->setWrapperLegend( $msg->text() );
1215 return $this;
1219 * Set the prefix for various default messages
1220 * @todo Currently only used for the "<fieldset>" legend on forms
1221 * with multiple sections; should be used elsewhere?
1223 * @param string $p
1225 * @return HTMLForm $this for chaining calls (since 1.20)
1227 function setMessagePrefix( $p ) {
1228 $this->mMessagePrefix = $p;
1230 return $this;
1234 * Set the title for form submission
1236 * @param Title $t Title of page the form is on/should be posted to
1238 * @return HTMLForm $this for chaining calls (since 1.20)
1240 function setTitle( $t ) {
1241 $this->mTitle = $t;
1243 return $this;
1247 * Get the title
1248 * @return Title
1250 function getTitle() {
1251 return $this->mTitle === false
1252 ? $this->getContext()->getTitle()
1253 : $this->mTitle;
1257 * Set the method used to submit the form
1259 * @param string $method
1261 * @return HTMLForm $this for chaining calls (since 1.20)
1263 public function setMethod( $method = 'post' ) {
1264 $this->mMethod = $method;
1266 return $this;
1269 public function getMethod() {
1270 return $this->mMethod;
1274 * @todo Document
1276 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1277 * objects).
1278 * @param string $sectionName ID attribute of the "<table>" tag for this
1279 * section, ignored if empty.
1280 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1281 * each subsection, ignored if empty.
1282 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1284 * @return string
1286 public function displaySection( $fields,
1287 $sectionName = '',
1288 $fieldsetIDPrefix = '',
1289 &$hasUserVisibleFields = false ) {
1290 $displayFormat = $this->getDisplayFormat();
1292 $html = '';
1293 $subsectionHtml = '';
1294 $hasLabel = false;
1296 // Conveniently, PHP method names are case-insensitive.
1297 $getFieldHtmlMethod = $displayFormat == 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1299 foreach ( $fields as $key => $value ) {
1300 if ( $value instanceof HTMLFormField ) {
1301 $v = empty( $value->mParams['nodata'] )
1302 ? $this->mFieldData[$key]
1303 : $value->getDefault();
1304 $html .= $value->$getFieldHtmlMethod( $v );
1306 $labelValue = trim( $value->getLabel() );
1307 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1308 $hasLabel = true;
1311 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1312 get_class( $value ) !== 'HTMLApiField'
1314 $hasUserVisibleFields = true;
1316 } elseif ( is_array( $value ) ) {
1317 $subsectionHasVisibleFields = false;
1318 $section =
1319 $this->displaySection( $value,
1320 "mw-htmlform-$key",
1321 "$fieldsetIDPrefix$key-",
1322 $subsectionHasVisibleFields );
1323 $legend = null;
1325 if ( $subsectionHasVisibleFields === true ) {
1326 // Display the section with various niceties.
1327 $hasUserVisibleFields = true;
1329 $legend = $this->getLegend( $key );
1331 if ( isset( $this->mSectionHeaders[$key] ) ) {
1332 $section = $this->mSectionHeaders[$key] . $section;
1334 if ( isset( $this->mSectionFooters[$key] ) ) {
1335 $section .= $this->mSectionFooters[$key];
1338 $attributes = array();
1339 if ( $fieldsetIDPrefix ) {
1340 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1342 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1343 } else {
1344 // Just return the inputs, nothing fancy.
1345 $subsectionHtml .= $section;
1350 if ( $displayFormat !== 'raw' ) {
1351 $classes = array();
1353 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1354 $classes[] = 'mw-htmlform-nolabel';
1357 $attribs = array(
1358 'class' => implode( ' ', $classes ),
1361 if ( $sectionName ) {
1362 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1365 if ( $displayFormat === 'table' ) {
1366 $html = Html::rawElement( 'table',
1367 $attribs,
1368 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1369 } else {
1370 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1374 if ( $this->mSubSectionBeforeFields ) {
1375 return $subsectionHtml . "\n" . $html;
1376 } else {
1377 return $html . "\n" . $subsectionHtml;
1382 * Construct the form fields from the Descriptor array
1384 function loadData() {
1385 $fieldData = array();
1387 foreach ( $this->mFlatFields as $fieldname => $field ) {
1388 if ( !empty( $field->mParams['nodata'] ) ) {
1389 continue;
1390 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1391 $fieldData[$fieldname] = $field->getDefault();
1392 } else {
1393 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1397 # Filter data.
1398 foreach ( $fieldData as $name => &$value ) {
1399 $field = $this->mFlatFields[$name];
1400 $value = $field->filter( $value, $this->mFlatFields );
1403 $this->mFieldData = $fieldData;
1407 * Stop a reset button being shown for this form
1409 * @param bool $suppressReset Set to false to re-enable the button again
1411 * @return HTMLForm $this for chaining calls (since 1.20)
1413 function suppressReset( $suppressReset = true ) {
1414 $this->mShowReset = !$suppressReset;
1416 return $this;
1420 * Overload this if you want to apply special filtration routines
1421 * to the form as a whole, after it's submitted but before it's
1422 * processed.
1424 * @param array $data
1426 * @return array
1428 function filterDataForSubmit( $data ) {
1429 return $data;
1433 * Get a string to go in the "<legend>" of a section fieldset.
1434 * Override this if you want something more complicated.
1436 * @param string $key
1438 * @return string
1440 public function getLegend( $key ) {
1441 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1445 * Set the value for the action attribute of the form.
1446 * When set to false (which is the default state), the set title is used.
1448 * @since 1.19
1450 * @param string|bool $action
1452 * @return HTMLForm $this for chaining calls (since 1.20)
1454 public function setAction( $action ) {
1455 $this->mAction = $action;
1457 return $this;
1461 * Get the value for the action attribute of the form.
1463 * @since 1.22
1465 * @return string
1467 public function getAction() {
1468 // If an action is alredy provided, return it
1469 if ( $this->mAction !== false ) {
1470 return $this->mAction;
1473 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1474 // Check whether we are in GET mode and the ArticlePath contains a "?"
1475 // meaning that getLocalURL() would return something like "index.php?title=...".
1476 // As browser remove the query string before submitting GET forms,
1477 // it means that the title would be lost. In such case use wfScript() instead
1478 // and put title in an hidden field (see getHiddenFields()).
1479 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1480 return wfScript();
1483 return $this->getTitle()->getLocalURL();