Merge "Refactor Watchlist code so mobile can be more consistent"
[mediawiki.git] / includes / htmlform / HTMLForm.php
blob6cf8d0a7eb389428c5f0a85547b5174b51426ea8
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 'check' => 'HTMLCheckField',
111 'toggle' => 'HTMLCheckField',
112 'int' => 'HTMLIntField',
113 'float' => 'HTMLFloatField',
114 'info' => 'HTMLInfoField',
115 'selectorother' => 'HTMLSelectOrOtherField',
116 'selectandother' => 'HTMLSelectAndOtherField',
117 'submit' => 'HTMLSubmitField',
118 'hidden' => 'HTMLHiddenField',
119 'edittools' => 'HTMLEditTools',
120 'checkmatrix' => 'HTMLCheckMatrix',
121 'cloner' => 'HTMLFormFieldCloner',
122 // HTMLTextField will output the correct type="" attribute automagically.
123 // There are about four zillion other HTML5 input types, like range, but
124 // we don't use those at the moment, so no point in adding all of them.
125 'email' => 'HTMLTextField',
126 'password' => 'HTMLTextField',
127 'url' => 'HTMLTextField',
130 public $mFieldData;
132 protected $mMessagePrefix;
134 /** @var HTMLFormField[] */
135 protected $mFlatFields;
137 protected $mFieldTree;
138 protected $mShowReset = false;
139 protected $mShowSubmit = true;
141 protected $mSubmitCallback;
142 protected $mValidationErrorMessage;
144 protected $mPre = '';
145 protected $mHeader = '';
146 protected $mFooter = '';
147 protected $mSectionHeaders = array();
148 protected $mSectionFooters = array();
149 protected $mPost = '';
150 protected $mId;
151 protected $mTableId = '';
153 protected $mSubmitID;
154 protected $mSubmitName;
155 protected $mSubmitText;
156 protected $mSubmitTooltip;
158 protected $mTitle;
159 protected $mMethod = 'post';
160 protected $mWasSubmitted = false;
163 * Form action URL. false means we will use the URL to set Title
164 * @since 1.19
165 * @var bool|string
167 protected $mAction = false;
169 protected $mUseMultipart = false;
170 protected $mHiddenFields = array();
171 protected $mButtons = array();
173 protected $mWrapperLegend = false;
176 * Salt for the edit token.
177 * @var string|array
179 protected $mTokenSalt = '';
182 * If true, sections that contain both fields and subsections will
183 * render their subsections before their fields.
185 * Subclasses may set this to false to render subsections after fields
186 * instead.
188 protected $mSubSectionBeforeFields = true;
191 * Format in which to display form. For viable options,
192 * @see $availableDisplayFormats
193 * @var string
195 protected $displayFormat = 'table';
198 * Available formats in which to display the form
199 * @var array
201 protected $availableDisplayFormats = array(
202 'table',
203 'div',
204 'raw',
205 'vform',
209 * Build a new HTMLForm from an array of field attributes
211 * @param array $descriptor Array of Field constructs, as described above
212 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
213 * Obviates the need to call $form->setTitle()
214 * @param string $messagePrefix A prefix to go in front of default messages
216 public function __construct( $descriptor, /*IContextSource*/ $context = null,
217 $messagePrefix = ''
219 if ( $context instanceof IContextSource ) {
220 $this->setContext( $context );
221 $this->mTitle = false; // We don't need them to set a title
222 $this->mMessagePrefix = $messagePrefix;
223 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
224 $this->mMessagePrefix = $messagePrefix;
225 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
226 // B/C since 1.18
227 // it's actually $messagePrefix
228 $this->mMessagePrefix = $context;
231 // Expand out into a tree.
232 $loadedDescriptor = array();
233 $this->mFlatFields = array();
235 foreach ( $descriptor as $fieldname => $info ) {
236 $section = isset( $info['section'] )
237 ? $info['section']
238 : '';
240 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
241 $this->mUseMultipart = true;
244 $field = self::loadInputFromParameters( $fieldname, $info );
245 // FIXME During field's construct, the parent form isn't available!
246 // could add a 'parent' name-value to $info, could add a third parameter.
247 $field->mParent = $this;
249 // vform gets too much space if empty labels generate HTML.
250 if ( $this->isVForm() ) {
251 $field->setShowEmptyLabel( false );
254 $setSection =& $loadedDescriptor;
255 if ( $section ) {
256 $sectionParts = explode( '/', $section );
258 while ( count( $sectionParts ) ) {
259 $newName = array_shift( $sectionParts );
261 if ( !isset( $setSection[$newName] ) ) {
262 $setSection[$newName] = array();
265 $setSection =& $setSection[$newName];
269 $setSection[$fieldname] = $field;
270 $this->mFlatFields[$fieldname] = $field;
273 $this->mFieldTree = $loadedDescriptor;
277 * Set format in which to display the form
279 * @param string $format The name of the format to use, must be one of
280 * $this->availableDisplayFormats
282 * @throws MWException
283 * @since 1.20
284 * @return HTMLForm $this for chaining calls (since 1.20)
286 public function setDisplayFormat( $format ) {
287 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
288 throw new MWException( 'Display format must be one of ' .
289 print_r( $this->availableDisplayFormats, true ) );
291 $this->displayFormat = $format;
293 return $this;
297 * Getter for displayFormat
298 * @since 1.20
299 * @return string
301 public function getDisplayFormat() {
302 return $this->displayFormat;
306 * Test if displayFormat is 'vform'
307 * @since 1.22
308 * @return bool
310 public function isVForm() {
311 return $this->displayFormat === 'vform';
315 * Get the HTMLFormField subclass for this descriptor.
317 * The descriptor can be passed either 'class' which is the name of
318 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
319 * This makes sure the 'class' is always set, and also is returned by
320 * this function for ease.
322 * @since 1.23
324 * @param string $fieldname Name of the field
325 * @param array $descriptor Input Descriptor, as described above
327 * @throws MWException
328 * @return string Name of a HTMLFormField subclass
330 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
331 if ( isset( $descriptor['class'] ) ) {
332 $class = $descriptor['class'];
333 } elseif ( isset( $descriptor['type'] ) ) {
334 $class = self::$typeMappings[$descriptor['type']];
335 $descriptor['class'] = $class;
336 } else {
337 $class = null;
340 if ( !$class ) {
341 throw new MWException( "Descriptor with no class for $fieldname: "
342 . print_r( $descriptor, true ) );
345 return $class;
349 * Initialise a new Object for the field
351 * @param string $fieldname Name of the field
352 * @param array $descriptor Input Descriptor, as described above
354 * @throws MWException
355 * @return HTMLFormField Instance of a subclass of HTMLFormField
357 public static function loadInputFromParameters( $fieldname, $descriptor ) {
358 $class = self::getClassFromDescriptor( $fieldname, $descriptor );
360 $descriptor['fieldname'] = $fieldname;
362 # @todo This will throw a fatal error whenever someone try to use
363 # 'class' to feed a CSS class instead of 'cssclass'. Would be
364 # great to avoid the fatal error and show a nice error.
365 $obj = new $class( $descriptor );
367 return $obj;
371 * Prepare form for submission.
373 * @attention When doing method chaining, that should be the very last
374 * method call before displayForm().
376 * @throws MWException
377 * @return HTMLForm $this for chaining calls (since 1.20)
379 function prepareForm() {
380 # Check if we have the info we need
381 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
382 throw new MWException( "You must call setTitle() on an HTMLForm" );
385 # Load data from the request.
386 $this->loadData();
388 return $this;
392 * Try submitting, with edit token check first
393 * @return Status|bool
395 function tryAuthorizedSubmit() {
396 $result = false;
398 $submit = false;
399 if ( $this->getMethod() != 'post' ) {
400 $submit = true; // no session check needed
401 } elseif ( $this->getRequest()->wasPosted() ) {
402 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
403 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
404 // Session tokens for logged-out users have no security value.
405 // However, if the user gave one, check it in order to give a nice
406 // "session expired" error instead of "permission denied" or such.
407 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
408 } else {
409 $submit = true;
413 if ( $submit ) {
414 $this->mWasSubmitted = true;
415 $result = $this->trySubmit();
418 return $result;
422 * The here's-one-I-made-earlier option: do the submission if
423 * posted, or display the form with or without funky validation
424 * errors
425 * @return bool|Status Whether submission was successful.
427 function show() {
428 $this->prepareForm();
430 $result = $this->tryAuthorizedSubmit();
431 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
432 return $result;
435 $this->displayForm( $result );
437 return false;
441 * Validate all the fields, and call the submission callback
442 * function if everything is kosher.
443 * @throws MWException
444 * @return bool|string|array|Status
445 * - Bool true or a good Status object indicates success,
446 * - Bool false indicates no submission was attempted,
447 * - Anything else indicates failure. The value may be a fatal Status
448 * object, an HTML string, or an array of arrays (message keys and
449 * params) or strings (message keys)
451 function trySubmit() {
452 $this->mWasSubmitted = true;
454 # Check for cancelled submission
455 foreach ( $this->mFlatFields as $fieldname => $field ) {
456 if ( !empty( $field->mParams['nodata'] ) ) {
457 continue;
459 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
460 $this->mWasSubmitted = false;
461 return false;
465 # Check for validation
466 foreach ( $this->mFlatFields as $fieldname => $field ) {
467 if ( !empty( $field->mParams['nodata'] ) ) {
468 continue;
470 if ( $field->validate(
471 $this->mFieldData[$fieldname],
472 $this->mFieldData )
473 !== true
475 return isset( $this->mValidationErrorMessage )
476 ? $this->mValidationErrorMessage
477 : array( 'htmlform-invalid-input' );
481 $callback = $this->mSubmitCallback;
482 if ( !is_callable( $callback ) ) {
483 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
484 'setSubmitCallback() to set one.' );
487 $data = $this->filterDataForSubmit( $this->mFieldData );
489 $res = call_user_func( $callback, $data, $this );
490 if ( $res === false ) {
491 $this->mWasSubmitted = false;
494 return $res;
498 * Test whether the form was considered to have been submitted or not, i.e.
499 * whether the last call to tryAuthorizedSubmit or trySubmit returned
500 * non-false.
502 * This will return false until HTMLForm::tryAuthorizedSubmit or
503 * HTMLForm::trySubmit is called.
505 * @since 1.23
506 * @return bool
508 function wasSubmitted() {
509 return $this->mWasSubmitted;
513 * Set a callback to a function to do something with the form
514 * once it's been successfully validated.
516 * @param callable $cb The function will be passed the output from
517 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
518 * return as documented for HTMLForm::trySubmit
520 * @return HTMLForm $this for chaining calls (since 1.20)
522 function setSubmitCallback( $cb ) {
523 $this->mSubmitCallback = $cb;
525 return $this;
529 * Set a message to display on a validation error.
531 * @param string|array $msg String or Array of valid inputs to wfMessage()
532 * (so each entry can be either a String or Array)
534 * @return HTMLForm $this for chaining calls (since 1.20)
536 function setValidationErrorMessage( $msg ) {
537 $this->mValidationErrorMessage = $msg;
539 return $this;
543 * Set the introductory message, overwriting any existing message.
545 * @param string $msg Complete text of message to display
547 * @return HTMLForm $this for chaining calls (since 1.20)
549 function setIntro( $msg ) {
550 $this->setPreText( $msg );
552 return $this;
556 * Set the introductory message, overwriting any existing message.
557 * @since 1.19
559 * @param string $msg Complete text of message to display
561 * @return HTMLForm $this for chaining calls (since 1.20)
563 function setPreText( $msg ) {
564 $this->mPre = $msg;
566 return $this;
570 * Add introductory text.
572 * @param string $msg Complete text of message to display
574 * @return HTMLForm $this for chaining calls (since 1.20)
576 function addPreText( $msg ) {
577 $this->mPre .= $msg;
579 return $this;
583 * Add header text, inside the form.
585 * @param string $msg Complete text of message to display
586 * @param string|null $section The section to add the header to
588 * @return HTMLForm $this for chaining calls (since 1.20)
590 function addHeaderText( $msg, $section = null ) {
591 if ( is_null( $section ) ) {
592 $this->mHeader .= $msg;
593 } else {
594 if ( !isset( $this->mSectionHeaders[$section] ) ) {
595 $this->mSectionHeaders[$section] = '';
597 $this->mSectionHeaders[$section] .= $msg;
600 return $this;
604 * Set header text, inside the form.
605 * @since 1.19
607 * @param string $msg Complete text of message to display
608 * @param string|null $section The section to add the header to
610 * @return HTMLForm $this for chaining calls (since 1.20)
612 function setHeaderText( $msg, $section = null ) {
613 if ( is_null( $section ) ) {
614 $this->mHeader = $msg;
615 } else {
616 $this->mSectionHeaders[$section] = $msg;
619 return $this;
623 * Add footer text, inside the form.
625 * @param string $msg Complete text of message to display
626 * @param string|null $section The section to add the footer text to
628 * @return HTMLForm $this for chaining calls (since 1.20)
630 function addFooterText( $msg, $section = null ) {
631 if ( is_null( $section ) ) {
632 $this->mFooter .= $msg;
633 } else {
634 if ( !isset( $this->mSectionFooters[$section] ) ) {
635 $this->mSectionFooters[$section] = '';
637 $this->mSectionFooters[$section] .= $msg;
640 return $this;
644 * Set footer text, inside the form.
645 * @since 1.19
647 * @param string $msg Complete text of message to display
648 * @param string|null $section The section to add the footer text to
650 * @return HTMLForm $this for chaining calls (since 1.20)
652 function setFooterText( $msg, $section = null ) {
653 if ( is_null( $section ) ) {
654 $this->mFooter = $msg;
655 } else {
656 $this->mSectionFooters[$section] = $msg;
659 return $this;
663 * Add text to the end of the display.
665 * @param string $msg Complete text of message to display
667 * @return HTMLForm $this for chaining calls (since 1.20)
669 function addPostText( $msg ) {
670 $this->mPost .= $msg;
672 return $this;
676 * Set text at 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 setPostText( $msg ) {
683 $this->mPost = $msg;
685 return $this;
689 * Add a hidden field to the output
691 * @param string $name Field name. This will be used exactly as entered
692 * @param string $value Field value
693 * @param array $attribs
695 * @return HTMLForm $this for chaining calls (since 1.20)
697 public function addHiddenField( $name, $value, $attribs = array() ) {
698 $attribs += array( 'name' => $name );
699 $this->mHiddenFields[] = array( $value, $attribs );
701 return $this;
705 * Add an array of hidden fields to the output
707 * @since 1.22
709 * @param array $fields Associative array of fields to add;
710 * mapping names to their values
712 * @return HTMLForm $this for chaining calls
714 public function addHiddenFields( array $fields ) {
715 foreach ( $fields as $name => $value ) {
716 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
719 return $this;
723 * Add a button to the form
725 * @param string $name Field name.
726 * @param string $value Field value
727 * @param string $id DOM id for the button (default: null)
728 * @param array $attribs
730 * @return HTMLForm $this for chaining calls (since 1.20)
732 public function addButton( $name, $value, $id = null, $attribs = null ) {
733 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
735 return $this;
739 * Set the salt for the edit token.
741 * Only useful when the method is "post".
743 * @since 1.24
744 * @param string|array $salt Salt to use
745 * @return HTMLForm $this For chaining calls
747 public function setTokenSalt( $salt ) {
748 $this->mTokenSalt = $salt;
750 return $this;
754 * Display the form (sending to the context's OutputPage object), with an
755 * appropriate error message or stack of messages, and any validation errors, etc.
757 * @attention You should call prepareForm() before calling this function.
758 * Moreover, when doing method chaining this should be the very last method
759 * call just after prepareForm().
761 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
763 * @return void Nothing, should be last call
765 function displayForm( $submitResult ) {
766 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
770 * Returns the raw HTML generated by the form
772 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
774 * @return string
776 function getHTML( $submitResult ) {
777 # For good measure (it is the default)
778 $this->getOutput()->preventClickjacking();
779 $this->getOutput()->addModules( 'mediawiki.htmlform' );
780 if ( $this->isVForm() ) {
781 $this->getOutput()->addModuleStyles( array(
782 'mediawiki.ui',
783 'mediawiki.ui.button',
784 ) );
785 // @todo Should vertical form set setWrapperLegend( false )
786 // to hide ugly fieldsets?
789 $html = ''
790 . $this->getErrors( $submitResult )
791 . $this->mHeader
792 . $this->getBody()
793 . $this->getHiddenFields()
794 . $this->getButtons()
795 . $this->mFooter;
797 $html = $this->wrapForm( $html );
799 return '' . $this->mPre . $html . $this->mPost;
803 * Wrap the form innards in an actual "<form>" element
805 * @param string $html HTML contents to wrap.
807 * @return string Wrapped HTML.
809 function wrapForm( $html ) {
811 # Include a <fieldset> wrapper for style, if requested.
812 if ( $this->mWrapperLegend !== false ) {
813 $html = Xml::fieldset( $this->mWrapperLegend, $html );
815 # Use multipart/form-data
816 $encType = $this->mUseMultipart
817 ? 'multipart/form-data'
818 : 'application/x-www-form-urlencoded';
819 # Attributes
820 $attribs = array(
821 'action' => $this->getAction(),
822 'method' => $this->getMethod(),
823 'class' => array( 'visualClear' ),
824 'enctype' => $encType,
826 if ( !empty( $this->mId ) ) {
827 $attribs['id'] = $this->mId;
830 if ( $this->isVForm() ) {
831 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
834 return Html::rawElement( 'form', $attribs, $html );
838 * Get the hidden fields that should go inside the form.
839 * @return string HTML.
841 function getHiddenFields() {
842 global $wgArticlePath;
844 $html = '';
845 if ( $this->getMethod() == 'post' ) {
846 $html .= Html::hidden(
847 'wpEditToken',
848 $this->getUser()->getEditToken( $this->mTokenSalt ),
849 array( 'id' => 'wpEditToken' )
850 ) . "\n";
851 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
854 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
855 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
858 foreach ( $this->mHiddenFields as $data ) {
859 list( $value, $attribs ) = $data;
860 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
863 return $html;
867 * Get the submit and (potentially) reset buttons.
868 * @return string HTML.
870 function getButtons() {
871 $buttons = '';
873 if ( $this->mShowSubmit ) {
874 $attribs = array();
876 if ( isset( $this->mSubmitID ) ) {
877 $attribs['id'] = $this->mSubmitID;
880 if ( isset( $this->mSubmitName ) ) {
881 $attribs['name'] = $this->mSubmitName;
884 if ( isset( $this->mSubmitTooltip ) ) {
885 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
888 $attribs['class'] = array( 'mw-htmlform-submit' );
890 if ( $this->isVForm() ) {
891 // mw-ui-block is necessary because the buttons aren't necessarily in an
892 // immediate child div of the vform.
893 // @todo Let client specify if the primary submit button is progressive or destructive
894 array_push(
895 $attribs['class'],
896 'mw-ui-button',
897 'mw-ui-big',
898 'mw-ui-constructive',
899 'mw-ui-block'
903 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
906 if ( $this->mShowReset ) {
907 $buttons .= Html::element(
908 'input',
909 array(
910 'type' => 'reset',
911 'value' => $this->msg( 'htmlform-reset' )->text()
913 ) . "\n";
916 foreach ( $this->mButtons as $button ) {
917 $attrs = array(
918 'type' => 'submit',
919 'name' => $button['name'],
920 'value' => $button['value']
923 if ( $button['attribs'] ) {
924 $attrs += $button['attribs'];
927 if ( isset( $button['id'] ) ) {
928 $attrs['id'] = $button['id'];
931 $buttons .= Html::element( 'input', $attrs ) . "\n";
934 $html = Html::rawElement( 'span',
935 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
937 // Buttons are top-level form elements in table and div layouts,
938 // but vform wants all elements inside divs to get spaced-out block
939 // styling.
940 if ( $this->mShowSubmit && $this->isVForm() ) {
941 $html = Html::rawElement( 'div', null, "\n$html" ) . "\n";
944 return $html;
948 * Get the whole body of the form.
949 * @return string
951 function getBody() {
952 return $this->displaySection( $this->mFieldTree, $this->mTableId );
956 * Format and display an error message stack.
958 * @param string|array|Status $errors
960 * @return string
962 function getErrors( $errors ) {
963 if ( $errors instanceof Status ) {
964 if ( $errors->isOK() ) {
965 $errorstr = '';
966 } else {
967 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
969 } elseif ( is_array( $errors ) ) {
970 $errorstr = $this->formatErrors( $errors );
971 } else {
972 $errorstr = $errors;
975 return $errorstr
976 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
977 : '';
981 * Format a stack of error messages into a single HTML string
983 * @param array $errors Array of message keys/values
985 * @return string HTML, a "<ul>" list of errors
987 public static function formatErrors( $errors ) {
988 $errorstr = '';
990 foreach ( $errors as $error ) {
991 if ( is_array( $error ) ) {
992 $msg = array_shift( $error );
993 } else {
994 $msg = $error;
995 $error = array();
998 $errorstr .= Html::rawElement(
999 'li',
1000 array(),
1001 wfMessage( $msg, $error )->parse()
1005 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1007 return $errorstr;
1011 * Set the text for the submit button
1013 * @param string $t Plaintext
1015 * @return HTMLForm $this for chaining calls (since 1.20)
1017 function setSubmitText( $t ) {
1018 $this->mSubmitText = $t;
1020 return $this;
1024 * Set the text for the submit button to a message
1025 * @since 1.19
1027 * @param string|Message $msg Message key or Message object
1029 * @return HTMLForm $this for chaining calls (since 1.20)
1031 public function setSubmitTextMsg( $msg ) {
1032 if ( !$msg instanceof Message ) {
1033 $msg = $this->msg( $msg );
1035 $this->setSubmitText( $msg->text() );
1037 return $this;
1041 * Get the text for the submit button, either customised or a default.
1042 * @return string
1044 function getSubmitText() {
1045 return $this->mSubmitText
1046 ? $this->mSubmitText
1047 : $this->msg( 'htmlform-submit' )->text();
1051 * @param string $name Submit button name
1053 * @return HTMLForm $this for chaining calls (since 1.20)
1055 public function setSubmitName( $name ) {
1056 $this->mSubmitName = $name;
1058 return $this;
1062 * @param string $name Tooltip for the submit button
1064 * @return HTMLForm $this for chaining calls (since 1.20)
1066 public function setSubmitTooltip( $name ) {
1067 $this->mSubmitTooltip = $name;
1069 return $this;
1073 * Set the id for the submit button.
1075 * @param string $t
1077 * @todo FIXME: Integrity of $t is *not* validated
1078 * @return HTMLForm $this for chaining calls (since 1.20)
1080 function setSubmitID( $t ) {
1081 $this->mSubmitID = $t;
1083 return $this;
1087 * Stop a default submit button being shown for this form. This implies that an
1088 * alternate submit method must be provided manually.
1090 * @since 1.22
1092 * @param bool $suppressSubmit Set to false to re-enable the button again
1094 * @return HTMLForm $this for chaining calls
1096 function suppressDefaultSubmit( $suppressSubmit = true ) {
1097 $this->mShowSubmit = !$suppressSubmit;
1099 return $this;
1103 * Set the id of the \<table\> or outermost \<div\> element.
1105 * @since 1.22
1107 * @param string $id New value of the id attribute, or "" to remove
1109 * @return HTMLForm $this for chaining calls
1111 public function setTableId( $id ) {
1112 $this->mTableId = $id;
1114 return $this;
1118 * @param string $id DOM id for the form
1120 * @return HTMLForm $this for chaining calls (since 1.20)
1122 public function setId( $id ) {
1123 $this->mId = $id;
1125 return $this;
1129 * Prompt the whole form to be wrapped in a "<fieldset>", with
1130 * this text as its "<legend>" element.
1132 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1133 * false for no <legend>
1134 * Will be escaped
1136 * @return HTMLForm $this for chaining calls (since 1.20)
1138 public function setWrapperLegend( $legend ) {
1139 $this->mWrapperLegend = $legend;
1141 return $this;
1145 * Prompt the whole form to be wrapped in a "<fieldset>", with
1146 * this message as its "<legend>" element.
1147 * @since 1.19
1149 * @param string|Message $msg Message key or Message object
1151 * @return HTMLForm $this for chaining calls (since 1.20)
1153 public function setWrapperLegendMsg( $msg ) {
1154 if ( !$msg instanceof Message ) {
1155 $msg = $this->msg( $msg );
1157 $this->setWrapperLegend( $msg->text() );
1159 return $this;
1163 * Set the prefix for various default messages
1164 * @todo Currently only used for the "<fieldset>" legend on forms
1165 * with multiple sections; should be used elsewhere?
1167 * @param string $p
1169 * @return HTMLForm $this for chaining calls (since 1.20)
1171 function setMessagePrefix( $p ) {
1172 $this->mMessagePrefix = $p;
1174 return $this;
1178 * Set the title for form submission
1180 * @param Title $t Title of page the form is on/should be posted to
1182 * @return HTMLForm $this for chaining calls (since 1.20)
1184 function setTitle( $t ) {
1185 $this->mTitle = $t;
1187 return $this;
1191 * Get the title
1192 * @return Title
1194 function getTitle() {
1195 return $this->mTitle === false
1196 ? $this->getContext()->getTitle()
1197 : $this->mTitle;
1201 * Set the method used to submit the form
1203 * @param string $method
1205 * @return HTMLForm $this for chaining calls (since 1.20)
1207 public function setMethod( $method = 'post' ) {
1208 $this->mMethod = $method;
1210 return $this;
1213 public function getMethod() {
1214 return $this->mMethod;
1218 * @todo Document
1220 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1221 * objects).
1222 * @param string $sectionName ID attribute of the "<table>" tag for this
1223 * section, ignored if empty.
1224 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1225 * each subsection, ignored if empty.
1226 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1228 * @return string
1230 public function displaySection( $fields,
1231 $sectionName = '',
1232 $fieldsetIDPrefix = '',
1233 &$hasUserVisibleFields = false ) {
1234 $displayFormat = $this->getDisplayFormat();
1236 $html = '';
1237 $subsectionHtml = '';
1238 $hasLabel = false;
1240 switch ( $displayFormat ) {
1241 case 'table':
1242 $getFieldHtmlMethod = 'getTableRow';
1243 break;
1244 case 'vform':
1245 // Close enough to a div.
1246 $getFieldHtmlMethod = 'getDiv';
1247 break;
1248 default:
1249 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1252 foreach ( $fields as $key => $value ) {
1253 if ( $value instanceof HTMLFormField ) {
1254 $v = empty( $value->mParams['nodata'] )
1255 ? $this->mFieldData[$key]
1256 : $value->getDefault();
1257 $html .= $value->$getFieldHtmlMethod( $v );
1259 $labelValue = trim( $value->getLabel() );
1260 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1261 $hasLabel = true;
1264 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1265 get_class( $value ) !== 'HTMLApiField'
1267 $hasUserVisibleFields = true;
1269 } elseif ( is_array( $value ) ) {
1270 $subsectionHasVisibleFields = false;
1271 $section =
1272 $this->displaySection( $value,
1273 "mw-htmlform-$key",
1274 "$fieldsetIDPrefix$key-",
1275 $subsectionHasVisibleFields );
1276 $legend = null;
1278 if ( $subsectionHasVisibleFields === true ) {
1279 // Display the section with various niceties.
1280 $hasUserVisibleFields = true;
1282 $legend = $this->getLegend( $key );
1284 if ( isset( $this->mSectionHeaders[$key] ) ) {
1285 $section = $this->mSectionHeaders[$key] . $section;
1287 if ( isset( $this->mSectionFooters[$key] ) ) {
1288 $section .= $this->mSectionFooters[$key];
1291 $attributes = array();
1292 if ( $fieldsetIDPrefix ) {
1293 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1295 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1296 } else {
1297 // Just return the inputs, nothing fancy.
1298 $subsectionHtml .= $section;
1303 if ( $displayFormat !== 'raw' ) {
1304 $classes = array();
1306 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1307 $classes[] = 'mw-htmlform-nolabel';
1310 $attribs = array(
1311 'class' => implode( ' ', $classes ),
1314 if ( $sectionName ) {
1315 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1318 if ( $displayFormat === 'table' ) {
1319 $html = Html::rawElement( 'table',
1320 $attribs,
1321 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1322 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1323 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1327 if ( $this->mSubSectionBeforeFields ) {
1328 return $subsectionHtml . "\n" . $html;
1329 } else {
1330 return $html . "\n" . $subsectionHtml;
1335 * Construct the form fields from the Descriptor array
1337 function loadData() {
1338 $fieldData = array();
1340 foreach ( $this->mFlatFields as $fieldname => $field ) {
1341 if ( !empty( $field->mParams['nodata'] ) ) {
1342 continue;
1343 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1344 $fieldData[$fieldname] = $field->getDefault();
1345 } else {
1346 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1350 # Filter data.
1351 foreach ( $fieldData as $name => &$value ) {
1352 $field = $this->mFlatFields[$name];
1353 $value = $field->filter( $value, $this->mFlatFields );
1356 $this->mFieldData = $fieldData;
1360 * Stop a reset button being shown for this form
1362 * @param bool $suppressReset Set to false to re-enable the button again
1364 * @return HTMLForm $this for chaining calls (since 1.20)
1366 function suppressReset( $suppressReset = true ) {
1367 $this->mShowReset = !$suppressReset;
1369 return $this;
1373 * Overload this if you want to apply special filtration routines
1374 * to the form as a whole, after it's submitted but before it's
1375 * processed.
1377 * @param array $data
1379 * @return array
1381 function filterDataForSubmit( $data ) {
1382 return $data;
1386 * Get a string to go in the "<legend>" of a section fieldset.
1387 * Override this if you want something more complicated.
1389 * @param string $key
1391 * @return string
1393 public function getLegend( $key ) {
1394 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1398 * Set the value for the action attribute of the form.
1399 * When set to false (which is the default state), the set title is used.
1401 * @since 1.19
1403 * @param string|bool $action
1405 * @return HTMLForm $this for chaining calls (since 1.20)
1407 public function setAction( $action ) {
1408 $this->mAction = $action;
1410 return $this;
1414 * Get the value for the action attribute of the form.
1416 * @since 1.22
1418 * @return string
1420 public function getAction() {
1421 global $wgScript, $wgArticlePath;
1423 // If an action is alredy provided, return it
1424 if ( $this->mAction !== false ) {
1425 return $this->mAction;
1428 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1429 // meaning that getLocalURL() would return something like "index.php?title=...".
1430 // As browser remove the query string before submitting GET forms,
1431 // it means that the title would be lost. In such case use $wgScript instead
1432 // and put title in an hidden field (see getHiddenFields()).
1433 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1434 return $wgScript;
1437 return $this->getTitle()->getLocalURL();