Implement extension registration from an extension.json file
[mediawiki.git] / includes / htmlform / HTMLForm.php
blobdc73522144f8a238073db312cb47779170dea9cf
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',
210 'vform',
214 * Build a new HTMLForm from an array of field attributes
216 * @param array $descriptor Array of Field constructs, as described above
217 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
218 * Obviates the need to call $form->setTitle()
219 * @param string $messagePrefix A prefix to go in front of default messages
221 public function __construct( $descriptor, /*IContextSource*/ $context = null,
222 $messagePrefix = ''
224 if ( $context instanceof IContextSource ) {
225 $this->setContext( $context );
226 $this->mTitle = false; // We don't need them to set a title
227 $this->mMessagePrefix = $messagePrefix;
228 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
229 $this->mMessagePrefix = $messagePrefix;
230 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
231 // B/C since 1.18
232 // it's actually $messagePrefix
233 $this->mMessagePrefix = $context;
236 // Expand out into a tree.
237 $loadedDescriptor = array();
238 $this->mFlatFields = array();
240 foreach ( $descriptor as $fieldname => $info ) {
241 $section = isset( $info['section'] )
242 ? $info['section']
243 : '';
245 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
246 $this->mUseMultipart = true;
249 $field = self::loadInputFromParameters( $fieldname, $info, $this );
251 // vform gets too much space if empty labels generate HTML.
252 if ( $this->isVForm() ) {
253 $field->setShowEmptyLabel( false );
256 $setSection =& $loadedDescriptor;
257 if ( $section ) {
258 $sectionParts = explode( '/', $section );
260 while ( count( $sectionParts ) ) {
261 $newName = array_shift( $sectionParts );
263 if ( !isset( $setSection[$newName] ) ) {
264 $setSection[$newName] = array();
267 $setSection =& $setSection[$newName];
271 $setSection[$fieldname] = $field;
272 $this->mFlatFields[$fieldname] = $field;
275 $this->mFieldTree = $loadedDescriptor;
279 * Set format in which to display the form
281 * @param string $format The name of the format to use, must be one of
282 * $this->availableDisplayFormats
284 * @throws MWException
285 * @since 1.20
286 * @return HTMLForm $this for chaining calls (since 1.20)
288 public function setDisplayFormat( $format ) {
289 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
290 throw new MWException( 'Display format must be one of ' .
291 print_r( $this->availableDisplayFormats, true ) );
293 $this->displayFormat = $format;
295 return $this;
299 * Getter for displayFormat
300 * @since 1.20
301 * @return string
303 public function getDisplayFormat() {
304 $format = $this->displayFormat;
305 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
306 $format = 'div';
308 return $format;
312 * Test if displayFormat is 'vform'
313 * @since 1.22
314 * @return bool
316 public function isVForm() {
317 return $this->displayFormat === 'vform';
321 * Get the HTMLFormField subclass for this descriptor.
323 * The descriptor can be passed either 'class' which is the name of
324 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
325 * This makes sure the 'class' is always set, and also is returned by
326 * this function for ease.
328 * @since 1.23
330 * @param string $fieldname Name of the field
331 * @param array $descriptor Input Descriptor, as described above
333 * @throws MWException
334 * @return string Name of a HTMLFormField subclass
336 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
337 if ( isset( $descriptor['class'] ) ) {
338 $class = $descriptor['class'];
339 } elseif ( isset( $descriptor['type'] ) ) {
340 $class = self::$typeMappings[$descriptor['type']];
341 $descriptor['class'] = $class;
342 } else {
343 $class = null;
346 if ( !$class ) {
347 throw new MWException( "Descriptor with no class for $fieldname: "
348 . print_r( $descriptor, true ) );
351 return $class;
355 * Initialise a new Object for the field
357 * @param string $fieldname Name of the field
358 * @param array $descriptor Input Descriptor, as described above
359 * @param HTMLForm|null $parent Parent instance of HTMLForm
361 * @throws MWException
362 * @return HTMLFormField Instance of a subclass of HTMLFormField
364 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent = null ) {
365 $class = self::getClassFromDescriptor( $fieldname, $descriptor );
367 $descriptor['fieldname'] = $fieldname;
368 if ( $parent ) {
369 $descriptor['parent'] = $parent;
372 # @todo This will throw a fatal error whenever someone try to use
373 # 'class' to feed a CSS class instead of 'cssclass'. Would be
374 # great to avoid the fatal error and show a nice error.
375 $obj = new $class( $descriptor );
377 return $obj;
381 * Prepare form for submission.
383 * @attention When doing method chaining, that should be the very last
384 * method call before displayForm().
386 * @throws MWException
387 * @return HTMLForm $this for chaining calls (since 1.20)
389 function prepareForm() {
390 # Check if we have the info we need
391 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
392 throw new MWException( "You must call setTitle() on an HTMLForm" );
395 # Load data from the request.
396 $this->loadData();
398 return $this;
402 * Try submitting, with edit token check first
403 * @return Status|bool
405 function tryAuthorizedSubmit() {
406 $result = false;
408 $submit = false;
409 if ( $this->getMethod() != 'post' ) {
410 $submit = true; // no session check needed
411 } elseif ( $this->getRequest()->wasPosted() ) {
412 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
413 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
414 // Session tokens for logged-out users have no security value.
415 // However, if the user gave one, check it in order to give a nice
416 // "session expired" error instead of "permission denied" or such.
417 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
418 } else {
419 $submit = true;
423 if ( $submit ) {
424 $this->mWasSubmitted = true;
425 $result = $this->trySubmit();
428 return $result;
432 * The here's-one-I-made-earlier option: do the submission if
433 * posted, or display the form with or without funky validation
434 * errors
435 * @return bool|Status Whether submission was successful.
437 function show() {
438 $this->prepareForm();
440 $result = $this->tryAuthorizedSubmit();
441 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
442 return $result;
445 $this->displayForm( $result );
447 return false;
451 * Validate all the fields, and call the submission callback
452 * function if everything is kosher.
453 * @throws MWException
454 * @return bool|string|array|Status
455 * - Bool true or a good Status object indicates success,
456 * - Bool false indicates no submission was attempted,
457 * - Anything else indicates failure. The value may be a fatal Status
458 * object, an HTML string, or an array of arrays (message keys and
459 * params) or strings (message keys)
461 function trySubmit() {
462 $this->mWasSubmitted = true;
464 # Check for cancelled submission
465 foreach ( $this->mFlatFields as $fieldname => $field ) {
466 if ( !empty( $field->mParams['nodata'] ) ) {
467 continue;
469 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
470 $this->mWasSubmitted = false;
471 return false;
475 # Check for validation
476 foreach ( $this->mFlatFields as $fieldname => $field ) {
477 if ( !empty( $field->mParams['nodata'] ) ) {
478 continue;
480 if ( $field->isHidden( $this->mFieldData ) ) {
481 continue;
483 if ( $field->validate(
484 $this->mFieldData[$fieldname],
485 $this->mFieldData )
486 !== true
488 return isset( $this->mValidationErrorMessage )
489 ? $this->mValidationErrorMessage
490 : array( 'htmlform-invalid-input' );
494 $callback = $this->mSubmitCallback;
495 if ( !is_callable( $callback ) ) {
496 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
497 'setSubmitCallback() to set one.' );
500 $data = $this->filterDataForSubmit( $this->mFieldData );
502 $res = call_user_func( $callback, $data, $this );
503 if ( $res === false ) {
504 $this->mWasSubmitted = false;
507 return $res;
511 * Test whether the form was considered to have been submitted or not, i.e.
512 * whether the last call to tryAuthorizedSubmit or trySubmit returned
513 * non-false.
515 * This will return false until HTMLForm::tryAuthorizedSubmit or
516 * HTMLForm::trySubmit is called.
518 * @since 1.23
519 * @return bool
521 function wasSubmitted() {
522 return $this->mWasSubmitted;
526 * Set a callback to a function to do something with the form
527 * once it's been successfully validated.
529 * @param callable $cb The function will be passed the output from
530 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
531 * return as documented for HTMLForm::trySubmit
533 * @return HTMLForm $this for chaining calls (since 1.20)
535 function setSubmitCallback( $cb ) {
536 $this->mSubmitCallback = $cb;
538 return $this;
542 * Set a message to display on a validation error.
544 * @param string|array $msg String or Array of valid inputs to wfMessage()
545 * (so each entry can be either a String or Array)
547 * @return HTMLForm $this for chaining calls (since 1.20)
549 function setValidationErrorMessage( $msg ) {
550 $this->mValidationErrorMessage = $msg;
552 return $this;
556 * Set the introductory message, overwriting any existing message.
558 * @param string $msg Complete text of message to display
560 * @return HTMLForm $this for chaining calls (since 1.20)
562 function setIntro( $msg ) {
563 $this->setPreText( $msg );
565 return $this;
569 * Set the introductory message, overwriting any existing message.
570 * @since 1.19
572 * @param string $msg Complete text of message to display
574 * @return HTMLForm $this for chaining calls (since 1.20)
576 function setPreText( $msg ) {
577 $this->mPre = $msg;
579 return $this;
583 * Add introductory text.
585 * @param string $msg Complete text of message to display
587 * @return HTMLForm $this for chaining calls (since 1.20)
589 function addPreText( $msg ) {
590 $this->mPre .= $msg;
592 return $this;
596 * Add header text, inside the form.
598 * @param string $msg Complete text of message to display
599 * @param string|null $section The section to add the header to
601 * @return HTMLForm $this for chaining calls (since 1.20)
603 function addHeaderText( $msg, $section = null ) {
604 if ( is_null( $section ) ) {
605 $this->mHeader .= $msg;
606 } else {
607 if ( !isset( $this->mSectionHeaders[$section] ) ) {
608 $this->mSectionHeaders[$section] = '';
610 $this->mSectionHeaders[$section] .= $msg;
613 return $this;
617 * Set header text, inside the form.
618 * @since 1.19
620 * @param string $msg Complete text of message to display
621 * @param string|null $section The section to add the header to
623 * @return HTMLForm $this for chaining calls (since 1.20)
625 function setHeaderText( $msg, $section = null ) {
626 if ( is_null( $section ) ) {
627 $this->mHeader = $msg;
628 } else {
629 $this->mSectionHeaders[$section] = $msg;
632 return $this;
636 * Add footer text, inside the form.
638 * @param string $msg Complete text of message to display
639 * @param string|null $section The section to add the footer text to
641 * @return HTMLForm $this for chaining calls (since 1.20)
643 function addFooterText( $msg, $section = null ) {
644 if ( is_null( $section ) ) {
645 $this->mFooter .= $msg;
646 } else {
647 if ( !isset( $this->mSectionFooters[$section] ) ) {
648 $this->mSectionFooters[$section] = '';
650 $this->mSectionFooters[$section] .= $msg;
653 return $this;
657 * Set footer text, inside the form.
658 * @since 1.19
660 * @param string $msg Complete text of message to display
661 * @param string|null $section The section to add the footer text to
663 * @return HTMLForm $this for chaining calls (since 1.20)
665 function setFooterText( $msg, $section = null ) {
666 if ( is_null( $section ) ) {
667 $this->mFooter = $msg;
668 } else {
669 $this->mSectionFooters[$section] = $msg;
672 return $this;
676 * Add text to the end of the display.
678 * @param string $msg Complete text of message to display
680 * @return HTMLForm $this for chaining calls (since 1.20)
682 function addPostText( $msg ) {
683 $this->mPost .= $msg;
685 return $this;
689 * Set text at the end of the display.
691 * @param string $msg Complete text of message to display
693 * @return HTMLForm $this for chaining calls (since 1.20)
695 function setPostText( $msg ) {
696 $this->mPost = $msg;
698 return $this;
702 * Add a hidden field to the output
704 * @param string $name Field name. This will be used exactly as entered
705 * @param string $value Field value
706 * @param array $attribs
708 * @return HTMLForm $this for chaining calls (since 1.20)
710 public function addHiddenField( $name, $value, $attribs = array() ) {
711 $attribs += array( 'name' => $name );
712 $this->mHiddenFields[] = array( $value, $attribs );
714 return $this;
718 * Add an array of hidden fields to the output
720 * @since 1.22
722 * @param array $fields Associative array of fields to add;
723 * mapping names to their values
725 * @return HTMLForm $this for chaining calls
727 public function addHiddenFields( array $fields ) {
728 foreach ( $fields as $name => $value ) {
729 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
732 return $this;
736 * Add a button to the form
738 * @param string $name Field name.
739 * @param string $value Field value
740 * @param string $id DOM id for the button (default: null)
741 * @param array $attribs
743 * @return HTMLForm $this for chaining calls (since 1.20)
745 public function addButton( $name, $value, $id = null, $attribs = null ) {
746 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
748 return $this;
752 * Set the salt for the edit token.
754 * Only useful when the method is "post".
756 * @since 1.24
757 * @param string|array $salt Salt to use
758 * @return HTMLForm $this For chaining calls
760 public function setTokenSalt( $salt ) {
761 $this->mTokenSalt = $salt;
763 return $this;
767 * Display the form (sending to the context's OutputPage object), with an
768 * appropriate error message or stack of messages, and any validation errors, etc.
770 * @attention You should call prepareForm() before calling this function.
771 * Moreover, when doing method chaining this should be the very last method
772 * call just after prepareForm().
774 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
776 * @return void Nothing, should be last call
778 function displayForm( $submitResult ) {
779 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
783 * Returns the raw HTML generated by the form
785 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
787 * @return string
789 function getHTML( $submitResult ) {
790 # For good measure (it is the default)
791 $this->getOutput()->preventClickjacking();
792 $this->getOutput()->addModules( 'mediawiki.htmlform' );
793 if ( $this->isVForm() ) {
794 // This is required for VForm HTMLForms that use that style regardless
795 // of wgUseMediaWikiUIEverywhere (since they pre-date it).
796 // When wgUseMediaWikiUIEverywhere is removed, this should be consolidated
797 // with the addModuleStyles in SpecialPage->setHeaders.
798 $this->getOutput()->addModuleStyles( array(
799 'mediawiki.ui',
800 'mediawiki.ui.button',
801 'mediawiki.ui.input',
802 ) );
803 // @todo Should vertical form set setWrapperLegend( false )
804 // to hide ugly fieldsets?
807 $html = ''
808 . $this->getErrors( $submitResult )
809 . $this->mHeader
810 . $this->getBody()
811 . $this->getHiddenFields()
812 . $this->getButtons()
813 . $this->mFooter;
815 $html = $this->wrapForm( $html );
817 return '' . $this->mPre . $html . $this->mPost;
821 * Wrap the form innards in an actual "<form>" element
823 * @param string $html HTML contents to wrap.
825 * @return string Wrapped HTML.
827 function wrapForm( $html ) {
829 # Include a <fieldset> wrapper for style, if requested.
830 if ( $this->mWrapperLegend !== false ) {
831 $html = Xml::fieldset( $this->mWrapperLegend, $html );
833 # Use multipart/form-data
834 $encType = $this->mUseMultipart
835 ? 'multipart/form-data'
836 : 'application/x-www-form-urlencoded';
837 # Attributes
838 $attribs = array(
839 'action' => $this->getAction(),
840 'method' => $this->getMethod(),
841 'class' => array( 'visualClear' ),
842 'enctype' => $encType,
844 if ( !empty( $this->mId ) ) {
845 $attribs['id'] = $this->mId;
848 if ( $this->isVForm() ) {
849 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
852 return Html::rawElement( 'form', $attribs, $html );
856 * Get the hidden fields that should go inside the form.
857 * @return string HTML.
859 function getHiddenFields() {
860 $html = '';
861 if ( $this->getMethod() == 'post' ) {
862 $html .= Html::hidden(
863 'wpEditToken',
864 $this->getUser()->getEditToken( $this->mTokenSalt ),
865 array( 'id' => 'wpEditToken' )
866 ) . "\n";
867 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
870 $articlePath = $this->getConfig()->get( 'ArticlePath' );
871 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
872 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
875 foreach ( $this->mHiddenFields as $data ) {
876 list( $value, $attribs ) = $data;
877 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
880 return $html;
884 * Get the submit and (potentially) reset buttons.
885 * @return string HTML.
887 function getButtons() {
888 $buttons = '';
889 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
891 if ( $this->mShowSubmit ) {
892 $attribs = array();
894 if ( isset( $this->mSubmitID ) ) {
895 $attribs['id'] = $this->mSubmitID;
898 if ( isset( $this->mSubmitName ) ) {
899 $attribs['name'] = $this->mSubmitName;
902 if ( isset( $this->mSubmitTooltip ) ) {
903 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
906 $attribs['class'] = array( 'mw-htmlform-submit' );
908 if ( $this->isVForm() || $useMediaWikiUIEverywhere ) {
909 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass );
912 if ( $this->isVForm() ) {
913 // mw-ui-block is necessary because the buttons aren't necessarily in an
914 // immediate child div of the vform.
915 // @todo Let client specify if the primary submit button is progressive or destructive
916 array_push(
917 $attribs['class'],
918 'mw-ui-big',
919 'mw-ui-block'
923 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
926 if ( $this->mShowReset ) {
927 $buttons .= Html::element(
928 'input',
929 array(
930 'type' => 'reset',
931 'value' => $this->msg( 'htmlform-reset' )->text()
933 ) . "\n";
936 foreach ( $this->mButtons as $button ) {
937 $attrs = array(
938 'type' => 'submit',
939 'name' => $button['name'],
940 'value' => $button['value']
943 if ( $button['attribs'] ) {
944 $attrs += $button['attribs'];
947 if ( isset( $button['id'] ) ) {
948 $attrs['id'] = $button['id'];
951 if ( $this->isVForm() || $useMediaWikiUIEverywhere ) {
952 if ( isset( $attrs['class'] ) ) {
953 $attrs['class'] .= ' mw-ui-button';
954 } else {
955 $attrs['class'] = 'mw-ui-button';
957 if ( $this->isVForm() ) {
958 $attrs['class'] .= ' mw-ui-big mw-ui-block';
962 $buttons .= Html::element( 'input', $attrs ) . "\n";
965 $html = Html::rawElement( 'span',
966 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
968 // Buttons are top-level form elements in table and div layouts,
969 // but vform wants all elements inside divs to get spaced-out block
970 // styling.
971 if ( $this->mShowSubmit && $this->isVForm() ) {
972 $html = Html::rawElement( 'div', null, "\n$html" ) . "\n";
975 return $html;
979 * Get the whole body of the form.
980 * @return string
982 function getBody() {
983 return $this->displaySection( $this->mFieldTree, $this->mTableId );
987 * Format and display an error message stack.
989 * @param string|array|Status $errors
991 * @return string
993 function getErrors( $errors ) {
994 if ( $errors instanceof Status ) {
995 if ( $errors->isOK() ) {
996 $errorstr = '';
997 } else {
998 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1000 } elseif ( is_array( $errors ) ) {
1001 $errorstr = $this->formatErrors( $errors );
1002 } else {
1003 $errorstr = $errors;
1006 return $errorstr
1007 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1008 : '';
1012 * Format a stack of error messages into a single HTML string
1014 * @param array $errors Array of message keys/values
1016 * @return string HTML, a "<ul>" list of errors
1018 public function formatErrors( $errors ) {
1019 $errorstr = '';
1021 foreach ( $errors as $error ) {
1022 if ( is_array( $error ) ) {
1023 $msg = array_shift( $error );
1024 } else {
1025 $msg = $error;
1026 $error = array();
1029 $errorstr .= Html::rawElement(
1030 'li',
1031 array(),
1032 $this->msg( $msg, $error )->parse()
1036 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1038 return $errorstr;
1042 * Set the text for the submit button
1044 * @param string $t Plaintext
1046 * @return HTMLForm $this for chaining calls (since 1.20)
1048 function setSubmitText( $t ) {
1049 $this->mSubmitText = $t;
1051 return $this;
1055 * Identify that the submit button in the form has a destructive action
1056 * @since 1.24
1058 public function setSubmitDestructive() {
1059 $this->mSubmitModifierClass = 'mw-ui-destructive';
1063 * Identify that the submit button in the form has a progressive action
1064 * @since 1.25
1066 public function setSubmitProgressive() {
1067 $this->mSubmitModifierClass = 'mw-ui-progressive';
1071 * Set the text for the submit button to a message
1072 * @since 1.19
1074 * @param string|Message $msg Message key or Message object
1076 * @return HTMLForm $this for chaining calls (since 1.20)
1078 public function setSubmitTextMsg( $msg ) {
1079 if ( !$msg instanceof Message ) {
1080 $msg = $this->msg( $msg );
1082 $this->setSubmitText( $msg->text() );
1084 return $this;
1088 * Get the text for the submit button, either customised or a default.
1089 * @return string
1091 function getSubmitText() {
1092 return $this->mSubmitText
1093 ? $this->mSubmitText
1094 : $this->msg( 'htmlform-submit' )->text();
1098 * @param string $name Submit button name
1100 * @return HTMLForm $this for chaining calls (since 1.20)
1102 public function setSubmitName( $name ) {
1103 $this->mSubmitName = $name;
1105 return $this;
1109 * @param string $name Tooltip for the submit button
1111 * @return HTMLForm $this for chaining calls (since 1.20)
1113 public function setSubmitTooltip( $name ) {
1114 $this->mSubmitTooltip = $name;
1116 return $this;
1120 * Set the id for the submit button.
1122 * @param string $t
1124 * @todo FIXME: Integrity of $t is *not* validated
1125 * @return HTMLForm $this for chaining calls (since 1.20)
1127 function setSubmitID( $t ) {
1128 $this->mSubmitID = $t;
1130 return $this;
1134 * Stop a default submit button being shown for this form. This implies that an
1135 * alternate submit method must be provided manually.
1137 * @since 1.22
1139 * @param bool $suppressSubmit Set to false to re-enable the button again
1141 * @return HTMLForm $this for chaining calls
1143 function suppressDefaultSubmit( $suppressSubmit = true ) {
1144 $this->mShowSubmit = !$suppressSubmit;
1146 return $this;
1150 * Set the id of the \<table\> or outermost \<div\> element.
1152 * @since 1.22
1154 * @param string $id New value of the id attribute, or "" to remove
1156 * @return HTMLForm $this for chaining calls
1158 public function setTableId( $id ) {
1159 $this->mTableId = $id;
1161 return $this;
1165 * @param string $id DOM id for the form
1167 * @return HTMLForm $this for chaining calls (since 1.20)
1169 public function setId( $id ) {
1170 $this->mId = $id;
1172 return $this;
1176 * Prompt the whole form to be wrapped in a "<fieldset>", with
1177 * this text as its "<legend>" element.
1179 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1180 * false for no <legend>
1181 * Will be escaped
1183 * @return HTMLForm $this for chaining calls (since 1.20)
1185 public function setWrapperLegend( $legend ) {
1186 $this->mWrapperLegend = $legend;
1188 return $this;
1192 * Prompt the whole form to be wrapped in a "<fieldset>", with
1193 * this message as its "<legend>" element.
1194 * @since 1.19
1196 * @param string|Message $msg Message key or Message object
1198 * @return HTMLForm $this for chaining calls (since 1.20)
1200 public function setWrapperLegendMsg( $msg ) {
1201 if ( !$msg instanceof Message ) {
1202 $msg = $this->msg( $msg );
1204 $this->setWrapperLegend( $msg->text() );
1206 return $this;
1210 * Set the prefix for various default messages
1211 * @todo Currently only used for the "<fieldset>" legend on forms
1212 * with multiple sections; should be used elsewhere?
1214 * @param string $p
1216 * @return HTMLForm $this for chaining calls (since 1.20)
1218 function setMessagePrefix( $p ) {
1219 $this->mMessagePrefix = $p;
1221 return $this;
1225 * Set the title for form submission
1227 * @param Title $t Title of page the form is on/should be posted to
1229 * @return HTMLForm $this for chaining calls (since 1.20)
1231 function setTitle( $t ) {
1232 $this->mTitle = $t;
1234 return $this;
1238 * Get the title
1239 * @return Title
1241 function getTitle() {
1242 return $this->mTitle === false
1243 ? $this->getContext()->getTitle()
1244 : $this->mTitle;
1248 * Set the method used to submit the form
1250 * @param string $method
1252 * @return HTMLForm $this for chaining calls (since 1.20)
1254 public function setMethod( $method = 'post' ) {
1255 $this->mMethod = $method;
1257 return $this;
1260 public function getMethod() {
1261 return $this->mMethod;
1265 * @todo Document
1267 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1268 * objects).
1269 * @param string $sectionName ID attribute of the "<table>" tag for this
1270 * section, ignored if empty.
1271 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1272 * each subsection, ignored if empty.
1273 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1275 * @return string
1277 public function displaySection( $fields,
1278 $sectionName = '',
1279 $fieldsetIDPrefix = '',
1280 &$hasUserVisibleFields = false ) {
1281 $displayFormat = $this->getDisplayFormat();
1283 $html = '';
1284 $subsectionHtml = '';
1285 $hasLabel = false;
1287 switch ( $displayFormat ) {
1288 case 'table':
1289 $getFieldHtmlMethod = 'getTableRow';
1290 break;
1291 case 'vform':
1292 // Close enough to a div.
1293 $getFieldHtmlMethod = 'getDiv';
1294 break;
1295 case 'div':
1296 $getFieldHtmlMethod = 'getDiv';
1297 break;
1298 default:
1299 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1302 foreach ( $fields as $key => $value ) {
1303 if ( $value instanceof HTMLFormField ) {
1304 $v = empty( $value->mParams['nodata'] )
1305 ? $this->mFieldData[$key]
1306 : $value->getDefault();
1307 $html .= $value->$getFieldHtmlMethod( $v );
1309 $labelValue = trim( $value->getLabel() );
1310 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1311 $hasLabel = true;
1314 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1315 get_class( $value ) !== 'HTMLApiField'
1317 $hasUserVisibleFields = true;
1319 } elseif ( is_array( $value ) ) {
1320 $subsectionHasVisibleFields = false;
1321 $section =
1322 $this->displaySection( $value,
1323 "mw-htmlform-$key",
1324 "$fieldsetIDPrefix$key-",
1325 $subsectionHasVisibleFields );
1326 $legend = null;
1328 if ( $subsectionHasVisibleFields === true ) {
1329 // Display the section with various niceties.
1330 $hasUserVisibleFields = true;
1332 $legend = $this->getLegend( $key );
1334 if ( isset( $this->mSectionHeaders[$key] ) ) {
1335 $section = $this->mSectionHeaders[$key] . $section;
1337 if ( isset( $this->mSectionFooters[$key] ) ) {
1338 $section .= $this->mSectionFooters[$key];
1341 $attributes = array();
1342 if ( $fieldsetIDPrefix ) {
1343 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1345 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1346 } else {
1347 // Just return the inputs, nothing fancy.
1348 $subsectionHtml .= $section;
1353 if ( $displayFormat !== 'raw' ) {
1354 $classes = array();
1356 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1357 $classes[] = 'mw-htmlform-nolabel';
1360 $attribs = array(
1361 'class' => implode( ' ', $classes ),
1364 if ( $sectionName ) {
1365 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1368 if ( $displayFormat === 'table' ) {
1369 $html = Html::rawElement( 'table',
1370 $attribs,
1371 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1372 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1373 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1377 if ( $this->mSubSectionBeforeFields ) {
1378 return $subsectionHtml . "\n" . $html;
1379 } else {
1380 return $html . "\n" . $subsectionHtml;
1385 * Construct the form fields from the Descriptor array
1387 function loadData() {
1388 $fieldData = array();
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() );
1400 # Filter data.
1401 foreach ( $fieldData as $name => &$value ) {
1402 $field = $this->mFlatFields[$name];
1403 $value = $field->filter( $value, $this->mFlatFields );
1406 $this->mFieldData = $fieldData;
1410 * Stop a reset button being shown for this form
1412 * @param bool $suppressReset Set to false to re-enable the button again
1414 * @return HTMLForm $this for chaining calls (since 1.20)
1416 function suppressReset( $suppressReset = true ) {
1417 $this->mShowReset = !$suppressReset;
1419 return $this;
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.
1427 * @param array $data
1429 * @return array
1431 function filterDataForSubmit( $data ) {
1432 return $data;
1436 * Get a string to go in the "<legend>" of a section fieldset.
1437 * Override this if you want something more complicated.
1439 * @param string $key
1441 * @return string
1443 public function getLegend( $key ) {
1444 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
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.
1451 * @since 1.19
1453 * @param string|bool $action
1455 * @return HTMLForm $this for chaining calls (since 1.20)
1457 public function setAction( $action ) {
1458 $this->mAction = $action;
1460 return $this;
1464 * Get the value for the action attribute of the form.
1466 * @since 1.22
1468 * @return string
1470 public function getAction() {
1471 // If an action is alredy provided, return it
1472 if ( $this->mAction !== false ) {
1473 return $this->mAction;
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();
1486 return $this->getTitle()->getLocalURL();