Allow to set a salt for the edit token in HTMLForm
[mediawiki.git] / includes / htmlform / HTMLForm.php
blob33346948e288f1dfdaf3010d69d7f9a4cd9fc374
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 * Salt for the edit token.
176 * @var string|array
178 protected $mTokenSalt = '';
181 * If true, sections that contain both fields and subsections will
182 * render their subsections before their fields.
184 * Subclasses may set this to false to render subsections after fields
185 * instead.
187 protected $mSubSectionBeforeFields = true;
190 * Format in which to display form. For viable options,
191 * @see $availableDisplayFormats
192 * @var string
194 protected $displayFormat = 'table';
197 * Available formats in which to display the form
198 * @var array
200 protected $availableDisplayFormats = array(
201 'table',
202 'div',
203 'raw',
204 'vform',
208 * Build a new HTMLForm from an array of field attributes
210 * @param array $descriptor Array of Field constructs, as described above
211 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
212 * Obviates the need to call $form->setTitle()
213 * @param string $messagePrefix A prefix to go in front of default messages
215 public function __construct( $descriptor, /*IContextSource*/ $context = null,
216 $messagePrefix = ''
218 if ( $context instanceof IContextSource ) {
219 $this->setContext( $context );
220 $this->mTitle = false; // We don't need them to set a title
221 $this->mMessagePrefix = $messagePrefix;
222 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
223 $this->mMessagePrefix = $messagePrefix;
224 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
225 // B/C since 1.18
226 // it's actually $messagePrefix
227 $this->mMessagePrefix = $context;
230 // Expand out into a tree.
231 $loadedDescriptor = array();
232 $this->mFlatFields = array();
234 foreach ( $descriptor as $fieldname => $info ) {
235 $section = isset( $info['section'] )
236 ? $info['section']
237 : '';
239 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
240 $this->mUseMultipart = true;
243 $field = self::loadInputFromParameters( $fieldname, $info );
244 // FIXME During field's construct, the parent form isn't available!
245 // could add a 'parent' name-value to $info, could add a third parameter.
246 $field->mParent = $this;
248 // vform gets too much space if empty labels generate HTML.
249 if ( $this->isVForm() ) {
250 $field->setShowEmptyLabel( false );
253 $setSection =& $loadedDescriptor;
254 if ( $section ) {
255 $sectionParts = explode( '/', $section );
257 while ( count( $sectionParts ) ) {
258 $newName = array_shift( $sectionParts );
260 if ( !isset( $setSection[$newName] ) ) {
261 $setSection[$newName] = array();
264 $setSection =& $setSection[$newName];
268 $setSection[$fieldname] = $field;
269 $this->mFlatFields[$fieldname] = $field;
272 $this->mFieldTree = $loadedDescriptor;
276 * Set format in which to display the form
278 * @param string $format The name of the format to use, must be one of
279 * $this->availableDisplayFormats
281 * @throws MWException
282 * @since 1.20
283 * @return HTMLForm $this for chaining calls (since 1.20)
285 public function setDisplayFormat( $format ) {
286 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
287 throw new MWException( 'Display format must be one of ' .
288 print_r( $this->availableDisplayFormats, true ) );
290 $this->displayFormat = $format;
292 return $this;
296 * Getter for displayFormat
297 * @since 1.20
298 * @return string
300 public function getDisplayFormat() {
301 return $this->displayFormat;
305 * Test if displayFormat is 'vform'
306 * @since 1.22
307 * @return bool
309 public function isVForm() {
310 return $this->displayFormat === 'vform';
314 * Get the HTMLFormField subclass for this descriptor.
316 * The descriptor can be passed either 'class' which is the name of
317 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
318 * This makes sure the 'class' is always set, and also is returned by
319 * this function for ease.
321 * @since 1.23
323 * @param string $fieldname Name of the field
324 * @param array $descriptor Input Descriptor, as described above
326 * @throws MWException
327 * @return string Name of a HTMLFormField subclass
329 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
330 if ( isset( $descriptor['class'] ) ) {
331 $class = $descriptor['class'];
332 } elseif ( isset( $descriptor['type'] ) ) {
333 $class = self::$typeMappings[$descriptor['type']];
334 $descriptor['class'] = $class;
335 } else {
336 $class = null;
339 if ( !$class ) {
340 throw new MWException( "Descriptor with no class for $fieldname: "
341 . print_r( $descriptor, true ) );
344 return $class;
348 * Initialise a new Object for the field
350 * @param string $fieldname Name of the field
351 * @param array $descriptor Input Descriptor, as described above
353 * @throws MWException
354 * @return HTMLFormField subclass
356 public static function loadInputFromParameters( $fieldname, $descriptor ) {
357 $class = self::getClassFromDescriptor( $fieldname, $descriptor );
359 $descriptor['fieldname'] = $fieldname;
361 # @todo This will throw a fatal error whenever someone try to use
362 # 'class' to feed a CSS class instead of 'cssclass'. Would be
363 # great to avoid the fatal error and show a nice error.
364 $obj = new $class( $descriptor );
366 return $obj;
370 * Prepare form for submission.
372 * @attention When doing method chaining, that should be the very last
373 * method call before displayForm().
375 * @throws MWException
376 * @return HTMLForm $this for chaining calls (since 1.20)
378 function prepareForm() {
379 # Check if we have the info we need
380 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
381 throw new MWException( "You must call setTitle() on an HTMLForm" );
384 # Load data from the request.
385 $this->loadData();
387 return $this;
391 * Try submitting, with edit token check first
392 * @return Status|bool
394 function tryAuthorizedSubmit() {
395 $result = false;
397 $submit = false;
398 if ( $this->getMethod() != 'post' ) {
399 $submit = true; // no session check needed
400 } elseif ( $this->getRequest()->wasPosted() ) {
401 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
402 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
403 // Session tokens for logged-out users have no security value.
404 // However, if the user gave one, check it in order to give a nice
405 // "session expired" error instead of "permission denied" or such.
406 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
407 } else {
408 $submit = true;
412 if ( $submit ) {
413 $this->mWasSubmitted = true;
414 $result = $this->trySubmit();
417 return $result;
421 * The here's-one-I-made-earlier option: do the submission if
422 * posted, or display the form with or without funky validation
423 * errors
424 * @return bool|Status Whether submission was successful.
426 function show() {
427 $this->prepareForm();
429 $result = $this->tryAuthorizedSubmit();
430 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
431 return $result;
434 $this->displayForm( $result );
436 return false;
440 * Validate all the fields, and call the submission callback
441 * function if everything is kosher.
442 * @throws MWException
443 * @return bool|string|array|Status
444 * - Bool true or a good Status object indicates success,
445 * - Bool false indicates no submission was attempted,
446 * - Anything else indicates failure. The value may be a fatal Status
447 * object, an HTML string, or an array of arrays (message keys and
448 * params) or strings (message keys)
450 function trySubmit() {
451 $this->mWasSubmitted = true;
453 # Check for cancelled submission
454 foreach ( $this->mFlatFields as $fieldname => $field ) {
455 if ( !empty( $field->mParams['nodata'] ) ) {
456 continue;
458 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
459 $this->mWasSubmitted = false;
460 return false;
464 # Check for validation
465 foreach ( $this->mFlatFields as $fieldname => $field ) {
466 if ( !empty( $field->mParams['nodata'] ) ) {
467 continue;
469 if ( $field->validate(
470 $this->mFieldData[$fieldname],
471 $this->mFieldData )
472 !== true
474 return isset( $this->mValidationErrorMessage )
475 ? $this->mValidationErrorMessage
476 : array( 'htmlform-invalid-input' );
480 $callback = $this->mSubmitCallback;
481 if ( !is_callable( $callback ) ) {
482 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
483 'setSubmitCallback() to set one.' );
486 $data = $this->filterDataForSubmit( $this->mFieldData );
488 $res = call_user_func( $callback, $data, $this );
489 if ( $res === false ) {
490 $this->mWasSubmitted = false;
493 return $res;
497 * Test whether the form was considered to have been submitted or not, i.e.
498 * whether the last call to tryAuthorizedSubmit or trySubmit returned
499 * non-false.
501 * This will return false until HTMLForm::tryAuthorizedSubmit or
502 * HTMLForm::trySubmit is called.
504 * @since 1.23
505 * @return bool
507 function wasSubmitted() {
508 return $this->mWasSubmitted;
512 * Set a callback to a function to do something with the form
513 * once it's been successfully validated.
515 * @param callable $cb The function will be passed the output from
516 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
517 * return as documented for HTMLForm::trySubmit
519 * @return HTMLForm $this for chaining calls (since 1.20)
521 function setSubmitCallback( $cb ) {
522 $this->mSubmitCallback = $cb;
524 return $this;
528 * Set a message to display on a validation error.
530 * @param string|array $msg String or Array of valid inputs to wfMessage()
531 * (so each entry can be either a String or Array)
533 * @return HTMLForm $this for chaining calls (since 1.20)
535 function setValidationErrorMessage( $msg ) {
536 $this->mValidationErrorMessage = $msg;
538 return $this;
542 * Set the introductory message, overwriting any existing message.
544 * @param string $msg Complete text of message to display
546 * @return HTMLForm $this for chaining calls (since 1.20)
548 function setIntro( $msg ) {
549 $this->setPreText( $msg );
551 return $this;
555 * Set the introductory message, overwriting any existing message.
556 * @since 1.19
558 * @param string $msg Complete text of message to display
560 * @return HTMLForm $this for chaining calls (since 1.20)
562 function setPreText( $msg ) {
563 $this->mPre = $msg;
565 return $this;
569 * Add introductory text.
571 * @param string $msg Complete text of message to display
573 * @return HTMLForm $this for chaining calls (since 1.20)
575 function addPreText( $msg ) {
576 $this->mPre .= $msg;
578 return $this;
582 * Add header text, inside the form.
584 * @param string $msg Complete text of message to display
585 * @param string|null $section The section to add the header to
587 * @return HTMLForm $this for chaining calls (since 1.20)
589 function addHeaderText( $msg, $section = null ) {
590 if ( is_null( $section ) ) {
591 $this->mHeader .= $msg;
592 } else {
593 if ( !isset( $this->mSectionHeaders[$section] ) ) {
594 $this->mSectionHeaders[$section] = '';
596 $this->mSectionHeaders[$section] .= $msg;
599 return $this;
603 * Set header text, inside the form.
604 * @since 1.19
606 * @param string $msg Complete text of message to display
607 * @param string|null $section The section to add the header to
609 * @return HTMLForm $this for chaining calls (since 1.20)
611 function setHeaderText( $msg, $section = null ) {
612 if ( is_null( $section ) ) {
613 $this->mHeader = $msg;
614 } else {
615 $this->mSectionHeaders[$section] = $msg;
618 return $this;
622 * Add footer text, inside the form.
624 * @param string $msg complete text of message to display
625 * @param string|null $section The section to add the footer text to
627 * @return HTMLForm $this for chaining calls (since 1.20)
629 function addFooterText( $msg, $section = null ) {
630 if ( is_null( $section ) ) {
631 $this->mFooter .= $msg;
632 } else {
633 if ( !isset( $this->mSectionFooters[$section] ) ) {
634 $this->mSectionFooters[$section] = '';
636 $this->mSectionFooters[$section] .= $msg;
639 return $this;
643 * Set footer text, inside the form.
644 * @since 1.19
646 * @param string $msg Complete text of message to display
647 * @param string|null $section The section to add the footer text to
649 * @return HTMLForm $this for chaining calls (since 1.20)
651 function setFooterText( $msg, $section = null ) {
652 if ( is_null( $section ) ) {
653 $this->mFooter = $msg;
654 } else {
655 $this->mSectionFooters[$section] = $msg;
658 return $this;
662 * Add text to the end of the display.
664 * @param string $msg Complete text of message to display
666 * @return HTMLForm $this for chaining calls (since 1.20)
668 function addPostText( $msg ) {
669 $this->mPost .= $msg;
671 return $this;
675 * Set text at 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 setPostText( $msg ) {
682 $this->mPost = $msg;
684 return $this;
688 * Add a hidden field to the output
690 * @param string $name Field name. This will be used exactly as entered
691 * @param string $value Field value
692 * @param array $attribs
694 * @return HTMLForm $this for chaining calls (since 1.20)
696 public function addHiddenField( $name, $value, $attribs = array() ) {
697 $attribs += array( 'name' => $name );
698 $this->mHiddenFields[] = array( $value, $attribs );
700 return $this;
704 * Add an array of hidden fields to the output
706 * @since 1.22
708 * @param array $fields Associative array of fields to add;
709 * mapping names to their values
711 * @return HTMLForm $this for chaining calls
713 public function addHiddenFields( array $fields ) {
714 foreach ( $fields as $name => $value ) {
715 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
718 return $this;
722 * Add a button to the form
724 * @param string $name Field name.
725 * @param string $value Field value
726 * @param string $id DOM id for the button (default: null)
727 * @param array $attribs
729 * @return HTMLForm $this for chaining calls (since 1.20)
731 public function addButton( $name, $value, $id = null, $attribs = null ) {
732 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
734 return $this;
738 * Set the salt for the edit token.
740 * Only useful when the method is "post".
742 * @since 1.24
743 * @param string|array Salt to use
744 * @return HTMLForm $this for chaining calls
746 public function setTokenSalt( $salt ) {
747 $this->mTokenSalt = $salt;
749 return $this;
753 * Display the form (sending to the context's OutputPage object), with an
754 * appropriate error message or stack of messages, and any validation errors, etc.
756 * @attention You should call prepareForm() before calling this function.
757 * Moreover, when doing method chaining this should be the very last method
758 * call just after prepareForm().
760 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
762 * @return Nothing, should be last call
764 function displayForm( $submitResult ) {
765 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
769 * Returns the raw HTML generated by the form
771 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
773 * @return string
775 function getHTML( $submitResult ) {
776 # For good measure (it is the default)
777 $this->getOutput()->preventClickjacking();
778 $this->getOutput()->addModules( 'mediawiki.htmlform' );
779 if ( $this->isVForm() ) {
780 $this->getOutput()->addModuleStyles( array(
781 'mediawiki.ui',
782 'mediawiki.ui.button',
783 ) );
784 // @todo Should vertical form set setWrapperLegend( false )
785 // to hide ugly fieldsets?
788 $html = ''
789 . $this->getErrors( $submitResult )
790 . $this->mHeader
791 . $this->getBody()
792 . $this->getHiddenFields()
793 . $this->getButtons()
794 . $this->mFooter;
796 $html = $this->wrapForm( $html );
798 return '' . $this->mPre . $html . $this->mPost;
802 * Wrap the form innards in an actual "<form>" element
804 * @param string $html HTML contents to wrap.
806 * @return string Wrapped HTML.
808 function wrapForm( $html ) {
810 # Include a <fieldset> wrapper for style, if requested.
811 if ( $this->mWrapperLegend !== false ) {
812 $html = Xml::fieldset( $this->mWrapperLegend, $html );
814 # Use multipart/form-data
815 $encType = $this->mUseMultipart
816 ? 'multipart/form-data'
817 : 'application/x-www-form-urlencoded';
818 # Attributes
819 $attribs = array(
820 'action' => $this->getAction(),
821 'method' => $this->getMethod(),
822 'class' => array( 'visualClear' ),
823 'enctype' => $encType,
825 if ( !empty( $this->mId ) ) {
826 $attribs['id'] = $this->mId;
829 if ( $this->isVForm() ) {
830 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
833 return Html::rawElement( 'form', $attribs, $html );
837 * Get the hidden fields that should go inside the form.
838 * @return string HTML.
840 function getHiddenFields() {
841 global $wgArticlePath;
843 $html = '';
844 if ( $this->getMethod() == 'post' ) {
845 $html .= Html::hidden(
846 'wpEditToken',
847 $this->getUser()->getEditToken( $this->mTokenSalt ),
848 array( 'id' => 'wpEditToken' )
849 ) . "\n";
850 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
853 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
854 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
857 foreach ( $this->mHiddenFields as $data ) {
858 list( $value, $attribs ) = $data;
859 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
862 return $html;
866 * Get the submit and (potentially) reset buttons.
867 * @return string HTML.
869 function getButtons() {
870 $buttons = '';
872 if ( $this->mShowSubmit ) {
873 $attribs = array();
875 if ( isset( $this->mSubmitID ) ) {
876 $attribs['id'] = $this->mSubmitID;
879 if ( isset( $this->mSubmitName ) ) {
880 $attribs['name'] = $this->mSubmitName;
883 if ( isset( $this->mSubmitTooltip ) ) {
884 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
887 $attribs['class'] = array( 'mw-htmlform-submit' );
889 if ( $this->isVForm() ) {
890 // mw-ui-block is necessary because the buttons aren't necessarily in an
891 // immediate child div of the vform.
892 // @todo Let client specify if the primary submit button is progressive or destructive
893 array_push(
894 $attribs['class'],
895 'mw-ui-button',
896 'mw-ui-big',
897 'mw-ui-constructive',
898 'mw-ui-block'
902 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
905 if ( $this->mShowReset ) {
906 $buttons .= Html::element(
907 'input',
908 array(
909 'type' => 'reset',
910 'value' => $this->msg( 'htmlform-reset' )->text()
912 ) . "\n";
915 foreach ( $this->mButtons as $button ) {
916 $attrs = array(
917 'type' => 'submit',
918 'name' => $button['name'],
919 'value' => $button['value']
922 if ( $button['attribs'] ) {
923 $attrs += $button['attribs'];
926 if ( isset( $button['id'] ) ) {
927 $attrs['id'] = $button['id'];
930 $buttons .= Html::element( 'input', $attrs ) . "\n";
933 $html = Html::rawElement( 'span',
934 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
936 // Buttons are top-level form elements in table and div layouts,
937 // but vform wants all elements inside divs to get spaced-out block
938 // styling.
939 if ( $this->mShowSubmit && $this->isVForm() ) {
940 $html = Html::rawElement( 'div', null, "\n$html" ) . "\n";
943 return $html;
947 * Get the whole body of the form.
948 * @return string
950 function getBody() {
951 return $this->displaySection( $this->mFieldTree, $this->mTableId );
955 * Format and display an error message stack.
957 * @param string|array|Status $errors
959 * @return string
961 function getErrors( $errors ) {
962 if ( $errors instanceof Status ) {
963 if ( $errors->isOK() ) {
964 $errorstr = '';
965 } else {
966 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
968 } elseif ( is_array( $errors ) ) {
969 $errorstr = $this->formatErrors( $errors );
970 } else {
971 $errorstr = $errors;
974 return $errorstr
975 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
976 : '';
980 * Format a stack of error messages into a single HTML string
982 * @param array $errors of message keys/values
984 * @return string HTML, a "<ul>" list of errors
986 public static function formatErrors( $errors ) {
987 $errorstr = '';
989 foreach ( $errors as $error ) {
990 if ( is_array( $error ) ) {
991 $msg = array_shift( $error );
992 } else {
993 $msg = $error;
994 $error = array();
997 $errorstr .= Html::rawElement(
998 'li',
999 array(),
1000 wfMessage( $msg, $error )->parse()
1004 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1006 return $errorstr;
1010 * Set the text for the submit button
1012 * @param string $t plaintext.
1014 * @return HTMLForm $this for chaining calls (since 1.20)
1016 function setSubmitText( $t ) {
1017 $this->mSubmitText = $t;
1019 return $this;
1023 * Set the text for the submit button to a message
1024 * @since 1.19
1026 * @param string $msg Message key
1028 * @return HTMLForm $this for chaining calls (since 1.20)
1030 public function setSubmitTextMsg( $msg ) {
1031 $this->setSubmitText( $this->msg( $msg )->text() );
1033 return $this;
1037 * Get the text for the submit button, either customised or a default.
1038 * @return string
1040 function getSubmitText() {
1041 return $this->mSubmitText
1042 ? $this->mSubmitText
1043 : $this->msg( 'htmlform-submit' )->text();
1047 * @param string $name Submit button name
1049 * @return HTMLForm $this for chaining calls (since 1.20)
1051 public function setSubmitName( $name ) {
1052 $this->mSubmitName = $name;
1054 return $this;
1058 * @param string $name Tooltip for the submit button
1060 * @return HTMLForm $this for chaining calls (since 1.20)
1062 public function setSubmitTooltip( $name ) {
1063 $this->mSubmitTooltip = $name;
1065 return $this;
1069 * Set the id for the submit button.
1071 * @param string $t
1073 * @todo FIXME: Integrity of $t is *not* validated
1074 * @return HTMLForm $this for chaining calls (since 1.20)
1076 function setSubmitID( $t ) {
1077 $this->mSubmitID = $t;
1079 return $this;
1083 * Stop a default submit button being shown for this form. This implies that an
1084 * alternate submit method must be provided manually.
1086 * @since 1.22
1088 * @param bool $suppressSubmit Set to false to re-enable the button again
1090 * @return HTMLForm $this for chaining calls
1092 function suppressDefaultSubmit( $suppressSubmit = true ) {
1093 $this->mShowSubmit = !$suppressSubmit;
1095 return $this;
1099 * Set the id of the \<table\> or outermost \<div\> element.
1101 * @since 1.22
1103 * @param string $id New value of the id attribute, or "" to remove
1105 * @return HTMLForm $this for chaining calls
1107 public function setTableId( $id ) {
1108 $this->mTableId = $id;
1110 return $this;
1114 * @param string $id DOM id for the form
1116 * @return HTMLForm $this for chaining calls (since 1.20)
1118 public function setId( $id ) {
1119 $this->mId = $id;
1121 return $this;
1125 * Prompt the whole form to be wrapped in a "<fieldset>", with
1126 * this text as its "<legend>" element.
1128 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1129 * false for no <legend>
1130 * Will be escaped
1132 * @return HTMLForm $this for chaining calls (since 1.20)
1134 public function setWrapperLegend( $legend ) {
1135 $this->mWrapperLegend = $legend;
1137 return $this;
1141 * Prompt the whole form to be wrapped in a "<fieldset>", with
1142 * this message as its "<legend>" element.
1143 * @since 1.19
1145 * @param string $msg Message key
1147 * @return HTMLForm $this for chaining calls (since 1.20)
1149 public function setWrapperLegendMsg( $msg ) {
1150 $this->setWrapperLegend( $this->msg( $msg )->text() );
1152 return $this;
1156 * Set the prefix for various default messages
1157 * @todo Currently only used for the "<fieldset>" legend on forms
1158 * with multiple sections; should be used elsewhere?
1160 * @param string $p
1162 * @return HTMLForm $this for chaining calls (since 1.20)
1164 function setMessagePrefix( $p ) {
1165 $this->mMessagePrefix = $p;
1167 return $this;
1171 * Set the title for form submission
1173 * @param Title $t Title of page the form is on/should be posted to
1175 * @return HTMLForm $this for chaining calls (since 1.20)
1177 function setTitle( $t ) {
1178 $this->mTitle = $t;
1180 return $this;
1184 * Get the title
1185 * @return Title
1187 function getTitle() {
1188 return $this->mTitle === false
1189 ? $this->getContext()->getTitle()
1190 : $this->mTitle;
1194 * Set the method used to submit the form
1196 * @param string $method
1198 * @return HTMLForm $this for chaining calls (since 1.20)
1200 public function setMethod( $method = 'post' ) {
1201 $this->mMethod = $method;
1203 return $this;
1206 public function getMethod() {
1207 return $this->mMethod;
1211 * @todo Document
1213 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1214 * objects).
1215 * @param string $sectionName ID attribute of the "<table>" tag for this
1216 * section, ignored if empty.
1217 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1218 * each subsection, ignored if empty.
1219 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1221 * @return string
1223 public function displaySection( $fields,
1224 $sectionName = '',
1225 $fieldsetIDPrefix = '',
1226 &$hasUserVisibleFields = false ) {
1227 $displayFormat = $this->getDisplayFormat();
1229 $html = '';
1230 $subsectionHtml = '';
1231 $hasLabel = false;
1233 switch ( $displayFormat ) {
1234 case 'table':
1235 $getFieldHtmlMethod = 'getTableRow';
1236 break;
1237 case 'vform':
1238 // Close enough to a div.
1239 $getFieldHtmlMethod = 'getDiv';
1240 break;
1241 default:
1242 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1245 foreach ( $fields as $key => $value ) {
1246 if ( $value instanceof HTMLFormField ) {
1247 $v = empty( $value->mParams['nodata'] )
1248 ? $this->mFieldData[$key]
1249 : $value->getDefault();
1250 $html .= $value->$getFieldHtmlMethod( $v );
1252 $labelValue = trim( $value->getLabel() );
1253 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1254 $hasLabel = true;
1257 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1258 get_class( $value ) !== 'HTMLApiField'
1260 $hasUserVisibleFields = true;
1262 } elseif ( is_array( $value ) ) {
1263 $subsectionHasVisibleFields = false;
1264 $section =
1265 $this->displaySection( $value,
1266 "mw-htmlform-$key",
1267 "$fieldsetIDPrefix$key-",
1268 $subsectionHasVisibleFields );
1269 $legend = null;
1271 if ( $subsectionHasVisibleFields === true ) {
1272 // Display the section with various niceties.
1273 $hasUserVisibleFields = true;
1275 $legend = $this->getLegend( $key );
1277 if ( isset( $this->mSectionHeaders[$key] ) ) {
1278 $section = $this->mSectionHeaders[$key] . $section;
1280 if ( isset( $this->mSectionFooters[$key] ) ) {
1281 $section .= $this->mSectionFooters[$key];
1284 $attributes = array();
1285 if ( $fieldsetIDPrefix ) {
1286 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1288 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1289 } else {
1290 // Just return the inputs, nothing fancy.
1291 $subsectionHtml .= $section;
1296 if ( $displayFormat !== 'raw' ) {
1297 $classes = array();
1299 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1300 $classes[] = 'mw-htmlform-nolabel';
1303 $attribs = array(
1304 'class' => implode( ' ', $classes ),
1307 if ( $sectionName ) {
1308 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1311 if ( $displayFormat === 'table' ) {
1312 $html = Html::rawElement( 'table',
1313 $attribs,
1314 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1315 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1316 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1320 if ( $this->mSubSectionBeforeFields ) {
1321 return $subsectionHtml . "\n" . $html;
1322 } else {
1323 return $html . "\n" . $subsectionHtml;
1328 * Construct the form fields from the Descriptor array
1330 function loadData() {
1331 $fieldData = array();
1333 foreach ( $this->mFlatFields as $fieldname => $field ) {
1334 if ( !empty( $field->mParams['nodata'] ) ) {
1335 continue;
1336 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1337 $fieldData[$fieldname] = $field->getDefault();
1338 } else {
1339 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1343 # Filter data.
1344 foreach ( $fieldData as $name => &$value ) {
1345 $field = $this->mFlatFields[$name];
1346 $value = $field->filter( $value, $this->mFlatFields );
1349 $this->mFieldData = $fieldData;
1353 * Stop a reset button being shown for this form
1355 * @param bool $suppressReset Set to false to re-enable the button again
1357 * @return HTMLForm $this for chaining calls (since 1.20)
1359 function suppressReset( $suppressReset = true ) {
1360 $this->mShowReset = !$suppressReset;
1362 return $this;
1366 * Overload this if you want to apply special filtration routines
1367 * to the form as a whole, after it's submitted but before it's
1368 * processed.
1370 * @param array $data
1372 * @return
1374 function filterDataForSubmit( $data ) {
1375 return $data;
1379 * Get a string to go in the "<legend>" of a section fieldset.
1380 * Override this if you want something more complicated.
1382 * @param string $key
1384 * @return string
1386 public function getLegend( $key ) {
1387 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1391 * Set the value for the action attribute of the form.
1392 * When set to false (which is the default state), the set title is used.
1394 * @since 1.19
1396 * @param string|bool $action
1398 * @return HTMLForm $this for chaining calls (since 1.20)
1400 public function setAction( $action ) {
1401 $this->mAction = $action;
1403 return $this;
1407 * Get the value for the action attribute of the form.
1409 * @since 1.22
1411 * @return string
1413 public function getAction() {
1414 global $wgScript, $wgArticlePath;
1416 // If an action is alredy provided, return it
1417 if ( $this->mAction !== false ) {
1418 return $this->mAction;
1421 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1422 // meaning that getLocalURL() would return something like "index.php?title=...".
1423 // As browser remove the query string before submitting GET forms,
1424 // it means that the title would be lost. In such case use $wgScript instead
1425 // and put title in an hidden field (see getHiddenFields()).
1426 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1427 return $wgScript;
1430 return $this->getTitle()->getLocalURL();