Support offsets in prefix searching
[mediawiki.git] / includes / htmlform / HTMLForm.php
blob62345b8cd48f3b7b2de22af273123dfccdb7b1f5
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 );
250 // FIXME During field's construct, the parent form isn't available!
251 // could add a 'parent' name-value to $info, could add a third parameter.
252 $field->mParent = $this;
254 // vform gets too much space if empty labels generate HTML.
255 if ( $this->isVForm() ) {
256 $field->setShowEmptyLabel( false );
259 $setSection =& $loadedDescriptor;
260 if ( $section ) {
261 $sectionParts = explode( '/', $section );
263 while ( count( $sectionParts ) ) {
264 $newName = array_shift( $sectionParts );
266 if ( !isset( $setSection[$newName] ) ) {
267 $setSection[$newName] = array();
270 $setSection =& $setSection[$newName];
274 $setSection[$fieldname] = $field;
275 $this->mFlatFields[$fieldname] = $field;
278 $this->mFieldTree = $loadedDescriptor;
282 * Set format in which to display the form
284 * @param string $format The name of the format to use, must be one of
285 * $this->availableDisplayFormats
287 * @throws MWException
288 * @since 1.20
289 * @return HTMLForm $this for chaining calls (since 1.20)
291 public function setDisplayFormat( $format ) {
292 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
293 throw new MWException( 'Display format must be one of ' .
294 print_r( $this->availableDisplayFormats, true ) );
296 $this->displayFormat = $format;
298 return $this;
302 * Getter for displayFormat
303 * @since 1.20
304 * @return string
306 public function getDisplayFormat() {
307 $format = $this->displayFormat;
308 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
309 $format = 'div';
311 return $format;
315 * Test if displayFormat is 'vform'
316 * @since 1.22
317 * @return bool
319 public function isVForm() {
320 return $this->displayFormat === 'vform';
324 * Get the HTMLFormField subclass for this descriptor.
326 * The descriptor can be passed either 'class' which is the name of
327 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
328 * This makes sure the 'class' is always set, and also is returned by
329 * this function for ease.
331 * @since 1.23
333 * @param string $fieldname Name of the field
334 * @param array $descriptor Input Descriptor, as described above
336 * @throws MWException
337 * @return string Name of a HTMLFormField subclass
339 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
340 if ( isset( $descriptor['class'] ) ) {
341 $class = $descriptor['class'];
342 } elseif ( isset( $descriptor['type'] ) ) {
343 $class = self::$typeMappings[$descriptor['type']];
344 $descriptor['class'] = $class;
345 } else {
346 $class = null;
349 if ( !$class ) {
350 throw new MWException( "Descriptor with no class for $fieldname: "
351 . print_r( $descriptor, true ) );
354 return $class;
358 * Initialise a new Object for the field
360 * @param string $fieldname Name of the field
361 * @param array $descriptor Input Descriptor, as described above
363 * @throws MWException
364 * @return HTMLFormField Instance of a subclass of HTMLFormField
366 public static function loadInputFromParameters( $fieldname, $descriptor ) {
367 $class = self::getClassFromDescriptor( $fieldname, $descriptor );
369 $descriptor['fieldname'] = $fieldname;
371 # @todo This will throw a fatal error whenever someone try to use
372 # 'class' to feed a CSS class instead of 'cssclass'. Would be
373 # great to avoid the fatal error and show a nice error.
374 $obj = new $class( $descriptor );
376 return $obj;
380 * Prepare form for submission.
382 * @attention When doing method chaining, that should be the very last
383 * method call before displayForm().
385 * @throws MWException
386 * @return HTMLForm $this for chaining calls (since 1.20)
388 function prepareForm() {
389 # Check if we have the info we need
390 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
391 throw new MWException( "You must call setTitle() on an HTMLForm" );
394 # Load data from the request.
395 $this->loadData();
397 return $this;
401 * Try submitting, with edit token check first
402 * @return Status|bool
404 function tryAuthorizedSubmit() {
405 $result = false;
407 $submit = false;
408 if ( $this->getMethod() != 'post' ) {
409 $submit = true; // no session check needed
410 } elseif ( $this->getRequest()->wasPosted() ) {
411 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
412 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
413 // Session tokens for logged-out users have no security value.
414 // However, if the user gave one, check it in order to give a nice
415 // "session expired" error instead of "permission denied" or such.
416 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
417 } else {
418 $submit = true;
422 if ( $submit ) {
423 $this->mWasSubmitted = true;
424 $result = $this->trySubmit();
427 return $result;
431 * The here's-one-I-made-earlier option: do the submission if
432 * posted, or display the form with or without funky validation
433 * errors
434 * @return bool|Status Whether submission was successful.
436 function show() {
437 $this->prepareForm();
439 $result = $this->tryAuthorizedSubmit();
440 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
441 return $result;
444 $this->displayForm( $result );
446 return false;
450 * Validate all the fields, and call the submission callback
451 * function if everything is kosher.
452 * @throws MWException
453 * @return bool|string|array|Status
454 * - Bool true or a good Status object indicates success,
455 * - Bool false indicates no submission was attempted,
456 * - Anything else indicates failure. The value may be a fatal Status
457 * object, an HTML string, or an array of arrays (message keys and
458 * params) or strings (message keys)
460 function trySubmit() {
461 $this->mWasSubmitted = true;
463 # Check for cancelled submission
464 foreach ( $this->mFlatFields as $fieldname => $field ) {
465 if ( !empty( $field->mParams['nodata'] ) ) {
466 continue;
468 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
469 $this->mWasSubmitted = false;
470 return false;
474 # Check for validation
475 foreach ( $this->mFlatFields as $fieldname => $field ) {
476 if ( !empty( $field->mParams['nodata'] ) ) {
477 continue;
479 if ( $field->isHidden( $this->mFieldData ) ) {
480 continue;
482 if ( $field->validate(
483 $this->mFieldData[$fieldname],
484 $this->mFieldData )
485 !== true
487 return isset( $this->mValidationErrorMessage )
488 ? $this->mValidationErrorMessage
489 : array( 'htmlform-invalid-input' );
493 $callback = $this->mSubmitCallback;
494 if ( !is_callable( $callback ) ) {
495 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
496 'setSubmitCallback() to set one.' );
499 $data = $this->filterDataForSubmit( $this->mFieldData );
501 $res = call_user_func( $callback, $data, $this );
502 if ( $res === false ) {
503 $this->mWasSubmitted = false;
506 return $res;
510 * Test whether the form was considered to have been submitted or not, i.e.
511 * whether the last call to tryAuthorizedSubmit or trySubmit returned
512 * non-false.
514 * This will return false until HTMLForm::tryAuthorizedSubmit or
515 * HTMLForm::trySubmit is called.
517 * @since 1.23
518 * @return bool
520 function wasSubmitted() {
521 return $this->mWasSubmitted;
525 * Set a callback to a function to do something with the form
526 * once it's been successfully validated.
528 * @param callable $cb The function will be passed the output from
529 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
530 * return as documented for HTMLForm::trySubmit
532 * @return HTMLForm $this for chaining calls (since 1.20)
534 function setSubmitCallback( $cb ) {
535 $this->mSubmitCallback = $cb;
537 return $this;
541 * Set a message to display on a validation error.
543 * @param string|array $msg String or Array of valid inputs to wfMessage()
544 * (so each entry can be either a String or Array)
546 * @return HTMLForm $this for chaining calls (since 1.20)
548 function setValidationErrorMessage( $msg ) {
549 $this->mValidationErrorMessage = $msg;
551 return $this;
555 * Set the introductory message, overwriting any existing message.
557 * @param string $msg Complete text of message to display
559 * @return HTMLForm $this for chaining calls (since 1.20)
561 function setIntro( $msg ) {
562 $this->setPreText( $msg );
564 return $this;
568 * Set the introductory message, overwriting any existing message.
569 * @since 1.19
571 * @param string $msg Complete text of message to display
573 * @return HTMLForm $this for chaining calls (since 1.20)
575 function setPreText( $msg ) {
576 $this->mPre = $msg;
578 return $this;
582 * Add introductory text.
584 * @param string $msg Complete text of message to display
586 * @return HTMLForm $this for chaining calls (since 1.20)
588 function addPreText( $msg ) {
589 $this->mPre .= $msg;
591 return $this;
595 * Add header text, inside the form.
597 * @param string $msg Complete text of message to display
598 * @param string|null $section The section to add the header to
600 * @return HTMLForm $this for chaining calls (since 1.20)
602 function addHeaderText( $msg, $section = null ) {
603 if ( is_null( $section ) ) {
604 $this->mHeader .= $msg;
605 } else {
606 if ( !isset( $this->mSectionHeaders[$section] ) ) {
607 $this->mSectionHeaders[$section] = '';
609 $this->mSectionHeaders[$section] .= $msg;
612 return $this;
616 * Set header text, inside the form.
617 * @since 1.19
619 * @param string $msg Complete text of message to display
620 * @param string|null $section The section to add the header to
622 * @return HTMLForm $this for chaining calls (since 1.20)
624 function setHeaderText( $msg, $section = null ) {
625 if ( is_null( $section ) ) {
626 $this->mHeader = $msg;
627 } else {
628 $this->mSectionHeaders[$section] = $msg;
631 return $this;
635 * Add footer text, inside the form.
637 * @param string $msg Complete text of message to display
638 * @param string|null $section The section to add the footer text to
640 * @return HTMLForm $this for chaining calls (since 1.20)
642 function addFooterText( $msg, $section = null ) {
643 if ( is_null( $section ) ) {
644 $this->mFooter .= $msg;
645 } else {
646 if ( !isset( $this->mSectionFooters[$section] ) ) {
647 $this->mSectionFooters[$section] = '';
649 $this->mSectionFooters[$section] .= $msg;
652 return $this;
656 * Set footer text, inside the form.
657 * @since 1.19
659 * @param string $msg Complete text of message to display
660 * @param string|null $section The section to add the footer text to
662 * @return HTMLForm $this for chaining calls (since 1.20)
664 function setFooterText( $msg, $section = null ) {
665 if ( is_null( $section ) ) {
666 $this->mFooter = $msg;
667 } else {
668 $this->mSectionFooters[$section] = $msg;
671 return $this;
675 * Add text to the end of the display.
677 * @param string $msg Complete text of message to display
679 * @return HTMLForm $this for chaining calls (since 1.20)
681 function addPostText( $msg ) {
682 $this->mPost .= $msg;
684 return $this;
688 * Set text at the end of the display.
690 * @param string $msg Complete text of message to display
692 * @return HTMLForm $this for chaining calls (since 1.20)
694 function setPostText( $msg ) {
695 $this->mPost = $msg;
697 return $this;
701 * Add a hidden field to the output
703 * @param string $name Field name. This will be used exactly as entered
704 * @param string $value Field value
705 * @param array $attribs
707 * @return HTMLForm $this for chaining calls (since 1.20)
709 public function addHiddenField( $name, $value, $attribs = array() ) {
710 $attribs += array( 'name' => $name );
711 $this->mHiddenFields[] = array( $value, $attribs );
713 return $this;
717 * Add an array of hidden fields to the output
719 * @since 1.22
721 * @param array $fields Associative array of fields to add;
722 * mapping names to their values
724 * @return HTMLForm $this for chaining calls
726 public function addHiddenFields( array $fields ) {
727 foreach ( $fields as $name => $value ) {
728 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
731 return $this;
735 * Add a button to the form
737 * @param string $name Field name.
738 * @param string $value Field value
739 * @param string $id DOM id for the button (default: null)
740 * @param array $attribs
742 * @return HTMLForm $this for chaining calls (since 1.20)
744 public function addButton( $name, $value, $id = null, $attribs = null ) {
745 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
747 return $this;
751 * Set the salt for the edit token.
753 * Only useful when the method is "post".
755 * @since 1.24
756 * @param string|array $salt Salt to use
757 * @return HTMLForm $this For chaining calls
759 public function setTokenSalt( $salt ) {
760 $this->mTokenSalt = $salt;
762 return $this;
766 * Display the form (sending to the context's OutputPage object), with an
767 * appropriate error message or stack of messages, and any validation errors, etc.
769 * @attention You should call prepareForm() before calling this function.
770 * Moreover, when doing method chaining this should be the very last method
771 * call just after prepareForm().
773 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
775 * @return void Nothing, should be last call
777 function displayForm( $submitResult ) {
778 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
782 * Returns the raw HTML generated by the form
784 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
786 * @return string
788 function getHTML( $submitResult ) {
789 # For good measure (it is the default)
790 $this->getOutput()->preventClickjacking();
791 $this->getOutput()->addModules( 'mediawiki.htmlform' );
792 if ( $this->isVForm() ) {
793 // This is required for VForm HTMLForms that use that style regardless
794 // of wgUseMediaWikiUIEverywhere (since they pre-date it).
795 // When wgUseMediaWikiUIEverywhere is removed, this should be consolidated
796 // with the addModuleStyles in SpecialPage->setHeaders.
797 $this->getOutput()->addModuleStyles( array(
798 'mediawiki.ui',
799 'mediawiki.ui.button',
800 'mediawiki.ui.input',
801 ) );
802 // @todo Should vertical form set setWrapperLegend( false )
803 // to hide ugly fieldsets?
806 $html = ''
807 . $this->getErrors( $submitResult )
808 . $this->mHeader
809 . $this->getBody()
810 . $this->getHiddenFields()
811 . $this->getButtons()
812 . $this->mFooter;
814 $html = $this->wrapForm( $html );
816 return '' . $this->mPre . $html . $this->mPost;
820 * Wrap the form innards in an actual "<form>" element
822 * @param string $html HTML contents to wrap.
824 * @return string Wrapped HTML.
826 function wrapForm( $html ) {
828 # Include a <fieldset> wrapper for style, if requested.
829 if ( $this->mWrapperLegend !== false ) {
830 $html = Xml::fieldset( $this->mWrapperLegend, $html );
832 # Use multipart/form-data
833 $encType = $this->mUseMultipart
834 ? 'multipart/form-data'
835 : 'application/x-www-form-urlencoded';
836 # Attributes
837 $attribs = array(
838 'action' => $this->getAction(),
839 'method' => $this->getMethod(),
840 'class' => array( 'visualClear' ),
841 'enctype' => $encType,
843 if ( !empty( $this->mId ) ) {
844 $attribs['id'] = $this->mId;
847 if ( $this->isVForm() ) {
848 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
851 return Html::rawElement( 'form', $attribs, $html );
855 * Get the hidden fields that should go inside the form.
856 * @return string HTML.
858 function getHiddenFields() {
859 $html = '';
860 if ( $this->getMethod() == 'post' ) {
861 $html .= Html::hidden(
862 'wpEditToken',
863 $this->getUser()->getEditToken( $this->mTokenSalt ),
864 array( 'id' => 'wpEditToken' )
865 ) . "\n";
866 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
869 $articlePath = $this->getConfig()->get( 'ArticlePath' );
870 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
871 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
874 foreach ( $this->mHiddenFields as $data ) {
875 list( $value, $attribs ) = $data;
876 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
879 return $html;
883 * Get the submit and (potentially) reset buttons.
884 * @return string HTML.
886 function getButtons() {
887 $buttons = '';
888 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
890 if ( $this->mShowSubmit ) {
891 $attribs = array();
893 if ( isset( $this->mSubmitID ) ) {
894 $attribs['id'] = $this->mSubmitID;
897 if ( isset( $this->mSubmitName ) ) {
898 $attribs['name'] = $this->mSubmitName;
901 if ( isset( $this->mSubmitTooltip ) ) {
902 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
905 $attribs['class'] = array( 'mw-htmlform-submit' );
907 if ( $this->isVForm() || $useMediaWikiUIEverywhere ) {
908 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass );
911 if ( $this->isVForm() ) {
912 // mw-ui-block is necessary because the buttons aren't necessarily in an
913 // immediate child div of the vform.
914 // @todo Let client specify if the primary submit button is progressive or destructive
915 array_push(
916 $attribs['class'],
917 'mw-ui-big',
918 'mw-ui-block'
922 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
925 if ( $this->mShowReset ) {
926 $buttons .= Html::element(
927 'input',
928 array(
929 'type' => 'reset',
930 'value' => $this->msg( 'htmlform-reset' )->text()
932 ) . "\n";
935 foreach ( $this->mButtons as $button ) {
936 $attrs = array(
937 'type' => 'submit',
938 'name' => $button['name'],
939 'value' => $button['value']
942 if ( $button['attribs'] ) {
943 $attrs += $button['attribs'];
946 if ( isset( $button['id'] ) ) {
947 $attrs['id'] = $button['id'];
950 if ( $this->isVForm() || $useMediaWikiUIEverywhere ) {
951 if ( isset( $attrs['class'] ) ) {
952 $attrs['class'] .= ' mw-ui-button';
953 } else {
954 $attrs['class'] = 'mw-ui-button';
956 if ( $this->isVForm() ) {
957 $attrs['class'] .= ' mw-ui-big mw-ui-block';
961 $buttons .= Html::element( 'input', $attrs ) . "\n";
964 $html = Html::rawElement( 'span',
965 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
967 // Buttons are top-level form elements in table and div layouts,
968 // but vform wants all elements inside divs to get spaced-out block
969 // styling.
970 if ( $this->mShowSubmit && $this->isVForm() ) {
971 $html = Html::rawElement( 'div', null, "\n$html" ) . "\n";
974 return $html;
978 * Get the whole body of the form.
979 * @return string
981 function getBody() {
982 return $this->displaySection( $this->mFieldTree, $this->mTableId );
986 * Format and display an error message stack.
988 * @param string|array|Status $errors
990 * @return string
992 function getErrors( $errors ) {
993 if ( $errors instanceof Status ) {
994 if ( $errors->isOK() ) {
995 $errorstr = '';
996 } else {
997 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
999 } elseif ( is_array( $errors ) ) {
1000 $errorstr = $this->formatErrors( $errors );
1001 } else {
1002 $errorstr = $errors;
1005 return $errorstr
1006 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1007 : '';
1011 * Format a stack of error messages into a single HTML string
1013 * @param array $errors Array of message keys/values
1015 * @return string HTML, a "<ul>" list of errors
1017 public static function formatErrors( $errors ) {
1018 $errorstr = '';
1020 foreach ( $errors as $error ) {
1021 if ( is_array( $error ) ) {
1022 $msg = array_shift( $error );
1023 } else {
1024 $msg = $error;
1025 $error = array();
1028 $errorstr .= Html::rawElement(
1029 'li',
1030 array(),
1031 wfMessage( $msg, $error )->parse()
1035 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1037 return $errorstr;
1041 * Set the text for the submit button
1043 * @param string $t Plaintext
1045 * @return HTMLForm $this for chaining calls (since 1.20)
1047 function setSubmitText( $t ) {
1048 $this->mSubmitText = $t;
1050 return $this;
1054 * Identify that the submit button in the form has a destructive action
1055 * @since 1.24
1057 public function setSubmitDestructive() {
1058 $this->mSubmitModifierClass = 'mw-ui-destructive';
1062 * Identify that the submit button in the form has a progressive action
1063 * @since 1.25
1065 public function setSubmitProgressive() {
1066 $this->mSubmitModifierClass = 'mw-ui-progressive';
1070 * Set the text for the submit button to a message
1071 * @since 1.19
1073 * @param string|Message $msg Message key or Message object
1075 * @return HTMLForm $this for chaining calls (since 1.20)
1077 public function setSubmitTextMsg( $msg ) {
1078 if ( !$msg instanceof Message ) {
1079 $msg = $this->msg( $msg );
1081 $this->setSubmitText( $msg->text() );
1083 return $this;
1087 * Get the text for the submit button, either customised or a default.
1088 * @return string
1090 function getSubmitText() {
1091 return $this->mSubmitText
1092 ? $this->mSubmitText
1093 : $this->msg( 'htmlform-submit' )->text();
1097 * @param string $name Submit button name
1099 * @return HTMLForm $this for chaining calls (since 1.20)
1101 public function setSubmitName( $name ) {
1102 $this->mSubmitName = $name;
1104 return $this;
1108 * @param string $name Tooltip for the submit button
1110 * @return HTMLForm $this for chaining calls (since 1.20)
1112 public function setSubmitTooltip( $name ) {
1113 $this->mSubmitTooltip = $name;
1115 return $this;
1119 * Set the id for the submit button.
1121 * @param string $t
1123 * @todo FIXME: Integrity of $t is *not* validated
1124 * @return HTMLForm $this for chaining calls (since 1.20)
1126 function setSubmitID( $t ) {
1127 $this->mSubmitID = $t;
1129 return $this;
1133 * Stop a default submit button being shown for this form. This implies that an
1134 * alternate submit method must be provided manually.
1136 * @since 1.22
1138 * @param bool $suppressSubmit Set to false to re-enable the button again
1140 * @return HTMLForm $this for chaining calls
1142 function suppressDefaultSubmit( $suppressSubmit = true ) {
1143 $this->mShowSubmit = !$suppressSubmit;
1145 return $this;
1149 * Set the id of the \<table\> or outermost \<div\> element.
1151 * @since 1.22
1153 * @param string $id New value of the id attribute, or "" to remove
1155 * @return HTMLForm $this for chaining calls
1157 public function setTableId( $id ) {
1158 $this->mTableId = $id;
1160 return $this;
1164 * @param string $id DOM id for the form
1166 * @return HTMLForm $this for chaining calls (since 1.20)
1168 public function setId( $id ) {
1169 $this->mId = $id;
1171 return $this;
1175 * Prompt the whole form to be wrapped in a "<fieldset>", with
1176 * this text as its "<legend>" element.
1178 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1179 * false for no <legend>
1180 * Will be escaped
1182 * @return HTMLForm $this for chaining calls (since 1.20)
1184 public function setWrapperLegend( $legend ) {
1185 $this->mWrapperLegend = $legend;
1187 return $this;
1191 * Prompt the whole form to be wrapped in a "<fieldset>", with
1192 * this message as its "<legend>" element.
1193 * @since 1.19
1195 * @param string|Message $msg Message key or Message object
1197 * @return HTMLForm $this for chaining calls (since 1.20)
1199 public function setWrapperLegendMsg( $msg ) {
1200 if ( !$msg instanceof Message ) {
1201 $msg = $this->msg( $msg );
1203 $this->setWrapperLegend( $msg->text() );
1205 return $this;
1209 * Set the prefix for various default messages
1210 * @todo Currently only used for the "<fieldset>" legend on forms
1211 * with multiple sections; should be used elsewhere?
1213 * @param string $p
1215 * @return HTMLForm $this for chaining calls (since 1.20)
1217 function setMessagePrefix( $p ) {
1218 $this->mMessagePrefix = $p;
1220 return $this;
1224 * Set the title for form submission
1226 * @param Title $t Title of page the form is on/should be posted to
1228 * @return HTMLForm $this for chaining calls (since 1.20)
1230 function setTitle( $t ) {
1231 $this->mTitle = $t;
1233 return $this;
1237 * Get the title
1238 * @return Title
1240 function getTitle() {
1241 return $this->mTitle === false
1242 ? $this->getContext()->getTitle()
1243 : $this->mTitle;
1247 * Set the method used to submit the form
1249 * @param string $method
1251 * @return HTMLForm $this for chaining calls (since 1.20)
1253 public function setMethod( $method = 'post' ) {
1254 $this->mMethod = $method;
1256 return $this;
1259 public function getMethod() {
1260 return $this->mMethod;
1264 * @todo Document
1266 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1267 * objects).
1268 * @param string $sectionName ID attribute of the "<table>" tag for this
1269 * section, ignored if empty.
1270 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1271 * each subsection, ignored if empty.
1272 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1274 * @return string
1276 public function displaySection( $fields,
1277 $sectionName = '',
1278 $fieldsetIDPrefix = '',
1279 &$hasUserVisibleFields = false ) {
1280 $displayFormat = $this->getDisplayFormat();
1282 $html = '';
1283 $subsectionHtml = '';
1284 $hasLabel = false;
1286 switch ( $displayFormat ) {
1287 case 'table':
1288 $getFieldHtmlMethod = 'getTableRow';
1289 break;
1290 case 'vform':
1291 // Close enough to a div.
1292 $getFieldHtmlMethod = 'getDiv';
1293 break;
1294 case 'div':
1295 $getFieldHtmlMethod = 'getDiv';
1296 break;
1297 default:
1298 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1301 foreach ( $fields as $key => $value ) {
1302 if ( $value instanceof HTMLFormField ) {
1303 $v = empty( $value->mParams['nodata'] )
1304 ? $this->mFieldData[$key]
1305 : $value->getDefault();
1306 $html .= $value->$getFieldHtmlMethod( $v );
1308 $labelValue = trim( $value->getLabel() );
1309 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1310 $hasLabel = true;
1313 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1314 get_class( $value ) !== 'HTMLApiField'
1316 $hasUserVisibleFields = true;
1318 } elseif ( is_array( $value ) ) {
1319 $subsectionHasVisibleFields = false;
1320 $section =
1321 $this->displaySection( $value,
1322 "mw-htmlform-$key",
1323 "$fieldsetIDPrefix$key-",
1324 $subsectionHasVisibleFields );
1325 $legend = null;
1327 if ( $subsectionHasVisibleFields === true ) {
1328 // Display the section with various niceties.
1329 $hasUserVisibleFields = true;
1331 $legend = $this->getLegend( $key );
1333 if ( isset( $this->mSectionHeaders[$key] ) ) {
1334 $section = $this->mSectionHeaders[$key] . $section;
1336 if ( isset( $this->mSectionFooters[$key] ) ) {
1337 $section .= $this->mSectionFooters[$key];
1340 $attributes = array();
1341 if ( $fieldsetIDPrefix ) {
1342 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1344 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1345 } else {
1346 // Just return the inputs, nothing fancy.
1347 $subsectionHtml .= $section;
1352 if ( $displayFormat !== 'raw' ) {
1353 $classes = array();
1355 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1356 $classes[] = 'mw-htmlform-nolabel';
1359 $attribs = array(
1360 'class' => implode( ' ', $classes ),
1363 if ( $sectionName ) {
1364 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1367 if ( $displayFormat === 'table' ) {
1368 $html = Html::rawElement( 'table',
1369 $attribs,
1370 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1371 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1372 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1376 if ( $this->mSubSectionBeforeFields ) {
1377 return $subsectionHtml . "\n" . $html;
1378 } else {
1379 return $html . "\n" . $subsectionHtml;
1384 * Construct the form fields from the Descriptor array
1386 function loadData() {
1387 $fieldData = array();
1389 foreach ( $this->mFlatFields as $fieldname => $field ) {
1390 if ( !empty( $field->mParams['nodata'] ) ) {
1391 continue;
1392 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1393 $fieldData[$fieldname] = $field->getDefault();
1394 } else {
1395 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1399 # Filter data.
1400 foreach ( $fieldData as $name => &$value ) {
1401 $field = $this->mFlatFields[$name];
1402 $value = $field->filter( $value, $this->mFlatFields );
1405 $this->mFieldData = $fieldData;
1409 * Stop a reset button being shown for this form
1411 * @param bool $suppressReset Set to false to re-enable the button again
1413 * @return HTMLForm $this for chaining calls (since 1.20)
1415 function suppressReset( $suppressReset = true ) {
1416 $this->mShowReset = !$suppressReset;
1418 return $this;
1422 * Overload this if you want to apply special filtration routines
1423 * to the form as a whole, after it's submitted but before it's
1424 * processed.
1426 * @param array $data
1428 * @return array
1430 function filterDataForSubmit( $data ) {
1431 return $data;
1435 * Get a string to go in the "<legend>" of a section fieldset.
1436 * Override this if you want something more complicated.
1438 * @param string $key
1440 * @return string
1442 public function getLegend( $key ) {
1443 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1447 * Set the value for the action attribute of the form.
1448 * When set to false (which is the default state), the set title is used.
1450 * @since 1.19
1452 * @param string|bool $action
1454 * @return HTMLForm $this for chaining calls (since 1.20)
1456 public function setAction( $action ) {
1457 $this->mAction = $action;
1459 return $this;
1463 * Get the value for the action attribute of the form.
1465 * @since 1.22
1467 * @return string
1469 public function getAction() {
1470 // If an action is alredy provided, return it
1471 if ( $this->mAction !== false ) {
1472 return $this->mAction;
1475 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1476 // Check whether we are in GET mode and the ArticlePath contains a "?"
1477 // meaning that getLocalURL() would return something like "index.php?title=...".
1478 // As browser remove the query string before submitting GET forms,
1479 // it means that the title would be lost. In such case use wfScript() instead
1480 // and put title in an hidden field (see getHiddenFields()).
1481 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1482 return wfScript();
1485 return $this->getTitle()->getLocalURL();