Reset RequestContext between tests
[mediawiki.git] / includes / htmlform / HTMLForm.php
blob296de96f6e3330750aa6fd61a0848952ad6c5a0b
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 * 'options' -- associative array mapping labels to values.
54 * Some field types support multi-level arrays.
55 * 'options-messages' -- associative array mapping message keys to values.
56 * Some field types support multi-level arrays.
57 * 'options-message' -- message key to be parsed to extract the list of
58 * options (like 'ipbreason-dropdown').
59 * 'label-message' -- message key for a message to use as the label.
60 * can be an array of msg key and then parameters to
61 * the message.
62 * 'label' -- alternatively, a raw text message. Overridden by
63 * label-message
64 * 'help' -- message text for a message to use as a help text.
65 * 'help-message' -- message key for a message to use as a help text.
66 * can be an array of msg key and then parameters to
67 * the message.
68 * Overwrites 'help-messages' and 'help'.
69 * 'help-messages' -- array of message key. As above, each item can
70 * be an array of msg key and then parameters.
71 * Overwrites 'help'.
72 * 'required' -- passed through to the object, indicating that it
73 * is a required field.
74 * 'size' -- the length of text fields
75 * 'filter-callback -- a function name to give you the chance to
76 * massage the inputted value before it's processed.
77 * @see HTMLForm::filter()
78 * 'validation-callback' -- a function name to give you the chance
79 * to impose extra validation on the field input.
80 * @see HTMLForm::validate()
81 * 'name' -- By default, the 'name' attribute of the input field
82 * is "wp{$fieldname}". If you want a different name
83 * (eg one without the "wp" prefix), specify it here and
84 * it will be used without modification.
86 * Since 1.20, you can chain mutators to ease the form generation:
87 * @par Example:
88 * @code
89 * $form = new HTMLForm( $someFields );
90 * $form->setMethod( 'get' )
91 * ->setWrapperLegendMsg( 'message-key' )
92 * ->prepareForm()
93 * ->displayForm( '' );
94 * @endcode
95 * Note that you will have prepareForm and displayForm at the end. Other
96 * methods call done after that would simply not be part of the form :(
98 * @todo Document 'section' / 'subsection' stuff
100 class HTMLForm extends ContextSource {
101 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
102 public static $typeMappings = array(
103 'api' => 'HTMLApiField',
104 'text' => 'HTMLTextField',
105 'textarea' => 'HTMLTextAreaField',
106 'select' => 'HTMLSelectField',
107 'radio' => 'HTMLRadioField',
108 'multiselect' => 'HTMLMultiSelectField',
109 'check' => 'HTMLCheckField',
110 'toggle' => 'HTMLCheckField',
111 'int' => 'HTMLIntField',
112 'float' => 'HTMLFloatField',
113 'info' => 'HTMLInfoField',
114 'selectorother' => 'HTMLSelectOrOtherField',
115 'selectandother' => 'HTMLSelectAndOtherField',
116 'submit' => 'HTMLSubmitField',
117 'hidden' => 'HTMLHiddenField',
118 'edittools' => 'HTMLEditTools',
119 'checkmatrix' => 'HTMLCheckMatrix',
120 'cloner' => 'HTMLFormFieldCloner',
121 // HTMLTextField will output the correct type="" attribute automagically.
122 // There are about four zillion other HTML5 input types, like range, but
123 // we don't use those at the moment, so no point in adding all of them.
124 'email' => 'HTMLTextField',
125 'password' => 'HTMLTextField',
126 'url' => 'HTMLTextField',
129 public $mFieldData;
131 protected $mMessagePrefix;
133 /** @var HTMLFormField[] */
134 protected $mFlatFields;
136 protected $mFieldTree;
137 protected $mShowReset = false;
138 protected $mShowSubmit = true;
140 protected $mSubmitCallback;
141 protected $mValidationErrorMessage;
143 protected $mPre = '';
144 protected $mHeader = '';
145 protected $mFooter = '';
146 protected $mSectionHeaders = array();
147 protected $mSectionFooters = array();
148 protected $mPost = '';
149 protected $mId;
150 protected $mTableId = '';
152 protected $mSubmitID;
153 protected $mSubmitName;
154 protected $mSubmitText;
155 protected $mSubmitTooltip;
157 protected $mTitle;
158 protected $mMethod = 'post';
159 protected $mWasSubmitted = false;
162 * Form action URL. false means we will use the URL to set Title
163 * @since 1.19
164 * @var bool|string
166 protected $mAction = false;
168 protected $mUseMultipart = false;
169 protected $mHiddenFields = array();
170 protected $mButtons = array();
172 protected $mWrapperLegend = false;
175 * If true, sections that contain both fields and subsections will
176 * render their subsections before their fields.
178 * Subclasses may set this to false to render subsections after fields
179 * instead.
181 protected $mSubSectionBeforeFields = true;
184 * Format in which to display form. For viable options,
185 * @see $availableDisplayFormats
186 * @var string
188 protected $displayFormat = 'table';
191 * Available formats in which to display the form
192 * @var array
194 protected $availableDisplayFormats = array(
195 'table',
196 'div',
197 'raw',
198 'vform',
202 * Build a new HTMLForm from an array of field attributes
204 * @param array $descriptor Array of Field constructs, as described above
205 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
206 * Obviates the need to call $form->setTitle()
207 * @param string $messagePrefix A prefix to go in front of default messages
209 public function __construct( $descriptor, /*IContextSource*/ $context = null,
210 $messagePrefix = ''
212 if ( $context instanceof IContextSource ) {
213 $this->setContext( $context );
214 $this->mTitle = false; // We don't need them to set a title
215 $this->mMessagePrefix = $messagePrefix;
216 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
217 $this->mMessagePrefix = $messagePrefix;
218 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
219 // B/C since 1.18
220 // it's actually $messagePrefix
221 $this->mMessagePrefix = $context;
224 // Expand out into a tree.
225 $loadedDescriptor = array();
226 $this->mFlatFields = array();
228 foreach ( $descriptor as $fieldname => $info ) {
229 $section = isset( $info['section'] )
230 ? $info['section']
231 : '';
233 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
234 $this->mUseMultipart = true;
237 $field = self::loadInputFromParameters( $fieldname, $info );
238 // FIXME During field's construct, the parent form isn't available!
239 // could add a 'parent' name-value to $info, could add a third parameter.
240 $field->mParent = $this;
242 // vform gets too much space if empty labels generate HTML.
243 if ( $this->isVForm() ) {
244 $field->setShowEmptyLabel( false );
247 $setSection =& $loadedDescriptor;
248 if ( $section ) {
249 $sectionParts = explode( '/', $section );
251 while ( count( $sectionParts ) ) {
252 $newName = array_shift( $sectionParts );
254 if ( !isset( $setSection[$newName] ) ) {
255 $setSection[$newName] = array();
258 $setSection =& $setSection[$newName];
262 $setSection[$fieldname] = $field;
263 $this->mFlatFields[$fieldname] = $field;
266 $this->mFieldTree = $loadedDescriptor;
270 * Set format in which to display the form
272 * @param string $format The name of the format to use, must be one of
273 * $this->availableDisplayFormats
275 * @throws MWException
276 * @since 1.20
277 * @return HTMLForm $this for chaining calls (since 1.20)
279 public function setDisplayFormat( $format ) {
280 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
281 throw new MWException( 'Display format must be one of ' .
282 print_r( $this->availableDisplayFormats, true ) );
284 $this->displayFormat = $format;
286 return $this;
290 * Getter for displayFormat
291 * @since 1.20
292 * @return string
294 public function getDisplayFormat() {
295 return $this->displayFormat;
299 * Test if displayFormat is 'vform'
300 * @since 1.22
301 * @return bool
303 public function isVForm() {
304 return $this->displayFormat === 'vform';
308 * Get the HTMLFormField subclass for this descriptor.
310 * The descriptor can be passed either 'class' which is the name of
311 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
312 * This makes sure the 'class' is always set, and also is returned by
313 * this function for ease.
315 * @since 1.23
317 * @param string $fieldname Name of the field
318 * @param array $descriptor Input Descriptor, as described above
320 * @throws MWException
321 * @return string Name of a HTMLFormField subclass
323 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
324 if ( isset( $descriptor['class'] ) ) {
325 $class = $descriptor['class'];
326 } elseif ( isset( $descriptor['type'] ) ) {
327 $class = self::$typeMappings[$descriptor['type']];
328 $descriptor['class'] = $class;
329 } else {
330 $class = null;
333 if ( !$class ) {
334 throw new MWException( "Descriptor with no class for $fieldname: "
335 . print_r( $descriptor, true ) );
338 return $class;
342 * Initialise a new Object for the field
344 * @param string $fieldname Name of the field
345 * @param array $descriptor Input Descriptor, as described above
347 * @throws MWException
348 * @return HTMLFormField subclass
350 public static function loadInputFromParameters( $fieldname, $descriptor ) {
351 $class = self::getClassFromDescriptor( $fieldname, $descriptor );
353 $descriptor['fieldname'] = $fieldname;
355 # @todo This will throw a fatal error whenever someone try to use
356 # 'class' to feed a CSS class instead of 'cssclass'. Would be
357 # great to avoid the fatal error and show a nice error.
358 $obj = new $class( $descriptor );
360 return $obj;
364 * Prepare form for submission.
366 * @attention When doing method chaining, that should be the very last
367 * method call before displayForm().
369 * @throws MWException
370 * @return HTMLForm $this for chaining calls (since 1.20)
372 function prepareForm() {
373 # Check if we have the info we need
374 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
375 throw new MWException( "You must call setTitle() on an HTMLForm" );
378 # Load data from the request.
379 $this->loadData();
381 return $this;
385 * Try submitting, with edit token check first
386 * @return Status|bool
388 function tryAuthorizedSubmit() {
389 $result = false;
391 $submit = false;
392 if ( $this->getMethod() != 'post' ) {
393 $submit = true; // no session check needed
394 } elseif ( $this->getRequest()->wasPosted() ) {
395 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
396 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
397 // Session tokens for logged-out users have no security value.
398 // However, if the user gave one, check it in order to give a nice
399 // "session expired" error instead of "permission denied" or such.
400 $submit = $this->getUser()->matchEditToken( $editToken );
401 } else {
402 $submit = true;
406 if ( $submit ) {
407 $this->mWasSubmitted = true;
408 $result = $this->trySubmit();
411 return $result;
415 * The here's-one-I-made-earlier option: do the submission if
416 * posted, or display the form with or without funky validation
417 * errors
418 * @return bool|Status Whether submission was successful.
420 function show() {
421 $this->prepareForm();
423 $result = $this->tryAuthorizedSubmit();
424 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
425 return $result;
428 $this->displayForm( $result );
430 return false;
434 * Validate all the fields, and call the submission callback
435 * function if everything is kosher.
436 * @throws MWException
437 * @return mixed Bool true == Successful submission, Bool false
438 * == No submission attempted, anything else == Error to
439 * display.
441 function trySubmit() {
442 $this->mWasSubmitted = true;
444 # Check for cancelled submission
445 foreach ( $this->mFlatFields as $fieldname => $field ) {
446 if ( !empty( $field->mParams['nodata'] ) ) {
447 continue;
449 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
450 $this->mWasSubmitted = false;
451 return false;
455 # Check for validation
456 foreach ( $this->mFlatFields as $fieldname => $field ) {
457 if ( !empty( $field->mParams['nodata'] ) ) {
458 continue;
460 if ( $field->validate(
461 $this->mFieldData[$fieldname],
462 $this->mFieldData )
463 !== true
465 return isset( $this->mValidationErrorMessage )
466 ? $this->mValidationErrorMessage
467 : array( 'htmlform-invalid-input' );
471 $callback = $this->mSubmitCallback;
472 if ( !is_callable( $callback ) ) {
473 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
474 'setSubmitCallback() to set one.' );
477 $data = $this->filterDataForSubmit( $this->mFieldData );
479 $res = call_user_func( $callback, $data, $this );
480 if ( $res === false ) {
481 $this->mWasSubmitted = false;
484 return $res;
488 * Test whether the form was considered to have been submitted or not, i.e.
489 * whether the last call to tryAuthorizedSubmit or trySubmit returned
490 * non-false.
492 * This will return false until HTMLForm::tryAuthorizedSubmit or
493 * HTMLForm::trySubmit is called.
495 * @since 1.23
496 * @return bool
498 function wasSubmitted() {
499 return $this->mWasSubmitted;
503 * Set a callback to a function to do something with the form
504 * once it's been successfully validated.
506 * @param string $cb Function name. The function will be passed
507 * the output from HTMLForm::filterDataForSubmit, and must
508 * return Bool true on success, Bool false if no submission
509 * was attempted, or String HTML output to display on error.
511 * @return HTMLForm $this for chaining calls (since 1.20)
513 function setSubmitCallback( $cb ) {
514 $this->mSubmitCallback = $cb;
516 return $this;
520 * Set a message to display on a validation error.
522 * @param string|array $msg String or Array of valid inputs to wfMessage()
523 * (so each entry can be either a String or Array)
525 * @return HTMLForm $this for chaining calls (since 1.20)
527 function setValidationErrorMessage( $msg ) {
528 $this->mValidationErrorMessage = $msg;
530 return $this;
534 * Set the introductory message, overwriting any existing message.
536 * @param string $msg Complete text of message to display
538 * @return HTMLForm $this for chaining calls (since 1.20)
540 function setIntro( $msg ) {
541 $this->setPreText( $msg );
543 return $this;
547 * Set the introductory message, overwriting any existing message.
548 * @since 1.19
550 * @param string $msg Complete text of message to display
552 * @return HTMLForm $this for chaining calls (since 1.20)
554 function setPreText( $msg ) {
555 $this->mPre = $msg;
557 return $this;
561 * Add introductory text.
563 * @param string $msg Complete text of message to display
565 * @return HTMLForm $this for chaining calls (since 1.20)
567 function addPreText( $msg ) {
568 $this->mPre .= $msg;
570 return $this;
574 * Add header text, inside the form.
576 * @param string $msg Complete text of message to display
577 * @param string|null $section The section to add the header to
579 * @return HTMLForm $this for chaining calls (since 1.20)
581 function addHeaderText( $msg, $section = null ) {
582 if ( is_null( $section ) ) {
583 $this->mHeader .= $msg;
584 } else {
585 if ( !isset( $this->mSectionHeaders[$section] ) ) {
586 $this->mSectionHeaders[$section] = '';
588 $this->mSectionHeaders[$section] .= $msg;
591 return $this;
595 * Set header text, inside the form.
596 * @since 1.19
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 setHeaderText( $msg, $section = null ) {
604 if ( is_null( $section ) ) {
605 $this->mHeader = $msg;
606 } else {
607 $this->mSectionHeaders[$section] = $msg;
610 return $this;
614 * Add footer text, inside the form.
616 * @param string $msg complete text of message to display
617 * @param string|null $section The section to add the footer text to
619 * @return HTMLForm $this for chaining calls (since 1.20)
621 function addFooterText( $msg, $section = null ) {
622 if ( is_null( $section ) ) {
623 $this->mFooter .= $msg;
624 } else {
625 if ( !isset( $this->mSectionFooters[$section] ) ) {
626 $this->mSectionFooters[$section] = '';
628 $this->mSectionFooters[$section] .= $msg;
631 return $this;
635 * Set footer text, inside the form.
636 * @since 1.19
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 setFooterText( $msg, $section = null ) {
644 if ( is_null( $section ) ) {
645 $this->mFooter = $msg;
646 } else {
647 $this->mSectionFooters[$section] = $msg;
650 return $this;
654 * Add text to the end of the display.
656 * @param string $msg Complete text of message to display
658 * @return HTMLForm $this for chaining calls (since 1.20)
660 function addPostText( $msg ) {
661 $this->mPost .= $msg;
663 return $this;
667 * Set text at the end of the display.
669 * @param string $msg Complete text of message to display
671 * @return HTMLForm $this for chaining calls (since 1.20)
673 function setPostText( $msg ) {
674 $this->mPost = $msg;
676 return $this;
680 * Add a hidden field to the output
682 * @param string $name Field name. This will be used exactly as entered
683 * @param string $value Field value
684 * @param array $attribs
686 * @return HTMLForm $this for chaining calls (since 1.20)
688 public function addHiddenField( $name, $value, $attribs = array() ) {
689 $attribs += array( 'name' => $name );
690 $this->mHiddenFields[] = array( $value, $attribs );
692 return $this;
696 * Add an array of hidden fields to the output
698 * @since 1.22
700 * @param array $fields Associative array of fields to add;
701 * mapping names to their values
703 * @return HTMLForm $this for chaining calls
705 public function addHiddenFields( array $fields ) {
706 foreach ( $fields as $name => $value ) {
707 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
710 return $this;
714 * Add a button to the form
716 * @param string $name Field name.
717 * @param string $value Field value
718 * @param string $id DOM id for the button (default: null)
719 * @param array $attribs
721 * @return HTMLForm $this for chaining calls (since 1.20)
723 public function addButton( $name, $value, $id = null, $attribs = null ) {
724 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
726 return $this;
730 * Display the form (sending to the context's OutputPage object), with an
731 * appropriate error message or stack of messages, and any validation errors, etc.
733 * @attention You should call prepareForm() before calling this function.
734 * Moreover, when doing method chaining this should be the very last method
735 * call just after prepareForm().
737 * @param mixed $submitResult Mixed output from HTMLForm::trySubmit()
739 * @return Nothing, should be last call
741 function displayForm( $submitResult ) {
742 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
746 * Returns the raw HTML generated by the form
748 * @param mixed $submitResult Mixed output from HTMLForm::trySubmit()
750 * @return string
752 function getHTML( $submitResult ) {
753 # For good measure (it is the default)
754 $this->getOutput()->preventClickjacking();
755 $this->getOutput()->addModules( 'mediawiki.htmlform' );
756 if ( $this->isVForm() ) {
757 $this->getOutput()->addModuleStyles( array(
758 'mediawiki.ui',
759 'mediawiki.ui.button',
760 ) );
761 // @todo Should vertical form set setWrapperLegend( false )
762 // to hide ugly fieldsets?
765 $html = ''
766 . $this->getErrors( $submitResult )
767 . $this->mHeader
768 . $this->getBody()
769 . $this->getHiddenFields()
770 . $this->getButtons()
771 . $this->mFooter;
773 $html = $this->wrapForm( $html );
775 return '' . $this->mPre . $html . $this->mPost;
779 * Wrap the form innards in an actual "<form>" element
781 * @param string $html HTML contents to wrap.
783 * @return string Wrapped HTML.
785 function wrapForm( $html ) {
787 # Include a <fieldset> wrapper for style, if requested.
788 if ( $this->mWrapperLegend !== false ) {
789 $html = Xml::fieldset( $this->mWrapperLegend, $html );
791 # Use multipart/form-data
792 $encType = $this->mUseMultipart
793 ? 'multipart/form-data'
794 : 'application/x-www-form-urlencoded';
795 # Attributes
796 $attribs = array(
797 'action' => $this->getAction(),
798 'method' => $this->getMethod(),
799 'class' => array( 'visualClear' ),
800 'enctype' => $encType,
802 if ( !empty( $this->mId ) ) {
803 $attribs['id'] = $this->mId;
806 if ( $this->isVForm() ) {
807 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
810 return Html::rawElement( 'form', $attribs, $html );
814 * Get the hidden fields that should go inside the form.
815 * @return string HTML.
817 function getHiddenFields() {
818 global $wgArticlePath;
820 $html = '';
821 if ( $this->getMethod() == 'post' ) {
822 $html .= Html::hidden(
823 'wpEditToken',
824 $this->getUser()->getEditToken(),
825 array( 'id' => 'wpEditToken' )
826 ) . "\n";
827 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
830 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
831 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
834 foreach ( $this->mHiddenFields as $data ) {
835 list( $value, $attribs ) = $data;
836 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
839 return $html;
843 * Get the submit and (potentially) reset buttons.
844 * @return string HTML.
846 function getButtons() {
847 $buttons = '';
849 if ( $this->mShowSubmit ) {
850 $attribs = array();
852 if ( isset( $this->mSubmitID ) ) {
853 $attribs['id'] = $this->mSubmitID;
856 if ( isset( $this->mSubmitName ) ) {
857 $attribs['name'] = $this->mSubmitName;
860 if ( isset( $this->mSubmitTooltip ) ) {
861 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
864 $attribs['class'] = array( 'mw-htmlform-submit' );
866 if ( $this->isVForm() ) {
867 // mw-ui-block is necessary because the buttons aren't necessarily in an
868 // immediate child div of the vform.
869 // @todo Let client specify if the primary submit button is progressive or destructive
870 array_push(
871 $attribs['class'],
872 'mw-ui-button',
873 'mw-ui-big',
874 'mw-ui-constructive',
875 'mw-ui-block'
879 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
882 if ( $this->mShowReset ) {
883 $buttons .= Html::element(
884 'input',
885 array(
886 'type' => 'reset',
887 'value' => $this->msg( 'htmlform-reset' )->text()
889 ) . "\n";
892 foreach ( $this->mButtons as $button ) {
893 $attrs = array(
894 'type' => 'submit',
895 'name' => $button['name'],
896 'value' => $button['value']
899 if ( $button['attribs'] ) {
900 $attrs += $button['attribs'];
903 if ( isset( $button['id'] ) ) {
904 $attrs['id'] = $button['id'];
907 $buttons .= Html::element( 'input', $attrs ) . "\n";
910 $html = Html::rawElement( 'span',
911 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
913 // Buttons are top-level form elements in table and div layouts,
914 // but vform wants all elements inside divs to get spaced-out block
915 // styling.
916 if ( $this->mShowSubmit && $this->isVForm() ) {
917 $html = Html::rawElement( 'div', null, "\n$html" ) . "\n";
920 return $html;
924 * Get the whole body of the form.
925 * @return string
927 function getBody() {
928 return $this->displaySection( $this->mFieldTree, $this->mTableId );
932 * Format and display an error message stack.
934 * @param string|array|Status $errors
936 * @return string
938 function getErrors( $errors ) {
939 if ( $errors instanceof Status ) {
940 if ( $errors->isOK() ) {
941 $errorstr = '';
942 } else {
943 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
945 } elseif ( is_array( $errors ) ) {
946 $errorstr = $this->formatErrors( $errors );
947 } else {
948 $errorstr = $errors;
951 return $errorstr
952 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
953 : '';
957 * Format a stack of error messages into a single HTML string
959 * @param array $errors of message keys/values
961 * @return string HTML, a "<ul>" list of errors
963 public static function formatErrors( $errors ) {
964 $errorstr = '';
966 foreach ( $errors as $error ) {
967 if ( is_array( $error ) ) {
968 $msg = array_shift( $error );
969 } else {
970 $msg = $error;
971 $error = array();
974 $errorstr .= Html::rawElement(
975 'li',
976 array(),
977 wfMessage( $msg, $error )->parse()
981 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
983 return $errorstr;
987 * Set the text for the submit button
989 * @param string $t plaintext.
991 * @return HTMLForm $this for chaining calls (since 1.20)
993 function setSubmitText( $t ) {
994 $this->mSubmitText = $t;
996 return $this;
1000 * Set the text for the submit button to a message
1001 * @since 1.19
1003 * @param string $msg Message key
1005 * @return HTMLForm $this for chaining calls (since 1.20)
1007 public function setSubmitTextMsg( $msg ) {
1008 $this->setSubmitText( $this->msg( $msg )->text() );
1010 return $this;
1014 * Get the text for the submit button, either customised or a default.
1015 * @return string
1017 function getSubmitText() {
1018 return $this->mSubmitText
1019 ? $this->mSubmitText
1020 : $this->msg( 'htmlform-submit' )->text();
1024 * @param string $name Submit button name
1026 * @return HTMLForm $this for chaining calls (since 1.20)
1028 public function setSubmitName( $name ) {
1029 $this->mSubmitName = $name;
1031 return $this;
1035 * @param string $name Tooltip for the submit button
1037 * @return HTMLForm $this for chaining calls (since 1.20)
1039 public function setSubmitTooltip( $name ) {
1040 $this->mSubmitTooltip = $name;
1042 return $this;
1046 * Set the id for the submit button.
1048 * @param string $t
1050 * @todo FIXME: Integrity of $t is *not* validated
1051 * @return HTMLForm $this for chaining calls (since 1.20)
1053 function setSubmitID( $t ) {
1054 $this->mSubmitID = $t;
1056 return $this;
1060 * Stop a default submit button being shown for this form. This implies that an
1061 * alternate submit method must be provided manually.
1063 * @since 1.22
1065 * @param bool $suppressSubmit Set to false to re-enable the button again
1067 * @return HTMLForm $this for chaining calls
1069 function suppressDefaultSubmit( $suppressSubmit = true ) {
1070 $this->mShowSubmit = !$suppressSubmit;
1072 return $this;
1076 * Set the id of the \<table\> or outermost \<div\> element.
1078 * @since 1.22
1080 * @param string $id New value of the id attribute, or "" to remove
1082 * @return HTMLForm $this for chaining calls
1084 public function setTableId( $id ) {
1085 $this->mTableId = $id;
1087 return $this;
1091 * @param string $id DOM id for the form
1093 * @return HTMLForm $this for chaining calls (since 1.20)
1095 public function setId( $id ) {
1096 $this->mId = $id;
1098 return $this;
1102 * Prompt the whole form to be wrapped in a "<fieldset>", with
1103 * this text as its "<legend>" element.
1105 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1106 * false for no <legend>
1107 * Will be escaped
1109 * @return HTMLForm $this for chaining calls (since 1.20)
1111 public function setWrapperLegend( $legend ) {
1112 $this->mWrapperLegend = $legend;
1114 return $this;
1118 * Prompt the whole form to be wrapped in a "<fieldset>", with
1119 * this message as its "<legend>" element.
1120 * @since 1.19
1122 * @param string $msg Message key
1124 * @return HTMLForm $this for chaining calls (since 1.20)
1126 public function setWrapperLegendMsg( $msg ) {
1127 $this->setWrapperLegend( $this->msg( $msg )->text() );
1129 return $this;
1133 * Set the prefix for various default messages
1134 * @todo Currently only used for the "<fieldset>" legend on forms
1135 * with multiple sections; should be used elsewhere?
1137 * @param string $p
1139 * @return HTMLForm $this for chaining calls (since 1.20)
1141 function setMessagePrefix( $p ) {
1142 $this->mMessagePrefix = $p;
1144 return $this;
1148 * Set the title for form submission
1150 * @param Title $t Title of page the form is on/should be posted to
1152 * @return HTMLForm $this for chaining calls (since 1.20)
1154 function setTitle( $t ) {
1155 $this->mTitle = $t;
1157 return $this;
1161 * Get the title
1162 * @return Title
1164 function getTitle() {
1165 return $this->mTitle === false
1166 ? $this->getContext()->getTitle()
1167 : $this->mTitle;
1171 * Set the method used to submit the form
1173 * @param string $method
1175 * @return HTMLForm $this for chaining calls (since 1.20)
1177 public function setMethod( $method = 'post' ) {
1178 $this->mMethod = $method;
1180 return $this;
1183 public function getMethod() {
1184 return $this->mMethod;
1188 * @todo Document
1190 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1191 * objects).
1192 * @param string $sectionName ID attribute of the "<table>" tag for this
1193 * section, ignored if empty.
1194 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1195 * each subsection, ignored if empty.
1196 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1198 * @return string
1200 public function displaySection( $fields,
1201 $sectionName = '',
1202 $fieldsetIDPrefix = '',
1203 &$hasUserVisibleFields = false ) {
1204 $displayFormat = $this->getDisplayFormat();
1206 $html = '';
1207 $subsectionHtml = '';
1208 $hasLabel = false;
1210 switch ( $displayFormat ) {
1211 case 'table':
1212 $getFieldHtmlMethod = 'getTableRow';
1213 break;
1214 case 'vform':
1215 // Close enough to a div.
1216 $getFieldHtmlMethod = 'getDiv';
1217 break;
1218 default:
1219 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1222 foreach ( $fields as $key => $value ) {
1223 if ( $value instanceof HTMLFormField ) {
1224 $v = empty( $value->mParams['nodata'] )
1225 ? $this->mFieldData[$key]
1226 : $value->getDefault();
1227 $html .= $value->$getFieldHtmlMethod( $v );
1229 $labelValue = trim( $value->getLabel() );
1230 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1231 $hasLabel = true;
1234 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1235 get_class( $value ) !== 'HTMLApiField'
1237 $hasUserVisibleFields = true;
1239 } elseif ( is_array( $value ) ) {
1240 $subsectionHasVisibleFields = false;
1241 $section =
1242 $this->displaySection( $value,
1243 "mw-htmlform-$key",
1244 "$fieldsetIDPrefix$key-",
1245 $subsectionHasVisibleFields );
1246 $legend = null;
1248 if ( $subsectionHasVisibleFields === true ) {
1249 // Display the section with various niceties.
1250 $hasUserVisibleFields = true;
1252 $legend = $this->getLegend( $key );
1254 if ( isset( $this->mSectionHeaders[$key] ) ) {
1255 $section = $this->mSectionHeaders[$key] . $section;
1257 if ( isset( $this->mSectionFooters[$key] ) ) {
1258 $section .= $this->mSectionFooters[$key];
1261 $attributes = array();
1262 if ( $fieldsetIDPrefix ) {
1263 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1265 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1266 } else {
1267 // Just return the inputs, nothing fancy.
1268 $subsectionHtml .= $section;
1273 if ( $displayFormat !== 'raw' ) {
1274 $classes = array();
1276 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1277 $classes[] = 'mw-htmlform-nolabel';
1280 $attribs = array(
1281 'class' => implode( ' ', $classes ),
1284 if ( $sectionName ) {
1285 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1288 if ( $displayFormat === 'table' ) {
1289 $html = Html::rawElement( 'table',
1290 $attribs,
1291 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1292 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1293 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1297 if ( $this->mSubSectionBeforeFields ) {
1298 return $subsectionHtml . "\n" . $html;
1299 } else {
1300 return $html . "\n" . $subsectionHtml;
1305 * Construct the form fields from the Descriptor array
1307 function loadData() {
1308 $fieldData = array();
1310 foreach ( $this->mFlatFields as $fieldname => $field ) {
1311 if ( !empty( $field->mParams['nodata'] ) ) {
1312 continue;
1313 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1314 $fieldData[$fieldname] = $field->getDefault();
1315 } else {
1316 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1320 # Filter data.
1321 foreach ( $fieldData as $name => &$value ) {
1322 $field = $this->mFlatFields[$name];
1323 $value = $field->filter( $value, $this->mFlatFields );
1326 $this->mFieldData = $fieldData;
1330 * Stop a reset button being shown for this form
1332 * @param bool $suppressReset Set to false to re-enable the button again
1334 * @return HTMLForm $this for chaining calls (since 1.20)
1336 function suppressReset( $suppressReset = true ) {
1337 $this->mShowReset = !$suppressReset;
1339 return $this;
1343 * Overload this if you want to apply special filtration routines
1344 * to the form as a whole, after it's submitted but before it's
1345 * processed.
1347 * @param array $data
1349 * @return
1351 function filterDataForSubmit( $data ) {
1352 return $data;
1356 * Get a string to go in the "<legend>" of a section fieldset.
1357 * Override this if you want something more complicated.
1359 * @param string $key
1361 * @return string
1363 public function getLegend( $key ) {
1364 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1368 * Set the value for the action attribute of the form.
1369 * When set to false (which is the default state), the set title is used.
1371 * @since 1.19
1373 * @param string|bool $action
1375 * @return HTMLForm $this for chaining calls (since 1.20)
1377 public function setAction( $action ) {
1378 $this->mAction = $action;
1380 return $this;
1384 * Get the value for the action attribute of the form.
1386 * @since 1.22
1388 * @return string
1390 public function getAction() {
1391 global $wgScript, $wgArticlePath;
1393 // If an action is alredy provided, return it
1394 if ( $this->mAction !== false ) {
1395 return $this->mAction;
1398 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1399 // meaning that getLocalURL() would return something like "index.php?title=...".
1400 // As browser remove the query string before submitting GET forms,
1401 // it means that the title would be lost. In such case use $wgScript instead
1402 // and put title in an hidden field (see getHiddenFields()).
1403 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1404 return $wgScript;
1407 return $this->getTitle()->getLocalURL();