Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / HTMLForm.php
blob2d0cefc5c9469fe6f2fa1c8c1ffede8128d2e136
1 <?php
2 /**
3 * HTML form generation and submission handling.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Object handling generic submission, CSRF protection, layout and
25 * other logic for UI forms. in a reusable manner.
27 * In order to generate the form, the HTMLForm object takes an array
28 * structure detailing the form fields available. Each element of the
29 * array is a basic property-list, including the type of field, the
30 * label it is to be given in the form, callbacks for validation and
31 * 'filtering', and other pertinent information.
33 * Field types are implemented as subclasses of the generic HTMLFormField
34 * object, and typically implement at least getInputHTML, which generates
35 * the HTML for the input field to be placed in the table.
37 * You can find extensive documentation on the www.mediawiki.org wiki:
38 * - http://www.mediawiki.org/wiki/HTMLForm
39 * - http://www.mediawiki.org/wiki/HTMLForm/tutorial
41 * The constructor input is an associative array of $fieldname => $info,
42 * where $info is an Associative Array with any of the following:
44 * 'class' -- the subclass of HTMLFormField that will be used
45 * to create the object. *NOT* the CSS class!
46 * 'type' -- roughly translates into the <select> type attribute.
47 * if 'class' is not specified, this is used as a map
48 * through HTMLForm::$typeMappings to get the class name.
49 * 'default' -- default value when the form is displayed
50 * 'id' -- HTML id attribute
51 * 'cssclass' -- CSS class
52 * 'options' -- varies according to the specific object.
53 * 'label-message' -- message key for a message to use as the label.
54 * can be an array of msg key and then parameters to
55 * the message.
56 * 'label' -- alternatively, a raw text message. Overridden by
57 * label-message
58 * 'help' -- message text for a message to use as a help text.
59 * 'help-message' -- message key for a message to use as a help text.
60 * can be an array of msg key and then parameters to
61 * the message.
62 * Overwrites 'help-messages' and 'help'.
63 * 'help-messages' -- array of message key. As above, each item can
64 * be an array of msg key and then parameters.
65 * Overwrites 'help'.
66 * 'required' -- passed through to the object, indicating that it
67 * is a required field.
68 * 'size' -- the length of text fields
69 * 'filter-callback -- a function name to give you the chance to
70 * massage the inputted value before it's processed.
71 * @see HTMLForm::filter()
72 * 'validation-callback' -- a function name to give you the chance
73 * to impose extra validation on the field input.
74 * @see HTMLForm::validate()
75 * 'name' -- By default, the 'name' attribute of the input field
76 * is "wp{$fieldname}". If you want a different name
77 * (eg one without the "wp" prefix), specify it here and
78 * it will be used without modification.
80 * Since 1.20, you can chain mutators to ease the form generation:
81 * @par Example:
82 * @code
83 * $form = new HTMLForm( $someFields );
84 * $form->setMethod( 'get' )
85 * ->setWrapperLegendMsg( 'message-key' )
86 * ->suppressReset()
87 * ->prepareForm()
88 * ->displayForm();
89 * @endcode
90 * Note that you will have prepareForm and displayForm at the end. Other
91 * methods call done after that would simply not be part of the form :(
93 * TODO: Document 'section' / 'subsection' stuff
95 class HTMLForm extends ContextSource {
97 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
98 private static $typeMappings = array(
99 'api' => 'HTMLApiField',
100 'text' => 'HTMLTextField',
101 'textarea' => 'HTMLTextAreaField',
102 'select' => 'HTMLSelectField',
103 'radio' => 'HTMLRadioField',
104 'multiselect' => 'HTMLMultiSelectField',
105 'check' => 'HTMLCheckField',
106 'toggle' => 'HTMLCheckField',
107 'int' => 'HTMLIntField',
108 'float' => 'HTMLFloatField',
109 'info' => 'HTMLInfoField',
110 'selectorother' => 'HTMLSelectOrOtherField',
111 'selectandother' => 'HTMLSelectAndOtherField',
112 'submit' => 'HTMLSubmitField',
113 'hidden' => 'HTMLHiddenField',
114 'edittools' => 'HTMLEditTools',
115 'checkmatrix' => 'HTMLCheckMatrix',
117 // HTMLTextField will output the correct type="" attribute automagically.
118 // There are about four zillion other HTML5 input types, like url, but
119 // we don't use those at the moment, so no point in adding all of them.
120 'email' => 'HTMLTextField',
121 'password' => 'HTMLTextField',
124 protected $mMessagePrefix;
126 /** @var HTMLFormField[] */
127 protected $mFlatFields;
129 protected $mFieldTree;
130 protected $mShowReset = false;
131 protected $mShowSubmit = true;
132 public $mFieldData;
134 protected $mSubmitCallback;
135 protected $mValidationErrorMessage;
137 protected $mPre = '';
138 protected $mHeader = '';
139 protected $mFooter = '';
140 protected $mSectionHeaders = array();
141 protected $mSectionFooters = array();
142 protected $mPost = '';
143 protected $mId;
145 protected $mSubmitID;
146 protected $mSubmitName;
147 protected $mSubmitText;
148 protected $mSubmitTooltip;
150 protected $mTitle;
151 protected $mMethod = 'post';
154 * Form action URL. false means we will use the URL to set Title
155 * @since 1.19
156 * @var bool|string
158 protected $mAction = false;
160 protected $mUseMultipart = false;
161 protected $mHiddenFields = array();
162 protected $mButtons = array();
164 protected $mWrapperLegend = false;
167 * If true, sections that contain both fields and subsections will
168 * render their subsections before their fields.
170 * Subclasses may set this to false to render subsections after fields
171 * instead.
173 protected $mSubSectionBeforeFields = true;
176 * Format in which to display form. For viable options,
177 * @see $availableDisplayFormats
178 * @var String
180 protected $displayFormat = 'table';
183 * Available formats in which to display the form
184 * @var Array
186 protected $availableDisplayFormats = array(
187 'table',
188 'div',
189 'raw',
193 * Build a new HTMLForm from an array of field attributes
194 * @param array $descriptor of Field constructs, as described above
195 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
196 * Obviates the need to call $form->setTitle()
197 * @param string $messagePrefix a prefix to go in front of default messages
199 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
200 if ( $context instanceof IContextSource ) {
201 $this->setContext( $context );
202 $this->mTitle = false; // We don't need them to set a title
203 $this->mMessagePrefix = $messagePrefix;
204 } else {
205 // B/C since 1.18
206 if ( is_string( $context ) && $messagePrefix === '' ) {
207 // it's actually $messagePrefix
208 $this->mMessagePrefix = $context;
212 // Expand out into a tree.
213 $loadedDescriptor = array();
214 $this->mFlatFields = array();
216 foreach ( $descriptor as $fieldname => $info ) {
217 $section = isset( $info['section'] )
218 ? $info['section']
219 : '';
221 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
222 $this->mUseMultipart = true;
225 $field = self::loadInputFromParameters( $fieldname, $info );
226 $field->mParent = $this;
228 $setSection =& $loadedDescriptor;
229 if ( $section ) {
230 $sectionParts = explode( '/', $section );
232 while ( count( $sectionParts ) ) {
233 $newName = array_shift( $sectionParts );
235 if ( !isset( $setSection[$newName] ) ) {
236 $setSection[$newName] = array();
239 $setSection =& $setSection[$newName];
243 $setSection[$fieldname] = $field;
244 $this->mFlatFields[$fieldname] = $field;
247 $this->mFieldTree = $loadedDescriptor;
251 * Set format in which to display the form
252 * @param string $format the name of the format to use, must be one of
253 * $this->availableDisplayFormats
254 * @throws MWException
255 * @since 1.20
256 * @return HTMLForm $this for chaining calls (since 1.20)
258 public function setDisplayFormat( $format ) {
259 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
260 throw new MWException( 'Display format must be one of ' . print_r( $this->availableDisplayFormats, true ) );
262 $this->displayFormat = $format;
263 return $this;
267 * Getter for displayFormat
268 * @since 1.20
269 * @return String
271 public function getDisplayFormat() {
272 return $this->displayFormat;
276 * Add the HTMLForm-specific JavaScript, if it hasn't been
277 * done already.
278 * @deprecated since 1.18 load modules with ResourceLoader instead
280 static function addJS() {
281 wfDeprecated( __METHOD__, '1.18' );
285 * Initialise a new Object for the field
286 * @param $fieldname string
287 * @param string $descriptor input Descriptor, as described above
288 * @throws MWException
289 * @return HTMLFormField subclass
291 static function loadInputFromParameters( $fieldname, $descriptor ) {
292 if ( isset( $descriptor['class'] ) ) {
293 $class = $descriptor['class'];
294 } elseif ( isset( $descriptor['type'] ) ) {
295 $class = self::$typeMappings[$descriptor['type']];
296 $descriptor['class'] = $class;
297 } else {
298 $class = null;
301 if ( !$class ) {
302 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
305 $descriptor['fieldname'] = $fieldname;
307 # TODO
308 # This will throw a fatal error whenever someone try to use
309 # 'class' to feed a CSS class instead of 'cssclass'. Would be
310 # great to avoid the fatal error and show a nice error.
311 $obj = new $class( $descriptor );
313 return $obj;
317 * Prepare form for submission.
319 * @attention When doing method chaining, that should be the very last
320 * method call before displayForm().
322 * @throws MWException
323 * @return HTMLForm $this for chaining calls (since 1.20)
325 function prepareForm() {
326 # Check if we have the info we need
327 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
328 throw new MWException( "You must call setTitle() on an HTMLForm" );
331 # Load data from the request.
332 $this->loadData();
333 return $this;
337 * Try submitting, with edit token check first
338 * @return Status|boolean
340 function tryAuthorizedSubmit() {
341 $result = false;
343 $submit = false;
344 if ( $this->getMethod() != 'post' ) {
345 $submit = true; // no session check needed
346 } elseif ( $this->getRequest()->wasPosted() ) {
347 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
348 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
349 // Session tokens for logged-out users have no security value.
350 // However, if the user gave one, check it in order to give a nice
351 // "session expired" error instead of "permission denied" or such.
352 $submit = $this->getUser()->matchEditToken( $editToken );
353 } else {
354 $submit = true;
358 if ( $submit ) {
359 $result = $this->trySubmit();
362 return $result;
366 * The here's-one-I-made-earlier option: do the submission if
367 * posted, or display the form with or without funky validation
368 * errors
369 * @return Bool or Status whether submission was successful.
371 function show() {
372 $this->prepareForm();
374 $result = $this->tryAuthorizedSubmit();
375 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
376 return $result;
379 $this->displayForm( $result );
380 return false;
384 * Validate all the fields, and call the submission callback
385 * function if everything is kosher.
386 * @throws MWException
387 * @return Mixed Bool true == Successful submission, Bool false
388 * == No submission attempted, anything else == Error to
389 * display.
391 function trySubmit() {
392 # Check for validation
393 foreach ( $this->mFlatFields as $fieldname => $field ) {
394 if ( !empty( $field->mParams['nodata'] ) ) {
395 continue;
397 if ( $field->validate(
398 $this->mFieldData[$fieldname],
399 $this->mFieldData )
400 !== true
402 return isset( $this->mValidationErrorMessage )
403 ? $this->mValidationErrorMessage
404 : array( 'htmlform-invalid-input' );
408 $callback = $this->mSubmitCallback;
409 if ( !is_callable( $callback ) ) {
410 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
413 $data = $this->filterDataForSubmit( $this->mFieldData );
415 $res = call_user_func( $callback, $data, $this );
417 return $res;
421 * Set a callback to a function to do something with the form
422 * once it's been successfully validated.
423 * @param string $cb function name. The function will be passed
424 * the output from HTMLForm::filterDataForSubmit, and must
425 * return Bool true on success, Bool false if no submission
426 * was attempted, or String HTML output to display on error.
427 * @return HTMLForm $this for chaining calls (since 1.20)
429 function setSubmitCallback( $cb ) {
430 $this->mSubmitCallback = $cb;
431 return $this;
435 * Set a message to display on a validation error.
436 * @param $msg Mixed String or Array of valid inputs to wfMessage()
437 * (so each entry can be either a String or Array)
438 * @return HTMLForm $this for chaining calls (since 1.20)
440 function setValidationErrorMessage( $msg ) {
441 $this->mValidationErrorMessage = $msg;
442 return $this;
446 * Set the introductory message, overwriting any existing message.
447 * @param string $msg complete text of message to display
448 * @return HTMLForm $this for chaining calls (since 1.20)
450 function setIntro( $msg ) {
451 $this->setPreText( $msg );
452 return $this;
456 * Set the introductory message, overwriting any existing message.
457 * @since 1.19
458 * @param string $msg complete text of message to display
459 * @return HTMLForm $this for chaining calls (since 1.20)
461 function setPreText( $msg ) {
462 $this->mPre = $msg;
463 return $this;
467 * Add introductory text.
468 * @param string $msg complete text of message to display
469 * @return HTMLForm $this for chaining calls (since 1.20)
471 function addPreText( $msg ) {
472 $this->mPre .= $msg;
473 return $this;
477 * Add header text, inside the form.
478 * @param string $msg complete text of message to display
479 * @param string $section The section to add the header to
480 * @return HTMLForm $this for chaining calls (since 1.20)
482 function addHeaderText( $msg, $section = null ) {
483 if ( is_null( $section ) ) {
484 $this->mHeader .= $msg;
485 } else {
486 if ( !isset( $this->mSectionHeaders[$section] ) ) {
487 $this->mSectionHeaders[$section] = '';
489 $this->mSectionHeaders[$section] .= $msg;
491 return $this;
495 * Set header text, inside the form.
496 * @since 1.19
497 * @param string $msg complete text of message to display
498 * @param $section The section to add the header to
499 * @return HTMLForm $this for chaining calls (since 1.20)
501 function setHeaderText( $msg, $section = null ) {
502 if ( is_null( $section ) ) {
503 $this->mHeader = $msg;
504 } else {
505 $this->mSectionHeaders[$section] = $msg;
507 return $this;
511 * Add footer text, inside the form.
512 * @param string $msg complete text of message to display
513 * @param string $section The section to add the footer text to
514 * @return HTMLForm $this for chaining calls (since 1.20)
516 function addFooterText( $msg, $section = null ) {
517 if ( is_null( $section ) ) {
518 $this->mFooter .= $msg;
519 } else {
520 if ( !isset( $this->mSectionFooters[$section] ) ) {
521 $this->mSectionFooters[$section] = '';
523 $this->mSectionFooters[$section] .= $msg;
525 return $this;
529 * Set footer text, inside the form.
530 * @since 1.19
531 * @param string $msg complete text of message to display
532 * @param string $section The section to add the footer text to
533 * @return HTMLForm $this for chaining calls (since 1.20)
535 function setFooterText( $msg, $section = null ) {
536 if ( is_null( $section ) ) {
537 $this->mFooter = $msg;
538 } else {
539 $this->mSectionFooters[$section] = $msg;
541 return $this;
545 * Add text to the end of the display.
546 * @param string $msg complete text of message to display
547 * @return HTMLForm $this for chaining calls (since 1.20)
549 function addPostText( $msg ) {
550 $this->mPost .= $msg;
551 return $this;
555 * Set text at the end of the display.
556 * @param string $msg complete text of message to display
557 * @return HTMLForm $this for chaining calls (since 1.20)
559 function setPostText( $msg ) {
560 $this->mPost = $msg;
561 return $this;
565 * Add a hidden field to the output
566 * @param string $name field name. This will be used exactly as entered
567 * @param string $value field value
568 * @param $attribs Array
569 * @return HTMLForm $this for chaining calls (since 1.20)
571 public function addHiddenField( $name, $value, $attribs = array() ) {
572 $attribs += array( 'name' => $name );
573 $this->mHiddenFields[] = array( $value, $attribs );
574 return $this;
578 * Add a button to the form
579 * @param string $name field name.
580 * @param string $value field value
581 * @param string $id DOM id for the button (default: null)
582 * @param $attribs Array
583 * @return HTMLForm $this for chaining calls (since 1.20)
585 public function addButton( $name, $value, $id = null, $attribs = null ) {
586 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
587 return $this;
591 * Display the form (sending to $wgOut), with an appropriate error
592 * message or stack of messages, and any validation errors, etc.
594 * @attention You should call prepareForm() before calling this function.
595 * Moreover, when doing method chaining this should be the very last method
596 * call just after prepareForm().
598 * @param $submitResult Mixed output from HTMLForm::trySubmit()
599 * @return Nothing, should be last call
601 function displayForm( $submitResult ) {
602 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
606 * Returns the raw HTML generated by the form
607 * @param $submitResult Mixed output from HTMLForm::trySubmit()
608 * @return string
610 function getHTML( $submitResult ) {
611 # For good measure (it is the default)
612 $this->getOutput()->preventClickjacking();
613 $this->getOutput()->addModules( 'mediawiki.htmlform' );
615 $html = ''
616 . $this->getErrors( $submitResult )
617 . $this->mHeader
618 . $this->getBody()
619 . $this->getHiddenFields()
620 . $this->getButtons()
621 . $this->mFooter
624 $html = $this->wrapForm( $html );
626 return '' . $this->mPre . $html . $this->mPost;
630 * Wrap the form innards in an actual "<form>" element
631 * @param string $html HTML contents to wrap.
632 * @return String wrapped HTML.
634 function wrapForm( $html ) {
636 # Include a <fieldset> wrapper for style, if requested.
637 if ( $this->mWrapperLegend !== false ) {
638 $html = Xml::fieldset( $this->mWrapperLegend, $html );
640 # Use multipart/form-data
641 $encType = $this->mUseMultipart
642 ? 'multipart/form-data'
643 : 'application/x-www-form-urlencoded';
644 # Attributes
645 $attribs = array(
646 'action' => $this->mAction === false ? $this->getTitle()->getFullURL() : $this->mAction,
647 'method' => $this->mMethod,
648 'class' => 'visualClear',
649 'enctype' => $encType,
651 if ( !empty( $this->mId ) ) {
652 $attribs['id'] = $this->mId;
655 return Html::rawElement( 'form', $attribs, $html );
659 * Get the hidden fields that should go inside the form.
660 * @return String HTML.
662 function getHiddenFields() {
663 global $wgArticlePath;
665 $html = '';
666 if ( $this->getMethod() == 'post' ) {
667 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
668 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
671 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
672 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
675 foreach ( $this->mHiddenFields as $data ) {
676 list( $value, $attribs ) = $data;
677 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
680 return $html;
684 * Get the submit and (potentially) reset buttons.
685 * @return String HTML.
687 function getButtons() {
688 $html = '';
690 if ( $this->mShowSubmit ) {
691 $attribs = array();
693 if ( isset( $this->mSubmitID ) ) {
694 $attribs['id'] = $this->mSubmitID;
697 if ( isset( $this->mSubmitName ) ) {
698 $attribs['name'] = $this->mSubmitName;
701 if ( isset( $this->mSubmitTooltip ) ) {
702 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
705 $attribs['class'] = 'mw-htmlform-submit';
707 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
710 if ( $this->mShowReset ) {
711 $html .= Html::element(
712 'input',
713 array(
714 'type' => 'reset',
715 'value' => $this->msg( 'htmlform-reset' )->text()
717 ) . "\n";
720 foreach ( $this->mButtons as $button ) {
721 $attrs = array(
722 'type' => 'submit',
723 'name' => $button['name'],
724 'value' => $button['value']
727 if ( $button['attribs'] ) {
728 $attrs += $button['attribs'];
731 if ( isset( $button['id'] ) ) {
732 $attrs['id'] = $button['id'];
735 $html .= Html::element( 'input', $attrs );
738 return $html;
742 * Get the whole body of the form.
743 * @return String
745 function getBody() {
746 return $this->displaySection( $this->mFieldTree );
750 * Format and display an error message stack.
751 * @param $errors String|Array|Status
752 * @return String
754 function getErrors( $errors ) {
755 if ( $errors instanceof Status ) {
756 if ( $errors->isOK() ) {
757 $errorstr = '';
758 } else {
759 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
761 } elseif ( is_array( $errors ) ) {
762 $errorstr = $this->formatErrors( $errors );
763 } else {
764 $errorstr = $errors;
767 return $errorstr
768 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
769 : '';
773 * Format a stack of error messages into a single HTML string
774 * @param array $errors of message keys/values
775 * @return String HTML, a "<ul>" list of errors
777 public static function formatErrors( $errors ) {
778 $errorstr = '';
780 foreach ( $errors as $error ) {
781 if ( is_array( $error ) ) {
782 $msg = array_shift( $error );
783 } else {
784 $msg = $error;
785 $error = array();
788 $errorstr .= Html::rawElement(
789 'li',
790 array(),
791 wfMessage( $msg, $error )->parse()
795 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
797 return $errorstr;
801 * Set the text for the submit button
802 * @param string $t plaintext.
803 * @return HTMLForm $this for chaining calls (since 1.20)
805 function setSubmitText( $t ) {
806 $this->mSubmitText = $t;
807 return $this;
811 * Set the text for the submit button to a message
812 * @since 1.19
813 * @param string $msg message key
814 * @return HTMLForm $this for chaining calls (since 1.20)
816 public function setSubmitTextMsg( $msg ) {
817 $this->setSubmitText( $this->msg( $msg )->text() );
818 return $this;
822 * Get the text for the submit button, either customised or a default.
823 * @return string
825 function getSubmitText() {
826 return $this->mSubmitText
827 ? $this->mSubmitText
828 : $this->msg( 'htmlform-submit' )->text();
832 * @param string $name Submit button name
833 * @return HTMLForm $this for chaining calls (since 1.20)
835 public function setSubmitName( $name ) {
836 $this->mSubmitName = $name;
837 return $this;
841 * @param string $name Tooltip for the submit button
842 * @return HTMLForm $this for chaining calls (since 1.20)
844 public function setSubmitTooltip( $name ) {
845 $this->mSubmitTooltip = $name;
846 return $this;
850 * Set the id for the submit button.
851 * @param $t String.
852 * @todo FIXME: Integrity of $t is *not* validated
853 * @return HTMLForm $this for chaining calls (since 1.20)
855 function setSubmitID( $t ) {
856 $this->mSubmitID = $t;
857 return $this;
861 * Stop a default submit button being shown for this form. This implies that an
862 * alternate submit method must be provided manually.
864 * @since 1.22
866 * @param bool $suppressSubmit Set to false to re-enable the button again
868 * @return HTMLForm $this for chaining calls
870 function suppressDefaultSubmit( $suppressSubmit = true ) {
871 $this->mShowSubmit = !$suppressSubmit;
872 return $this;
876 * @param string $id DOM id for the form
877 * @return HTMLForm $this for chaining calls (since 1.20)
879 public function setId( $id ) {
880 $this->mId = $id;
881 return $this;
884 * Prompt the whole form to be wrapped in a "<fieldset>", with
885 * this text as its "<legend>" element.
886 * @param string $legend HTML to go inside the "<legend>" element.
887 * Will be escaped
888 * @return HTMLForm $this for chaining calls (since 1.20)
890 public function setWrapperLegend( $legend ) {
891 $this->mWrapperLegend = $legend;
892 return $this;
896 * Prompt the whole form to be wrapped in a "<fieldset>", with
897 * this message as its "<legend>" element.
898 * @since 1.19
899 * @param string $msg message key
900 * @return HTMLForm $this for chaining calls (since 1.20)
902 public function setWrapperLegendMsg( $msg ) {
903 $this->setWrapperLegend( $this->msg( $msg )->text() );
904 return $this;
908 * Set the prefix for various default messages
909 * @todo currently only used for the "<fieldset>" legend on forms
910 * with multiple sections; should be used elsewhere?
911 * @param $p String
912 * @return HTMLForm $this for chaining calls (since 1.20)
914 function setMessagePrefix( $p ) {
915 $this->mMessagePrefix = $p;
916 return $this;
920 * Set the title for form submission
921 * @param $t Title of page the form is on/should be posted to
922 * @return HTMLForm $this for chaining calls (since 1.20)
924 function setTitle( $t ) {
925 $this->mTitle = $t;
926 return $this;
930 * Get the title
931 * @return Title
933 function getTitle() {
934 return $this->mTitle === false
935 ? $this->getContext()->getTitle()
936 : $this->mTitle;
940 * Set the method used to submit the form
941 * @param $method String
942 * @return HTMLForm $this for chaining calls (since 1.20)
944 public function setMethod( $method = 'post' ) {
945 $this->mMethod = $method;
946 return $this;
949 public function getMethod() {
950 return $this->mMethod;
954 * @todo Document
955 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
956 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
957 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
958 * @return String
960 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
961 $displayFormat = $this->getDisplayFormat();
963 $html = '';
964 $subsectionHtml = '';
965 $hasLabel = false;
967 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ? 'getTableRow' : 'get' . ucfirst( $displayFormat );
969 foreach ( $fields as $key => $value ) {
970 if ( $value instanceof HTMLFormField ) {
971 $v = empty( $value->mParams['nodata'] )
972 ? $this->mFieldData[$key]
973 : $value->getDefault();
974 $html .= $value->$getFieldHtmlMethod( $v );
976 $labelValue = trim( $value->getLabel() );
977 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
978 $hasLabel = true;
980 } elseif ( is_array( $value ) ) {
981 $section = $this->displaySection( $value, $key, "$fieldsetIDPrefix$key-" );
982 $legend = $this->getLegend( $key );
983 if ( isset( $this->mSectionHeaders[$key] ) ) {
984 $section = $this->mSectionHeaders[$key] . $section;
986 if ( isset( $this->mSectionFooters[$key] ) ) {
987 $section .= $this->mSectionFooters[$key];
989 $attributes = array();
990 if ( $fieldsetIDPrefix ) {
991 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
993 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
997 if ( $displayFormat !== 'raw' ) {
998 $classes = array();
1000 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1001 $classes[] = 'mw-htmlform-nolabel';
1004 $attribs = array(
1005 'class' => implode( ' ', $classes ),
1008 if ( $sectionName ) {
1009 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
1012 if ( $displayFormat === 'table' ) {
1013 $html = Html::rawElement( 'table', $attribs,
1014 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1015 } elseif ( $displayFormat === 'div' ) {
1016 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1020 if ( $this->mSubSectionBeforeFields ) {
1021 return $subsectionHtml . "\n" . $html;
1022 } else {
1023 return $html . "\n" . $subsectionHtml;
1028 * Construct the form fields from the Descriptor array
1030 function loadData() {
1031 $fieldData = array();
1033 foreach ( $this->mFlatFields as $fieldname => $field ) {
1034 if ( !empty( $field->mParams['nodata'] ) ) {
1035 continue;
1036 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1037 $fieldData[$fieldname] = $field->getDefault();
1038 } else {
1039 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1043 # Filter data.
1044 foreach ( $fieldData as $name => &$value ) {
1045 $field = $this->mFlatFields[$name];
1046 $value = $field->filter( $value, $this->mFlatFields );
1049 $this->mFieldData = $fieldData;
1053 * Stop a reset button being shown for this form
1054 * @param bool $suppressReset set to false to re-enable the
1055 * button again
1056 * @return HTMLForm $this for chaining calls (since 1.20)
1058 function suppressReset( $suppressReset = true ) {
1059 $this->mShowReset = !$suppressReset;
1060 return $this;
1064 * Overload this if you want to apply special filtration routines
1065 * to the form as a whole, after it's submitted but before it's
1066 * processed.
1067 * @param $data
1068 * @return
1070 function filterDataForSubmit( $data ) {
1071 return $data;
1075 * Get a string to go in the "<legend>" of a section fieldset.
1076 * Override this if you want something more complicated.
1077 * @param $key String
1078 * @return String
1080 public function getLegend( $key ) {
1081 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1085 * Set the value for the action attribute of the form.
1086 * When set to false (which is the default state), the set title is used.
1088 * @since 1.19
1090 * @param string|bool $action
1091 * @return HTMLForm $this for chaining calls (since 1.20)
1093 public function setAction( $action ) {
1094 $this->mAction = $action;
1095 return $this;
1101 * The parent class to generate form fields. Any field type should
1102 * be a subclass of this.
1104 abstract class HTMLFormField {
1106 protected $mValidationCallback;
1107 protected $mFilterCallback;
1108 protected $mName;
1109 public $mParams;
1110 protected $mLabel; # String label. Set on construction
1111 protected $mID;
1112 protected $mClass = '';
1113 protected $mDefault;
1116 * @var HTMLForm
1118 public $mParent;
1121 * This function must be implemented to return the HTML to generate
1122 * the input object itself. It should not implement the surrounding
1123 * table cells/rows, or labels/help messages.
1124 * @param string $value the value to set the input to; eg a default
1125 * text for a text input.
1126 * @return String valid HTML.
1128 abstract function getInputHTML( $value );
1131 * Get a translated interface message
1133 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1134 * and wfMessage() otherwise.
1136 * Parameters are the same as wfMessage().
1138 * @return Message object
1140 function msg() {
1141 $args = func_get_args();
1143 if ( $this->mParent ) {
1144 $callback = array( $this->mParent, 'msg' );
1145 } else {
1146 $callback = 'wfMessage';
1149 return call_user_func_array( $callback, $args );
1153 * Override this function to add specific validation checks on the
1154 * field input. Don't forget to call parent::validate() to ensure
1155 * that the user-defined callback mValidationCallback is still run
1156 * @param string $value the value the field was submitted with
1157 * @param array $alldata the data collected from the form
1158 * @return Mixed Bool true on success, or String error to display.
1160 function validate( $value, $alldata ) {
1161 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1162 return $this->msg( 'htmlform-required' )->parse();
1165 if ( isset( $this->mValidationCallback ) ) {
1166 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1169 return true;
1172 function filter( $value, $alldata ) {
1173 if ( isset( $this->mFilterCallback ) ) {
1174 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1177 return $value;
1181 * Should this field have a label, or is there no input element with the
1182 * appropriate id for the label to point to?
1184 * @return bool True to output a label, false to suppress
1186 protected function needsLabel() {
1187 return true;
1191 * Get the value that this input has been set to from a posted form,
1192 * or the input's default value if it has not been set.
1193 * @param $request WebRequest
1194 * @return String the value
1196 function loadDataFromRequest( $request ) {
1197 if ( $request->getCheck( $this->mName ) ) {
1198 return $request->getText( $this->mName );
1199 } else {
1200 return $this->getDefault();
1205 * Initialise the object
1206 * @param array $params Associative Array. See HTMLForm doc for syntax.
1207 * @throws MWException
1209 function __construct( $params ) {
1210 $this->mParams = $params;
1212 # Generate the label from a message, if possible
1213 if ( isset( $params['label-message'] ) ) {
1214 $msgInfo = $params['label-message'];
1216 if ( is_array( $msgInfo ) ) {
1217 $msg = array_shift( $msgInfo );
1218 } else {
1219 $msg = $msgInfo;
1220 $msgInfo = array();
1223 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1224 } elseif ( isset( $params['label'] ) ) {
1225 $this->mLabel = $params['label'];
1228 $this->mName = "wp{$params['fieldname']}";
1229 if ( isset( $params['name'] ) ) {
1230 $this->mName = $params['name'];
1233 $validName = Sanitizer::escapeId( $this->mName );
1234 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1235 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1238 $this->mID = "mw-input-{$this->mName}";
1240 if ( isset( $params['default'] ) ) {
1241 $this->mDefault = $params['default'];
1244 if ( isset( $params['id'] ) ) {
1245 $id = $params['id'];
1246 $validId = Sanitizer::escapeId( $id );
1248 if ( $id != $validId ) {
1249 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1252 $this->mID = $id;
1255 if ( isset( $params['cssclass'] ) ) {
1256 $this->mClass = $params['cssclass'];
1259 if ( isset( $params['validation-callback'] ) ) {
1260 $this->mValidationCallback = $params['validation-callback'];
1263 if ( isset( $params['filter-callback'] ) ) {
1264 $this->mFilterCallback = $params['filter-callback'];
1267 if ( isset( $params['flatlist'] ) ) {
1268 $this->mClass .= ' mw-htmlform-flatlist';
1273 * Get the complete table row for the input, including help text,
1274 * labels, and whatever.
1275 * @param string $value the value to set the input to.
1276 * @return String complete HTML table row.
1278 function getTableRow( $value ) {
1279 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1280 $inputHtml = $this->getInputHTML( $value );
1281 $fieldType = get_class( $this );
1282 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1283 $cellAttributes = array();
1285 if ( !empty( $this->mParams['vertical-label'] ) ) {
1286 $cellAttributes['colspan'] = 2;
1287 $verticalLabel = true;
1288 } else {
1289 $verticalLabel = false;
1292 $label = $this->getLabelHtml( $cellAttributes );
1294 $field = Html::rawElement(
1295 'td',
1296 array( 'class' => 'mw-input' ) + $cellAttributes,
1297 $inputHtml . "\n$errors"
1300 if ( $verticalLabel ) {
1301 $html = Html::rawElement( 'tr',
1302 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1303 $html .= Html::rawElement( 'tr',
1304 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1305 $field );
1306 } else {
1307 $html = Html::rawElement( 'tr',
1308 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1309 $label . $field );
1312 return $html . $helptext;
1316 * Get the complete div for the input, including help text,
1317 * labels, and whatever.
1318 * @since 1.20
1319 * @param string $value the value to set the input to.
1320 * @return String complete HTML table row.
1322 public function getDiv( $value ) {
1323 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1324 $inputHtml = $this->getInputHTML( $value );
1325 $fieldType = get_class( $this );
1326 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1327 $cellAttributes = array();
1328 $label = $this->getLabelHtml( $cellAttributes );
1330 $field = Html::rawElement(
1331 'div',
1332 array( 'class' => 'mw-input' ) + $cellAttributes,
1333 $inputHtml . "\n$errors"
1335 $html = Html::rawElement( 'div',
1336 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1337 $label . $field );
1338 $html .= $helptext;
1339 return $html;
1343 * Get the complete raw fields for the input, including help text,
1344 * labels, and whatever.
1345 * @since 1.20
1346 * @param string $value the value to set the input to.
1347 * @return String complete HTML table row.
1349 public function getRaw( $value ) {
1350 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1351 $inputHtml = $this->getInputHTML( $value );
1352 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1353 $cellAttributes = array();
1354 $label = $this->getLabelHtml( $cellAttributes );
1356 $html = "\n$errors";
1357 $html .= $label;
1358 $html .= $inputHtml;
1359 $html .= $helptext;
1360 return $html;
1364 * Generate help text HTML in table format
1365 * @since 1.20
1366 * @param $helptext String|null
1367 * @return String
1369 public function getHelpTextHtmlTable( $helptext ) {
1370 if ( is_null( $helptext ) ) {
1371 return '';
1374 $row = Html::rawElement(
1375 'td',
1376 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1377 $helptext
1379 $row = Html::rawElement( 'tr', array(), $row );
1380 return $row;
1384 * Generate help text HTML in div format
1385 * @since 1.20
1386 * @param $helptext String|null
1387 * @return String
1389 public function getHelpTextHtmlDiv( $helptext ) {
1390 if ( is_null( $helptext ) ) {
1391 return '';
1394 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1395 return $div;
1399 * Generate help text HTML formatted for raw output
1400 * @since 1.20
1401 * @param $helptext String|null
1402 * @return String
1404 public function getHelpTextHtmlRaw( $helptext ) {
1405 return $this->getHelpTextHtmlDiv( $helptext );
1409 * Determine the help text to display
1410 * @since 1.20
1411 * @return String
1413 public function getHelpText() {
1414 $helptext = null;
1416 if ( isset( $this->mParams['help-message'] ) ) {
1417 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1420 if ( isset( $this->mParams['help-messages'] ) ) {
1421 foreach ( $this->mParams['help-messages'] as $name ) {
1422 $helpMessage = (array)$name;
1423 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1425 if ( $msg->exists() ) {
1426 if ( is_null( $helptext ) ) {
1427 $helptext = '';
1428 } else {
1429 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1431 $helptext .= $msg->parse(); // Append message
1435 elseif ( isset( $this->mParams['help'] ) ) {
1436 $helptext = $this->mParams['help'];
1438 return $helptext;
1442 * Determine form errors to display and their classes
1443 * @since 1.20
1444 * @param string $value the value of the input
1445 * @return Array
1447 public function getErrorsAndErrorClass( $value ) {
1448 $errors = $this->validate( $value, $this->mParent->mFieldData );
1450 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1451 $errors = '';
1452 $errorClass = '';
1453 } else {
1454 $errors = self::formatErrors( $errors );
1455 $errorClass = 'mw-htmlform-invalid-input';
1457 return array( $errors, $errorClass );
1460 function getLabel() {
1461 return $this->mLabel;
1464 function getLabelHtml( $cellAttributes = array() ) {
1465 # Don't output a for= attribute for labels with no associated input.
1466 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1467 $for = array();
1469 if ( $this->needsLabel() ) {
1470 $for['for'] = $this->mID;
1473 $displayFormat = $this->mParent->getDisplayFormat();
1474 $labelElement = Html::rawElement( 'label', $for, $this->getLabel() );
1476 if ( $displayFormat == 'table' ) {
1477 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1478 Html::rawElement( 'label', $for, $this->getLabel() )
1480 } elseif ( $displayFormat == 'div' ) {
1481 return Html::rawElement( 'div', array( 'class' => 'mw-label' ) + $cellAttributes,
1482 Html::rawElement( 'label', $for, $this->getLabel() )
1484 } else {
1485 return $labelElement;
1489 function getDefault() {
1490 if ( isset( $this->mDefault ) ) {
1491 return $this->mDefault;
1492 } else {
1493 return null;
1498 * Returns the attributes required for the tooltip and accesskey.
1500 * @return array Attributes
1502 public function getTooltipAndAccessKey() {
1503 if ( empty( $this->mParams['tooltip'] ) ) {
1504 return array();
1506 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1510 * flatten an array of options to a single array, for instance,
1511 * a set of "<options>" inside "<optgroups>".
1512 * @param array $options Associative Array with values either Strings
1513 * or Arrays
1514 * @return Array flattened input
1516 public static function flattenOptions( $options ) {
1517 $flatOpts = array();
1519 foreach ( $options as $value ) {
1520 if ( is_array( $value ) ) {
1521 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1522 } else {
1523 $flatOpts[] = $value;
1527 return $flatOpts;
1531 * Formats one or more errors as accepted by field validation-callback.
1532 * @param $errors String|Message|Array of strings or Message instances
1533 * @return String html
1534 * @since 1.18
1536 protected static function formatErrors( $errors ) {
1537 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1538 $errors = array_shift( $errors );
1541 if ( is_array( $errors ) ) {
1542 $lines = array();
1543 foreach ( $errors as $error ) {
1544 if ( $error instanceof Message ) {
1545 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1546 } else {
1547 $lines[] = Html::rawElement( 'li', array(), $error );
1550 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1551 } else {
1552 if ( $errors instanceof Message ) {
1553 $errors = $errors->parse();
1555 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1560 class HTMLTextField extends HTMLFormField {
1561 function getSize() {
1562 return isset( $this->mParams['size'] )
1563 ? $this->mParams['size']
1564 : 45;
1567 function getInputHTML( $value ) {
1568 $attribs = array(
1569 'id' => $this->mID,
1570 'name' => $this->mName,
1571 'size' => $this->getSize(),
1572 'value' => $value,
1573 ) + $this->getTooltipAndAccessKey();
1575 if ( $this->mClass !== '' ) {
1576 $attribs['class'] = $this->mClass;
1579 if ( !empty( $this->mParams['disabled'] ) ) {
1580 $attribs['disabled'] = 'disabled';
1583 # TODO: Enforce pattern, step, required, readonly on the server side as
1584 # well
1585 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1586 'placeholder', 'list', 'maxlength' );
1587 foreach ( $allowedParams as $param ) {
1588 if ( isset( $this->mParams[$param] ) ) {
1589 $attribs[$param] = $this->mParams[$param];
1593 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1594 if ( isset( $this->mParams[$param] ) ) {
1595 $attribs[$param] = '';
1599 # Implement tiny differences between some field variants
1600 # here, rather than creating a new class for each one which
1601 # is essentially just a clone of this one.
1602 if ( isset( $this->mParams['type'] ) ) {
1603 switch ( $this->mParams['type'] ) {
1604 case 'email':
1605 $attribs['type'] = 'email';
1606 break;
1607 case 'int':
1608 $attribs['type'] = 'number';
1609 break;
1610 case 'float':
1611 $attribs['type'] = 'number';
1612 $attribs['step'] = 'any';
1613 break;
1614 # Pass through
1615 case 'password':
1616 case 'file':
1617 $attribs['type'] = $this->mParams['type'];
1618 break;
1622 return Html::element( 'input', $attribs );
1625 class HTMLTextAreaField extends HTMLFormField {
1626 function getCols() {
1627 return isset( $this->mParams['cols'] )
1628 ? $this->mParams['cols']
1629 : 80;
1632 function getRows() {
1633 return isset( $this->mParams['rows'] )
1634 ? $this->mParams['rows']
1635 : 25;
1638 function getInputHTML( $value ) {
1639 $attribs = array(
1640 'id' => $this->mID,
1641 'name' => $this->mName,
1642 'cols' => $this->getCols(),
1643 'rows' => $this->getRows(),
1644 ) + $this->getTooltipAndAccessKey();
1646 if ( $this->mClass !== '' ) {
1647 $attribs['class'] = $this->mClass;
1650 if ( !empty( $this->mParams['disabled'] ) ) {
1651 $attribs['disabled'] = 'disabled';
1654 if ( !empty( $this->mParams['readonly'] ) ) {
1655 $attribs['readonly'] = 'readonly';
1658 if ( isset( $this->mParams['placeholder'] ) ) {
1659 $attribs['placeholder'] = $this->mParams['placeholder'];
1662 foreach ( array( 'required', 'autofocus' ) as $param ) {
1663 if ( isset( $this->mParams[$param] ) ) {
1664 $attribs[$param] = '';
1668 return Html::element( 'textarea', $attribs, $value );
1673 * A field that will contain a numeric value
1675 class HTMLFloatField extends HTMLTextField {
1676 function getSize() {
1677 return isset( $this->mParams['size'] )
1678 ? $this->mParams['size']
1679 : 20;
1682 function validate( $value, $alldata ) {
1683 $p = parent::validate( $value, $alldata );
1685 if ( $p !== true ) {
1686 return $p;
1689 $value = trim( $value );
1691 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1692 # with the addition that a leading '+' sign is ok.
1693 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1694 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1697 # The "int" part of these message names is rather confusing.
1698 # They make equal sense for all numbers.
1699 if ( isset( $this->mParams['min'] ) ) {
1700 $min = $this->mParams['min'];
1702 if ( $min > $value ) {
1703 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1707 if ( isset( $this->mParams['max'] ) ) {
1708 $max = $this->mParams['max'];
1710 if ( $max < $value ) {
1711 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1715 return true;
1720 * A field that must contain a number
1722 class HTMLIntField extends HTMLFloatField {
1723 function validate( $value, $alldata ) {
1724 $p = parent::validate( $value, $alldata );
1726 if ( $p !== true ) {
1727 return $p;
1730 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1731 # with the addition that a leading '+' sign is ok. Note that leading zeros
1732 # are fine, and will be left in the input, which is useful for things like
1733 # phone numbers when you know that they are integers (the HTML5 type=tel
1734 # input does not require its value to be numeric). If you want a tidier
1735 # value to, eg, save in the DB, clean it up with intval().
1736 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1738 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1741 return true;
1746 * A checkbox field
1748 class HTMLCheckField extends HTMLFormField {
1749 function getInputHTML( $value ) {
1750 if ( !empty( $this->mParams['invert'] ) ) {
1751 $value = !$value;
1754 $attr = $this->getTooltipAndAccessKey();
1755 $attr['id'] = $this->mID;
1757 if ( !empty( $this->mParams['disabled'] ) ) {
1758 $attr['disabled'] = 'disabled';
1761 if ( $this->mClass !== '' ) {
1762 $attr['class'] = $this->mClass;
1765 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1766 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1770 * For a checkbox, the label goes on the right hand side, and is
1771 * added in getInputHTML(), rather than HTMLFormField::getRow()
1772 * @return String
1774 function getLabel() {
1775 return '&#160;';
1779 * @param $request WebRequest
1780 * @return String
1782 function loadDataFromRequest( $request ) {
1783 $invert = false;
1784 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1785 $invert = true;
1788 // GetCheck won't work like we want for checks.
1789 // Fetch the value in either one of the two following case:
1790 // - we have a valid token (form got posted or GET forged by the user)
1791 // - checkbox name has a value (false or true), ie is not null
1792 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1793 // XOR has the following truth table, which is what we want
1794 // INVERT VALUE | OUTPUT
1795 // true true | false
1796 // false true | true
1797 // false false | false
1798 // true false | true
1799 return $request->getBool( $this->mName ) xor $invert;
1800 } else {
1801 return $this->getDefault();
1807 * A checkbox matrix
1808 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1809 * options, uses an array of rows and an array of columns to dynamically
1810 * construct a matrix of options.
1812 class HTMLCheckMatrix extends HTMLFormField {
1814 function validate( $value, $alldata ) {
1815 $rows = $this->mParams['rows'];
1816 $columns = $this->mParams['columns'];
1818 // Make sure user-defined validation callback is run
1819 $p = parent::validate( $value, $alldata );
1820 if ( $p !== true ) {
1821 return $p;
1824 // Make sure submitted value is an array
1825 if ( !is_array( $value ) ) {
1826 return false;
1829 // If all options are valid, array_intersect of the valid options
1830 // and the provided options will return the provided options.
1831 $validOptions = array();
1832 foreach ( $rows as $rowTag ) {
1833 foreach ( $columns as $columnTag ) {
1834 $validOptions[] = $columnTag . '-' . $rowTag;
1837 $validValues = array_intersect( $value, $validOptions );
1838 if ( count( $validValues ) == count( $value ) ) {
1839 return true;
1840 } else {
1841 return $this->msg( 'htmlform-select-badoption' )->parse();
1846 * Build a table containing a matrix of checkbox options.
1847 * The value of each option is a combination of the row tag and column tag.
1848 * mParams['rows'] is an array with row labels as keys and row tags as values.
1849 * mParams['columns'] is an array with column labels as keys and column tags as values.
1850 * @param array $value of the options that should be checked
1851 * @return String
1853 function getInputHTML( $value ) {
1854 $html = '';
1855 $tableContents = '';
1856 $attribs = array();
1857 $rows = $this->mParams['rows'];
1858 $columns = $this->mParams['columns'];
1860 // If the disabled param is set, disable all the options
1861 if ( !empty( $this->mParams['disabled'] ) ) {
1862 $attribs['disabled'] = 'disabled';
1865 // Build the column headers
1866 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
1867 foreach ( $columns as $columnLabel => $columnTag ) {
1868 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
1870 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
1872 // Build the options matrix
1873 foreach ( $rows as $rowLabel => $rowTag ) {
1874 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
1875 foreach ( $columns as $columnTag ) {
1876 // Knock out any options that are not wanted
1877 if ( isset( $this->mParams['remove-options'] )
1878 && in_array( "$columnTag-$rowTag", $this->mParams['remove-options'] ) )
1880 $rowContents .= Html::rawElement( 'td', array(), '&#160;' );
1881 } else {
1882 // Construct the checkbox
1883 $thisAttribs = array(
1884 'id' => "{$this->mID}-$columnTag-$rowTag",
1885 'value' => $columnTag . '-' . $rowTag
1887 $checkbox = Xml::check(
1888 $this->mName . '[]',
1889 in_array( $columnTag . '-' . $rowTag, (array)$value, true ),
1890 $attribs + $thisAttribs );
1891 $rowContents .= Html::rawElement( 'td', array(), $checkbox );
1894 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
1897 // Put it all in a table
1898 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
1899 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
1901 return $html;
1905 * Get the complete table row for the input, including help text,
1906 * labels, and whatever.
1907 * We override this function since the label should always be on a separate
1908 * line above the options in the case of a checkbox matrix, i.e. it's always
1909 * a "vertical-label".
1910 * @param string $value the value to set the input to
1911 * @return String complete HTML table row
1913 function getTableRow( $value ) {
1914 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1915 $inputHtml = $this->getInputHTML( $value );
1916 $fieldType = get_class( $this );
1917 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1918 $cellAttributes = array( 'colspan' => 2 );
1920 $label = $this->getLabelHtml( $cellAttributes );
1922 $field = Html::rawElement(
1923 'td',
1924 array( 'class' => 'mw-input' ) + $cellAttributes,
1925 $inputHtml . "\n$errors"
1928 $html = Html::rawElement( 'tr',
1929 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1930 $html .= Html::rawElement( 'tr',
1931 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1932 $field );
1934 return $html . $helptext;
1938 * @param $request WebRequest
1939 * @return Array
1941 function loadDataFromRequest( $request ) {
1942 if ( $this->mParent->getMethod() == 'post' ) {
1943 if ( $request->wasPosted() ) {
1944 // Checkboxes are not added to the request arrays if they're not checked,
1945 // so it's perfectly possible for there not to be an entry at all
1946 return $request->getArray( $this->mName, array() );
1947 } else {
1948 // That's ok, the user has not yet submitted the form, so show the defaults
1949 return $this->getDefault();
1951 } else {
1952 // This is the impossible case: if we look at $_GET and see no data for our
1953 // field, is it because the user has not yet submitted the form, or that they
1954 // have submitted it with all the options unchecked. We will have to assume the
1955 // latter, which basically means that you can't specify 'positive' defaults
1956 // for GET forms.
1957 return $request->getArray( $this->mName, array() );
1961 function getDefault() {
1962 if ( isset( $this->mDefault ) ) {
1963 return $this->mDefault;
1964 } else {
1965 return array();
1971 * A select dropdown field. Basically a wrapper for Xmlselect class
1973 class HTMLSelectField extends HTMLFormField {
1974 function validate( $value, $alldata ) {
1975 $p = parent::validate( $value, $alldata );
1977 if ( $p !== true ) {
1978 return $p;
1981 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1983 if ( in_array( $value, $validOptions ) ) {
1984 return true;
1985 } else {
1986 return $this->msg( 'htmlform-select-badoption' )->parse();
1990 function getInputHTML( $value ) {
1991 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1993 # If one of the options' 'name' is int(0), it is automatically selected.
1994 # because PHP sucks and thinks int(0) == 'some string'.
1995 # Working around this by forcing all of them to strings.
1996 foreach ( $this->mParams['options'] as &$opt ) {
1997 if ( is_int( $opt ) ) {
1998 $opt = strval( $opt );
2001 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2003 if ( !empty( $this->mParams['disabled'] ) ) {
2004 $select->setAttribute( 'disabled', 'disabled' );
2007 if ( $this->mClass !== '' ) {
2008 $select->setAttribute( 'class', $this->mClass );
2011 $select->addOptions( $this->mParams['options'] );
2013 return $select->getHTML();
2018 * Select dropdown field, with an additional "other" textbox.
2020 class HTMLSelectOrOtherField extends HTMLTextField {
2022 function __construct( $params ) {
2023 if ( !in_array( 'other', $params['options'], true ) ) {
2024 $msg = isset( $params['other'] ) ?
2025 $params['other'] :
2026 wfMessage( 'htmlform-selectorother-other' )->text();
2027 $params['options'][$msg] = 'other';
2030 parent::__construct( $params );
2033 static function forceToStringRecursive( $array ) {
2034 if ( is_array( $array ) ) {
2035 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2036 } else {
2037 return strval( $array );
2041 function getInputHTML( $value ) {
2042 $valInSelect = false;
2044 if ( $value !== false ) {
2045 $valInSelect = in_array(
2046 $value,
2047 HTMLFormField::flattenOptions( $this->mParams['options'] )
2051 $selected = $valInSelect ? $value : 'other';
2053 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2055 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2056 $select->addOptions( $opts );
2058 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2060 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2062 if ( !empty( $this->mParams['disabled'] ) ) {
2063 $select->setAttribute( 'disabled', 'disabled' );
2064 $tbAttribs['disabled'] = 'disabled';
2067 $select = $select->getHTML();
2069 if ( isset( $this->mParams['maxlength'] ) ) {
2070 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2073 if ( $this->mClass !== '' ) {
2074 $tbAttribs['class'] = $this->mClass;
2077 $textbox = Html::input(
2078 $this->mName . '-other',
2079 $valInSelect ? '' : $value,
2080 'text',
2081 $tbAttribs
2084 return "$select<br />\n$textbox";
2088 * @param $request WebRequest
2089 * @return String
2091 function loadDataFromRequest( $request ) {
2092 if ( $request->getCheck( $this->mName ) ) {
2093 $val = $request->getText( $this->mName );
2095 if ( $val == 'other' ) {
2096 $val = $request->getText( $this->mName . '-other' );
2099 return $val;
2100 } else {
2101 return $this->getDefault();
2107 * Multi-select field
2109 class HTMLMultiSelectField extends HTMLFormField {
2111 function validate( $value, $alldata ) {
2112 $p = parent::validate( $value, $alldata );
2114 if ( $p !== true ) {
2115 return $p;
2118 if ( !is_array( $value ) ) {
2119 return false;
2122 # If all options are valid, array_intersect of the valid options
2123 # and the provided options will return the provided options.
2124 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2126 $validValues = array_intersect( $value, $validOptions );
2127 if ( count( $validValues ) == count( $value ) ) {
2128 return true;
2129 } else {
2130 return $this->msg( 'htmlform-select-badoption' )->parse();
2134 function getInputHTML( $value ) {
2135 $html = $this->formatOptions( $this->mParams['options'], $value );
2137 return $html;
2140 function formatOptions( $options, $value ) {
2141 $html = '';
2143 $attribs = array();
2145 if ( !empty( $this->mParams['disabled'] ) ) {
2146 $attribs['disabled'] = 'disabled';
2149 foreach ( $options as $label => $info ) {
2150 if ( is_array( $info ) ) {
2151 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2152 $html .= $this->formatOptions( $info, $value );
2153 } else {
2154 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2156 $checkbox = Xml::check(
2157 $this->mName . '[]',
2158 in_array( $info, $value, true ),
2159 $attribs + $thisAttribs );
2160 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2162 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2166 return $html;
2170 * @param $request WebRequest
2171 * @return String
2173 function loadDataFromRequest( $request ) {
2174 if ( $this->mParent->getMethod() == 'post' ) {
2175 if ( $request->wasPosted() ) {
2176 # Checkboxes are just not added to the request arrays if they're not checked,
2177 # so it's perfectly possible for there not to be an entry at all
2178 return $request->getArray( $this->mName, array() );
2179 } else {
2180 # That's ok, the user has not yet submitted the form, so show the defaults
2181 return $this->getDefault();
2183 } else {
2184 # This is the impossible case: if we look at $_GET and see no data for our
2185 # field, is it because the user has not yet submitted the form, or that they
2186 # have submitted it with all the options unchecked? We will have to assume the
2187 # latter, which basically means that you can't specify 'positive' defaults
2188 # for GET forms.
2189 # @todo FIXME...
2190 return $request->getArray( $this->mName, array() );
2194 function getDefault() {
2195 if ( isset( $this->mDefault ) ) {
2196 return $this->mDefault;
2197 } else {
2198 return array();
2202 protected function needsLabel() {
2203 return false;
2208 * Double field with a dropdown list constructed from a system message in the format
2209 * * Optgroup header
2210 * ** <option value>
2211 * * New Optgroup header
2212 * Plus a text field underneath for an additional reason. The 'value' of the field is
2213 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2214 * select dropdown.
2215 * @todo FIXME: If made 'required', only the text field should be compulsory.
2217 class HTMLSelectAndOtherField extends HTMLSelectField {
2219 function __construct( $params ) {
2220 if ( array_key_exists( 'other', $params ) ) {
2221 } elseif ( array_key_exists( 'other-message', $params ) ) {
2222 $params['other'] = wfMessage( $params['other-message'] )->plain();
2223 } else {
2224 $params['other'] = null;
2227 if ( array_key_exists( 'options', $params ) ) {
2228 # Options array already specified
2229 } elseif ( array_key_exists( 'options-message', $params ) ) {
2230 # Generate options array from a system message
2231 $params['options'] = self::parseMessage(
2232 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2233 $params['other']
2235 } else {
2236 # Sulk
2237 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2239 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2241 parent::__construct( $params );
2245 * Build a drop-down box from a textual list.
2246 * @param string $string message text
2247 * @param string $otherName name of "other reason" option
2248 * @return Array
2249 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2251 public static function parseMessage( $string, $otherName = null ) {
2252 if ( $otherName === null ) {
2253 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2256 $optgroup = false;
2257 $options = array( $otherName => 'other' );
2259 foreach ( explode( "\n", $string ) as $option ) {
2260 $value = trim( $option );
2261 if ( $value == '' ) {
2262 continue;
2263 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2264 # A new group is starting...
2265 $value = trim( substr( $value, 1 ) );
2266 $optgroup = $value;
2267 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2268 # groupmember
2269 $opt = trim( substr( $value, 2 ) );
2270 if ( $optgroup === false ) {
2271 $options[$opt] = $opt;
2272 } else {
2273 $options[$optgroup][$opt] = $opt;
2275 } else {
2276 # groupless reason list
2277 $optgroup = false;
2278 $options[$option] = $option;
2282 return $options;
2285 function getInputHTML( $value ) {
2286 $select = parent::getInputHTML( $value[1] );
2288 $textAttribs = array(
2289 'id' => $this->mID . '-other',
2290 'size' => $this->getSize(),
2293 if ( $this->mClass !== '' ) {
2294 $textAttribs['class'] = $this->mClass;
2297 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2298 if ( isset( $this->mParams[$param] ) ) {
2299 $textAttribs[$param] = '';
2303 $textbox = Html::input(
2304 $this->mName . '-other',
2305 $value[2],
2306 'text',
2307 $textAttribs
2310 return "$select<br />\n$textbox";
2314 * @param $request WebRequest
2315 * @return Array("<overall message>","<select value>","<text field value>")
2317 function loadDataFromRequest( $request ) {
2318 if ( $request->getCheck( $this->mName ) ) {
2320 $list = $request->getText( $this->mName );
2321 $text = $request->getText( $this->mName . '-other' );
2323 if ( $list == 'other' ) {
2324 $final = $text;
2325 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2326 # User has spoofed the select form to give an option which wasn't
2327 # in the original offer. Sulk...
2328 $final = $text;
2329 } elseif ( $text == '' ) {
2330 $final = $list;
2331 } else {
2332 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2335 } else {
2336 $final = $this->getDefault();
2338 $list = 'other';
2339 $text = $final;
2340 foreach ( $this->mFlatOptions as $option ) {
2341 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2342 if ( strpos( $text, $match ) === 0 ) {
2343 $list = $option;
2344 $text = substr( $text, strlen( $match ) );
2345 break;
2349 return array( $final, $list, $text );
2352 function getSize() {
2353 return isset( $this->mParams['size'] )
2354 ? $this->mParams['size']
2355 : 45;
2358 function validate( $value, $alldata ) {
2359 # HTMLSelectField forces $value to be one of the options in the select
2360 # field, which is not useful here. But we do want the validation further up
2361 # the chain
2362 $p = parent::validate( $value[1], $alldata );
2364 if ( $p !== true ) {
2365 return $p;
2368 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2369 return $this->msg( 'htmlform-required' )->parse();
2372 return true;
2377 * Radio checkbox fields.
2379 class HTMLRadioField extends HTMLFormField {
2381 function validate( $value, $alldata ) {
2382 $p = parent::validate( $value, $alldata );
2384 if ( $p !== true ) {
2385 return $p;
2388 if ( !is_string( $value ) && !is_int( $value ) ) {
2389 return false;
2392 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2394 if ( in_array( $value, $validOptions ) ) {
2395 return true;
2396 } else {
2397 return $this->msg( 'htmlform-select-badoption' )->parse();
2402 * This returns a block of all the radio options, in one cell.
2403 * @see includes/HTMLFormField#getInputHTML()
2404 * @param $value String
2405 * @return String
2407 function getInputHTML( $value ) {
2408 $html = $this->formatOptions( $this->mParams['options'], $value );
2410 return $html;
2413 function formatOptions( $options, $value ) {
2414 $html = '';
2416 $attribs = array();
2417 if ( !empty( $this->mParams['disabled'] ) ) {
2418 $attribs['disabled'] = 'disabled';
2421 # TODO: should this produce an unordered list perhaps?
2422 foreach ( $options as $label => $info ) {
2423 if ( is_array( $info ) ) {
2424 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2425 $html .= $this->formatOptions( $info, $value );
2426 } else {
2427 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2428 $radio = Xml::radio(
2429 $this->mName,
2430 $info,
2431 $info == $value,
2432 $attribs + array( 'id' => $id )
2434 $radio .= '&#160;' .
2435 Html::rawElement( 'label', array( 'for' => $id ), $label );
2437 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2441 return $html;
2444 protected function needsLabel() {
2445 return false;
2450 * An information field (text blob), not a proper input.
2452 class HTMLInfoField extends HTMLFormField {
2453 public function __construct( $info ) {
2454 $info['nodata'] = true;
2456 parent::__construct( $info );
2459 public function getInputHTML( $value ) {
2460 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2463 public function getTableRow( $value ) {
2464 if ( !empty( $this->mParams['rawrow'] ) ) {
2465 return $value;
2468 return parent::getTableRow( $value );
2472 * @since 1.20
2474 public function getDiv( $value ) {
2475 if ( !empty( $this->mParams['rawrow'] ) ) {
2476 return $value;
2479 return parent::getDiv( $value );
2483 * @since 1.20
2485 public function getRaw( $value ) {
2486 if ( !empty( $this->mParams['rawrow'] ) ) {
2487 return $value;
2490 return parent::getRaw( $value );
2493 protected function needsLabel() {
2494 return false;
2498 class HTMLHiddenField extends HTMLFormField {
2499 public function __construct( $params ) {
2500 parent::__construct( $params );
2502 # Per HTML5 spec, hidden fields cannot be 'required'
2503 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2504 unset( $this->mParams['required'] );
2507 public function getTableRow( $value ) {
2508 $params = array();
2509 if ( $this->mID ) {
2510 $params['id'] = $this->mID;
2513 $this->mParent->addHiddenField(
2514 $this->mName,
2515 $this->mDefault,
2516 $params
2519 return '';
2523 * @since 1.20
2525 public function getDiv( $value ) {
2526 return $this->getTableRow( $value );
2530 * @since 1.20
2532 public function getRaw( $value ) {
2533 return $this->getTableRow( $value );
2536 public function getInputHTML( $value ) {
2537 return '';
2542 * Add a submit button inline in the form (as opposed to
2543 * HTMLForm::addButton(), which will add it at the end).
2545 class HTMLSubmitField extends HTMLButtonField {
2546 protected $buttonType = 'submit';
2550 * Adds a generic button inline to the form. Does not do anything, you must add
2551 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2552 * wish to add a submit button to a form.
2554 * @since 1.22
2556 class HTMLButtonField extends HTMLFormField {
2557 protected $buttonType = 'button';
2559 public function __construct( $info ) {
2560 $info['nodata'] = true;
2561 parent::__construct( $info );
2564 public function getInputHTML( $value ) {
2565 $attr = array(
2566 'class' => 'mw-htmlform-submit ' . $this->mClass,
2567 'id' => $this->mID,
2570 if ( !empty( $this->mParams['disabled'] ) ) {
2571 $attr['disabled'] = 'disabled';
2574 return Html::input(
2575 $this->mName,
2576 $value,
2577 $this->buttonType,
2578 $attr
2582 protected function needsLabel() {
2583 return false;
2587 * Button cannot be invalid
2588 * @param $value String
2589 * @param $alldata Array
2590 * @return Bool
2592 public function validate( $value, $alldata ) {
2593 return true;
2597 class HTMLEditTools extends HTMLFormField {
2598 public function getInputHTML( $value ) {
2599 return '';
2602 public function getTableRow( $value ) {
2603 $msg = $this->formatMsg();
2605 return '<tr><td></td><td class="mw-input">'
2606 . '<div class="mw-editTools">'
2607 . $msg->parseAsBlock()
2608 . "</div></td></tr>\n";
2612 * @since 1.20
2614 public function getDiv( $value ) {
2615 $msg = $this->formatMsg();
2616 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2620 * @since 1.20
2622 public function getRaw( $value ) {
2623 return $this->getDiv( $value );
2626 protected function formatMsg() {
2627 if ( empty( $this->mParams['message'] ) ) {
2628 $msg = $this->msg( 'edittools' );
2629 } else {
2630 $msg = $this->msg( $this->mParams['message'] );
2631 if ( $msg->isDisabled() ) {
2632 $msg = $this->msg( 'edittools' );
2635 $msg->inContentLanguage();
2636 return $msg;
2640 class HTMLApiField extends HTMLFormField {
2641 public function getTableRow( $value ) {
2642 return '';
2645 public function getDiv( $value ) {
2646 return $this->getTableRow( $value );
2649 public function getRaw( $value ) {
2650 return $this->getTableRow( $value );
2653 public function getInputHTML( $value ) {
2654 return '';