Merge "Typo fix"
[mediawiki.git] / includes / HTMLForm.php
blobe06a934d761ae7b71ad4f71ae9b106e7ef438733
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 * ->prepareForm()
87 * ->displayForm( '' );
88 * @endcode
89 * Note that you will have prepareForm and displayForm at the end. Other
90 * methods call done after that would simply not be part of the form :(
92 * TODO: Document 'section' / 'subsection' stuff
94 class HTMLForm extends ContextSource {
96 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
97 private static $typeMappings = array(
98 'api' => 'HTMLApiField',
99 'text' => 'HTMLTextField',
100 'textarea' => 'HTMLTextAreaField',
101 'select' => 'HTMLSelectField',
102 'radio' => 'HTMLRadioField',
103 'multiselect' => 'HTMLMultiSelectField',
104 'check' => 'HTMLCheckField',
105 'toggle' => 'HTMLCheckField',
106 'int' => 'HTMLIntField',
107 'float' => 'HTMLFloatField',
108 'info' => 'HTMLInfoField',
109 'selectorother' => 'HTMLSelectOrOtherField',
110 'selectandother' => 'HTMLSelectAndOtherField',
111 'submit' => 'HTMLSubmitField',
112 'hidden' => 'HTMLHiddenField',
113 'edittools' => 'HTMLEditTools',
114 'checkmatrix' => 'HTMLCheckMatrix',
116 // HTMLTextField will output the correct type="" attribute automagically.
117 // There are about four zillion other HTML5 input types, like url, but
118 // we don't use those at the moment, so no point in adding all of them.
119 'email' => 'HTMLTextField',
120 'password' => 'HTMLTextField',
123 protected $mMessagePrefix;
125 /** @var HTMLFormField[] */
126 protected $mFlatFields;
128 protected $mFieldTree;
129 protected $mShowReset = false;
130 protected $mShowSubmit = true;
131 public $mFieldData;
133 protected $mSubmitCallback;
134 protected $mValidationErrorMessage;
136 protected $mPre = '';
137 protected $mHeader = '';
138 protected $mFooter = '';
139 protected $mSectionHeaders = array();
140 protected $mSectionFooters = array();
141 protected $mPost = '';
142 protected $mId;
143 protected $mTableId = '';
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 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
205 $this->mMessagePrefix = $messagePrefix;
206 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
207 // B/C since 1.18
208 // it's actually $messagePrefix
209 $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 the context's OutputPage object), with an
592 * appropriate error 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->getAction(),
647 'method' => $this->getMethod(),
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, $this->mTableId );
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 * Set the id of the \<table\> or outermost \<div\> element.
878 * @since 1.22
879 * @param string $id new value of the id attribute, or "" to remove
880 * @return HTMLForm $this for chaining calls
882 public function setTableId( $id ) {
883 $this->mTableId = $id;
884 return $this;
888 * @param string $id DOM id for the form
889 * @return HTMLForm $this for chaining calls (since 1.20)
891 public function setId( $id ) {
892 $this->mId = $id;
893 return $this;
897 * Prompt the whole form to be wrapped in a "<fieldset>", with
898 * this text as its "<legend>" element.
899 * @param string $legend HTML to go inside the "<legend>" element.
900 * Will be escaped
901 * @return HTMLForm $this for chaining calls (since 1.20)
903 public function setWrapperLegend( $legend ) {
904 $this->mWrapperLegend = $legend;
905 return $this;
909 * Prompt the whole form to be wrapped in a "<fieldset>", with
910 * this message as its "<legend>" element.
911 * @since 1.19
912 * @param string $msg message key
913 * @return HTMLForm $this for chaining calls (since 1.20)
915 public function setWrapperLegendMsg( $msg ) {
916 $this->setWrapperLegend( $this->msg( $msg )->text() );
917 return $this;
921 * Set the prefix for various default messages
922 * @todo currently only used for the "<fieldset>" legend on forms
923 * with multiple sections; should be used elsewhere?
924 * @param $p String
925 * @return HTMLForm $this for chaining calls (since 1.20)
927 function setMessagePrefix( $p ) {
928 $this->mMessagePrefix = $p;
929 return $this;
933 * Set the title for form submission
934 * @param $t Title of page the form is on/should be posted to
935 * @return HTMLForm $this for chaining calls (since 1.20)
937 function setTitle( $t ) {
938 $this->mTitle = $t;
939 return $this;
943 * Get the title
944 * @return Title
946 function getTitle() {
947 return $this->mTitle === false
948 ? $this->getContext()->getTitle()
949 : $this->mTitle;
953 * Set the method used to submit the form
954 * @param $method String
955 * @return HTMLForm $this for chaining calls (since 1.20)
957 public function setMethod( $method = 'post' ) {
958 $this->mMethod = $method;
959 return $this;
962 public function getMethod() {
963 return $this->mMethod;
967 * @todo Document
968 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
969 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
970 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
971 * @return String
973 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
974 $displayFormat = $this->getDisplayFormat();
976 $html = '';
977 $subsectionHtml = '';
978 $hasLabel = false;
980 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ? 'getTableRow' : 'get' . ucfirst( $displayFormat );
982 foreach ( $fields as $key => $value ) {
983 if ( $value instanceof HTMLFormField ) {
984 $v = empty( $value->mParams['nodata'] )
985 ? $this->mFieldData[$key]
986 : $value->getDefault();
987 $html .= $value->$getFieldHtmlMethod( $v );
989 $labelValue = trim( $value->getLabel() );
990 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
991 $hasLabel = true;
993 } elseif ( is_array( $value ) ) {
994 $section = $this->displaySection( $value, "mw-htmlform-$key", "$fieldsetIDPrefix$key-" );
995 $legend = $this->getLegend( $key );
996 if ( isset( $this->mSectionHeaders[$key] ) ) {
997 $section = $this->mSectionHeaders[$key] . $section;
999 if ( isset( $this->mSectionFooters[$key] ) ) {
1000 $section .= $this->mSectionFooters[$key];
1002 $attributes = array();
1003 if ( $fieldsetIDPrefix ) {
1004 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1006 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1010 if ( $displayFormat !== 'raw' ) {
1011 $classes = array();
1013 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1014 $classes[] = 'mw-htmlform-nolabel';
1017 $attribs = array(
1018 'class' => implode( ' ', $classes ),
1021 if ( $sectionName ) {
1022 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1025 if ( $displayFormat === 'table' ) {
1026 $html = Html::rawElement( 'table', $attribs,
1027 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1028 } elseif ( $displayFormat === 'div' ) {
1029 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1033 if ( $this->mSubSectionBeforeFields ) {
1034 return $subsectionHtml . "\n" . $html;
1035 } else {
1036 return $html . "\n" . $subsectionHtml;
1041 * Construct the form fields from the Descriptor array
1043 function loadData() {
1044 $fieldData = array();
1046 foreach ( $this->mFlatFields as $fieldname => $field ) {
1047 if ( !empty( $field->mParams['nodata'] ) ) {
1048 continue;
1049 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1050 $fieldData[$fieldname] = $field->getDefault();
1051 } else {
1052 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1056 # Filter data.
1057 foreach ( $fieldData as $name => &$value ) {
1058 $field = $this->mFlatFields[$name];
1059 $value = $field->filter( $value, $this->mFlatFields );
1062 $this->mFieldData = $fieldData;
1066 * Stop a reset button being shown for this form
1067 * @param bool $suppressReset set to false to re-enable the
1068 * button again
1069 * @return HTMLForm $this for chaining calls (since 1.20)
1071 function suppressReset( $suppressReset = true ) {
1072 $this->mShowReset = !$suppressReset;
1073 return $this;
1077 * Overload this if you want to apply special filtration routines
1078 * to the form as a whole, after it's submitted but before it's
1079 * processed.
1080 * @param $data
1081 * @return
1083 function filterDataForSubmit( $data ) {
1084 return $data;
1088 * Get a string to go in the "<legend>" of a section fieldset.
1089 * Override this if you want something more complicated.
1090 * @param $key String
1091 * @return String
1093 public function getLegend( $key ) {
1094 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1098 * Set the value for the action attribute of the form.
1099 * When set to false (which is the default state), the set title is used.
1101 * @since 1.19
1103 * @param string|bool $action
1104 * @return HTMLForm $this for chaining calls (since 1.20)
1106 public function setAction( $action ) {
1107 $this->mAction = $action;
1108 return $this;
1112 * Get the value for the action attribute of the form.
1114 * @since 1.22
1116 * @return string
1118 public function getAction() {
1119 global $wgScript, $wgArticlePath;
1121 // If an action is alredy provided, return it
1122 if ( $this->mAction !== false ) {
1123 return $this->mAction;
1126 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1127 // meaning that getLocalURL() would return something like "index.php?title=...".
1128 // As browser remove the query string before submitting GET forms,
1129 // it means that the title would be lost. In such case use $wgScript instead
1130 // and put title in an hidden field (see getHiddenFields()).
1131 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1132 return $wgScript;
1135 return $this->getTitle()->getLocalURL();
1140 * The parent class to generate form fields. Any field type should
1141 * be a subclass of this.
1143 abstract class HTMLFormField {
1145 protected $mValidationCallback;
1146 protected $mFilterCallback;
1147 protected $mName;
1148 public $mParams;
1149 protected $mLabel; # String label. Set on construction
1150 protected $mID;
1151 protected $mClass = '';
1152 protected $mDefault;
1155 * @var bool If true will generate an empty div element with no label
1156 * @since 1.22
1158 protected $mShowEmptyLabels = true;
1161 * @var HTMLForm
1163 public $mParent;
1166 * This function must be implemented to return the HTML to generate
1167 * the input object itself. It should not implement the surrounding
1168 * table cells/rows, or labels/help messages.
1169 * @param string $value the value to set the input to; eg a default
1170 * text for a text input.
1171 * @return String valid HTML.
1173 abstract function getInputHTML( $value );
1176 * Get a translated interface message
1178 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1179 * and wfMessage() otherwise.
1181 * Parameters are the same as wfMessage().
1183 * @return Message object
1185 function msg() {
1186 $args = func_get_args();
1188 if ( $this->mParent ) {
1189 $callback = array( $this->mParent, 'msg' );
1190 } else {
1191 $callback = 'wfMessage';
1194 return call_user_func_array( $callback, $args );
1198 * Override this function to add specific validation checks on the
1199 * field input. Don't forget to call parent::validate() to ensure
1200 * that the user-defined callback mValidationCallback is still run
1201 * @param string $value the value the field was submitted with
1202 * @param array $alldata the data collected from the form
1203 * @return Mixed Bool true on success, or String error to display.
1205 function validate( $value, $alldata ) {
1206 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1207 return $this->msg( 'htmlform-required' )->parse();
1210 if ( isset( $this->mValidationCallback ) ) {
1211 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1214 return true;
1217 function filter( $value, $alldata ) {
1218 if ( isset( $this->mFilterCallback ) ) {
1219 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1222 return $value;
1226 * Should this field have a label, or is there no input element with the
1227 * appropriate id for the label to point to?
1229 * @return bool True to output a label, false to suppress
1231 protected function needsLabel() {
1232 return true;
1236 * Get the value that this input has been set to from a posted form,
1237 * or the input's default value if it has not been set.
1238 * @param $request WebRequest
1239 * @return String the value
1241 function loadDataFromRequest( $request ) {
1242 if ( $request->getCheck( $this->mName ) ) {
1243 return $request->getText( $this->mName );
1244 } else {
1245 return $this->getDefault();
1250 * Initialise the object
1251 * @param array $params Associative Array. See HTMLForm doc for syntax.
1253 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
1254 * @throws MWException
1256 function __construct( $params ) {
1257 $this->mParams = $params;
1259 # Generate the label from a message, if possible
1260 if ( isset( $params['label-message'] ) ) {
1261 $msgInfo = $params['label-message'];
1263 if ( is_array( $msgInfo ) ) {
1264 $msg = array_shift( $msgInfo );
1265 } else {
1266 $msg = $msgInfo;
1267 $msgInfo = array();
1270 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1271 } elseif ( isset( $params['label'] ) ) {
1272 if ( $params['label'] === '&#160;' ) {
1273 // Apparently some things set &nbsp directly and in an odd format
1274 $this->mLabel = '&#160;';
1275 } else {
1276 $this->mLabel = htmlspecialchars( $params['label'] );
1278 } elseif ( isset( $params['label-raw'] ) ) {
1279 $this->mLabel = $params['label-raw'];
1282 $this->mName = "wp{$params['fieldname']}";
1283 if ( isset( $params['name'] ) ) {
1284 $this->mName = $params['name'];
1287 $validName = Sanitizer::escapeId( $this->mName );
1288 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1289 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1292 $this->mID = "mw-input-{$this->mName}";
1294 if ( isset( $params['default'] ) ) {
1295 $this->mDefault = $params['default'];
1298 if ( isset( $params['id'] ) ) {
1299 $id = $params['id'];
1300 $validId = Sanitizer::escapeId( $id );
1302 if ( $id != $validId ) {
1303 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1306 $this->mID = $id;
1309 if ( isset( $params['cssclass'] ) ) {
1310 $this->mClass = $params['cssclass'];
1313 if ( isset( $params['validation-callback'] ) ) {
1314 $this->mValidationCallback = $params['validation-callback'];
1317 if ( isset( $params['filter-callback'] ) ) {
1318 $this->mFilterCallback = $params['filter-callback'];
1321 if ( isset( $params['flatlist'] ) ) {
1322 $this->mClass .= ' mw-htmlform-flatlist';
1325 if ( isset( $params['hidelabel'] ) ) {
1326 $this->mShowEmptyLabels = false;
1331 * Get the complete table row for the input, including help text,
1332 * labels, and whatever.
1333 * @param string $value the value to set the input to.
1334 * @return String complete HTML table row.
1336 function getTableRow( $value ) {
1337 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1338 $inputHtml = $this->getInputHTML( $value );
1339 $fieldType = get_class( $this );
1340 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1341 $cellAttributes = array();
1343 if ( !empty( $this->mParams['vertical-label'] ) ) {
1344 $cellAttributes['colspan'] = 2;
1345 $verticalLabel = true;
1346 } else {
1347 $verticalLabel = false;
1350 $label = $this->getLabelHtml( $cellAttributes );
1352 $field = Html::rawElement(
1353 'td',
1354 array( 'class' => 'mw-input' ) + $cellAttributes,
1355 $inputHtml . "\n$errors"
1358 if ( $verticalLabel ) {
1359 $html = Html::rawElement( 'tr',
1360 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1361 $html .= Html::rawElement( 'tr',
1362 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1363 $field );
1364 } else {
1365 $html = Html::rawElement( 'tr',
1366 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1367 $label . $field );
1370 return $html . $helptext;
1374 * Get the complete div for the input, including help text,
1375 * labels, and whatever.
1376 * @since 1.20
1377 * @param string $value the value to set the input to.
1378 * @return String complete HTML table row.
1380 public function getDiv( $value ) {
1381 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1382 $inputHtml = $this->getInputHTML( $value );
1383 $fieldType = get_class( $this );
1384 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1385 $cellAttributes = array();
1386 $label = $this->getLabelHtml( $cellAttributes );
1388 $outerDivClass = array(
1389 'mw-input',
1390 'mw-htmlform-nolabel' => ( $label === '' )
1393 $field = Html::rawElement(
1394 'div',
1395 array( 'class' => $outerDivClass ) + $cellAttributes,
1396 $inputHtml . "\n$errors"
1398 $html = Html::rawElement( 'div',
1399 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1400 $label . $field );
1401 $html .= $helptext;
1402 return $html;
1406 * Get the complete raw fields for the input, including help text,
1407 * labels, and whatever.
1408 * @since 1.20
1409 * @param string $value the value to set the input to.
1410 * @return String complete HTML table row.
1412 public function getRaw( $value ) {
1413 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1414 $inputHtml = $this->getInputHTML( $value );
1415 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1416 $cellAttributes = array();
1417 $label = $this->getLabelHtml( $cellAttributes );
1419 $html = "\n$errors";
1420 $html .= $label;
1421 $html .= $inputHtml;
1422 $html .= $helptext;
1423 return $html;
1427 * Generate help text HTML in table format
1428 * @since 1.20
1429 * @param $helptext String|null
1430 * @return String
1432 public function getHelpTextHtmlTable( $helptext ) {
1433 if ( is_null( $helptext ) ) {
1434 return '';
1437 $row = Html::rawElement(
1438 'td',
1439 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1440 $helptext
1442 $row = Html::rawElement( 'tr', array(), $row );
1443 return $row;
1447 * Generate help text HTML in div format
1448 * @since 1.20
1449 * @param $helptext String|null
1450 * @return String
1452 public function getHelpTextHtmlDiv( $helptext ) {
1453 if ( is_null( $helptext ) ) {
1454 return '';
1457 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1458 return $div;
1462 * Generate help text HTML formatted for raw output
1463 * @since 1.20
1464 * @param $helptext String|null
1465 * @return String
1467 public function getHelpTextHtmlRaw( $helptext ) {
1468 return $this->getHelpTextHtmlDiv( $helptext );
1472 * Determine the help text to display
1473 * @since 1.20
1474 * @return String
1476 public function getHelpText() {
1477 $helptext = null;
1479 if ( isset( $this->mParams['help-message'] ) ) {
1480 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1483 if ( isset( $this->mParams['help-messages'] ) ) {
1484 foreach ( $this->mParams['help-messages'] as $name ) {
1485 $helpMessage = (array)$name;
1486 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1488 if ( $msg->exists() ) {
1489 if ( is_null( $helptext ) ) {
1490 $helptext = '';
1491 } else {
1492 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1494 $helptext .= $msg->parse(); // Append message
1498 elseif ( isset( $this->mParams['help'] ) ) {
1499 $helptext = $this->mParams['help'];
1501 return $helptext;
1505 * Determine form errors to display and their classes
1506 * @since 1.20
1507 * @param string $value the value of the input
1508 * @return Array
1510 public function getErrorsAndErrorClass( $value ) {
1511 $errors = $this->validate( $value, $this->mParent->mFieldData );
1513 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1514 $errors = '';
1515 $errorClass = '';
1516 } else {
1517 $errors = self::formatErrors( $errors );
1518 $errorClass = 'mw-htmlform-invalid-input';
1520 return array( $errors, $errorClass );
1523 function getLabel() {
1524 return is_null( $this->mLabel ) ? '' : $this->mLabel;
1527 function getLabelHtml( $cellAttributes = array() ) {
1528 # Don't output a for= attribute for labels with no associated input.
1529 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1530 $for = array();
1532 if ( $this->needsLabel() ) {
1533 $for['for'] = $this->mID;
1536 $labelValue = trim( $this->getLabel() );
1537 $hasLabel = false;
1538 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
1539 $hasLabel = true;
1542 $displayFormat = $this->mParent->getDisplayFormat();
1543 $html = '';
1545 if ( $displayFormat === 'table' ) {
1546 $html = Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1547 Html::rawElement( 'label', $for, $labelValue )
1549 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
1550 if ( $displayFormat === 'div' ) {
1551 $html = Html::rawElement(
1552 'div',
1553 array( 'class' => 'mw-label' ) + $cellAttributes,
1554 Html::rawElement( 'label', $for, $labelValue )
1556 } else {
1557 $html = Html::rawElement( 'label', $for, $labelValue );
1561 return $html;
1564 function getDefault() {
1565 if ( isset( $this->mDefault ) ) {
1566 return $this->mDefault;
1567 } else {
1568 return null;
1573 * Returns the attributes required for the tooltip and accesskey.
1575 * @return array Attributes
1577 public function getTooltipAndAccessKey() {
1578 if ( empty( $this->mParams['tooltip'] ) ) {
1579 return array();
1581 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1585 * flatten an array of options to a single array, for instance,
1586 * a set of "<options>" inside "<optgroups>".
1587 * @param array $options Associative Array with values either Strings
1588 * or Arrays
1589 * @return Array flattened input
1591 public static function flattenOptions( $options ) {
1592 $flatOpts = array();
1594 foreach ( $options as $value ) {
1595 if ( is_array( $value ) ) {
1596 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1597 } else {
1598 $flatOpts[] = $value;
1602 return $flatOpts;
1606 * Formats one or more errors as accepted by field validation-callback.
1607 * @param $errors String|Message|Array of strings or Message instances
1608 * @return String html
1609 * @since 1.18
1611 protected static function formatErrors( $errors ) {
1612 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1613 $errors = array_shift( $errors );
1616 if ( is_array( $errors ) ) {
1617 $lines = array();
1618 foreach ( $errors as $error ) {
1619 if ( $error instanceof Message ) {
1620 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1621 } else {
1622 $lines[] = Html::rawElement( 'li', array(), $error );
1625 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1626 } else {
1627 if ( $errors instanceof Message ) {
1628 $errors = $errors->parse();
1630 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1635 class HTMLTextField extends HTMLFormField {
1636 function getSize() {
1637 return isset( $this->mParams['size'] )
1638 ? $this->mParams['size']
1639 : 45;
1642 function getInputHTML( $value ) {
1643 $attribs = array(
1644 'id' => $this->mID,
1645 'name' => $this->mName,
1646 'size' => $this->getSize(),
1647 'value' => $value,
1648 ) + $this->getTooltipAndAccessKey();
1650 if ( $this->mClass !== '' ) {
1651 $attribs['class'] = $this->mClass;
1654 if ( !empty( $this->mParams['disabled'] ) ) {
1655 $attribs['disabled'] = 'disabled';
1658 # TODO: Enforce pattern, step, required, readonly on the server side as
1659 # well
1660 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1661 'placeholder', 'list', 'maxlength' );
1662 foreach ( $allowedParams as $param ) {
1663 if ( isset( $this->mParams[$param] ) ) {
1664 $attribs[$param] = $this->mParams[$param];
1668 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1669 if ( isset( $this->mParams[$param] ) ) {
1670 $attribs[$param] = '';
1674 # Implement tiny differences between some field variants
1675 # here, rather than creating a new class for each one which
1676 # is essentially just a clone of this one.
1677 if ( isset( $this->mParams['type'] ) ) {
1678 switch ( $this->mParams['type'] ) {
1679 case 'email':
1680 $attribs['type'] = 'email';
1681 break;
1682 case 'int':
1683 $attribs['type'] = 'number';
1684 break;
1685 case 'float':
1686 $attribs['type'] = 'number';
1687 $attribs['step'] = 'any';
1688 break;
1689 # Pass through
1690 case 'password':
1691 case 'file':
1692 $attribs['type'] = $this->mParams['type'];
1693 break;
1697 return Html::element( 'input', $attribs );
1700 class HTMLTextAreaField extends HTMLFormField {
1701 const DEFAULT_COLS = 80;
1702 const DEFAULT_ROWS = 25;
1704 function getCols() {
1705 return isset( $this->mParams['cols'] )
1706 ? $this->mParams['cols']
1707 : static::DEFAULT_COLS;
1710 function getRows() {
1711 return isset( $this->mParams['rows'] )
1712 ? $this->mParams['rows']
1713 : static::DEFAULT_ROWS;
1716 function getInputHTML( $value ) {
1717 $attribs = array(
1718 'id' => $this->mID,
1719 'name' => $this->mName,
1720 'cols' => $this->getCols(),
1721 'rows' => $this->getRows(),
1722 ) + $this->getTooltipAndAccessKey();
1724 if ( $this->mClass !== '' ) {
1725 $attribs['class'] = $this->mClass;
1728 if ( !empty( $this->mParams['disabled'] ) ) {
1729 $attribs['disabled'] = 'disabled';
1732 if ( !empty( $this->mParams['readonly'] ) ) {
1733 $attribs['readonly'] = 'readonly';
1736 if ( isset( $this->mParams['placeholder'] ) ) {
1737 $attribs['placeholder'] = $this->mParams['placeholder'];
1740 foreach ( array( 'required', 'autofocus' ) as $param ) {
1741 if ( isset( $this->mParams[$param] ) ) {
1742 $attribs[$param] = '';
1746 return Html::element( 'textarea', $attribs, $value );
1751 * A field that will contain a numeric value
1753 class HTMLFloatField extends HTMLTextField {
1754 function getSize() {
1755 return isset( $this->mParams['size'] )
1756 ? $this->mParams['size']
1757 : 20;
1760 function validate( $value, $alldata ) {
1761 $p = parent::validate( $value, $alldata );
1763 if ( $p !== true ) {
1764 return $p;
1767 $value = trim( $value );
1769 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1770 # with the addition that a leading '+' sign is ok.
1771 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1772 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1775 # The "int" part of these message names is rather confusing.
1776 # They make equal sense for all numbers.
1777 if ( isset( $this->mParams['min'] ) ) {
1778 $min = $this->mParams['min'];
1780 if ( $min > $value ) {
1781 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1785 if ( isset( $this->mParams['max'] ) ) {
1786 $max = $this->mParams['max'];
1788 if ( $max < $value ) {
1789 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1793 return true;
1798 * A field that must contain a number
1800 class HTMLIntField extends HTMLFloatField {
1801 function validate( $value, $alldata ) {
1802 $p = parent::validate( $value, $alldata );
1804 if ( $p !== true ) {
1805 return $p;
1808 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1809 # with the addition that a leading '+' sign is ok. Note that leading zeros
1810 # are fine, and will be left in the input, which is useful for things like
1811 # phone numbers when you know that they are integers (the HTML5 type=tel
1812 # input does not require its value to be numeric). If you want a tidier
1813 # value to, eg, save in the DB, clean it up with intval().
1814 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1816 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1819 return true;
1824 * A checkbox field
1826 class HTMLCheckField extends HTMLFormField {
1827 function getInputHTML( $value ) {
1828 if ( !empty( $this->mParams['invert'] ) ) {
1829 $value = !$value;
1832 $attr = $this->getTooltipAndAccessKey();
1833 $attr['id'] = $this->mID;
1835 if ( !empty( $this->mParams['disabled'] ) ) {
1836 $attr['disabled'] = 'disabled';
1839 if ( $this->mClass !== '' ) {
1840 $attr['class'] = $this->mClass;
1843 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1844 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1848 * For a checkbox, the label goes on the right hand side, and is
1849 * added in getInputHTML(), rather than HTMLFormField::getRow()
1850 * @return String
1852 function getLabel() {
1853 return '&#160;';
1857 * @param $request WebRequest
1858 * @return String
1860 function loadDataFromRequest( $request ) {
1861 $invert = false;
1862 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1863 $invert = true;
1866 // GetCheck won't work like we want for checks.
1867 // Fetch the value in either one of the two following case:
1868 // - we have a valid token (form got posted or GET forged by the user)
1869 // - checkbox name has a value (false or true), ie is not null
1870 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1871 // XOR has the following truth table, which is what we want
1872 // INVERT VALUE | OUTPUT
1873 // true true | false
1874 // false true | true
1875 // false false | false
1876 // true false | true
1877 return $request->getBool( $this->mName ) xor $invert;
1878 } else {
1879 return $this->getDefault();
1885 * A checkbox matrix
1886 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1887 * options, uses an array of rows and an array of columns to dynamically
1888 * construct a matrix of options. The tags used to identify a particular cell
1889 * are of the form "columnName-rowName"
1891 * Options:
1892 * - columns
1893 * - Required list of columns in the matrix.
1894 * - rows
1895 * - Required list of rows in the matrix.
1896 * - force-options-on
1897 * - Accepts array of column-row tags to be displayed as enabled but unavailable to change
1898 * - force-options-off
1899 * - Accepts array of column-row tags to be displayed as disabled but unavailable to change.
1900 * - tooltips
1901 * - Optional array mapping row label to tooltip content
1902 * - tooltip-class
1903 * - Optional CSS class used on tooltip container span. Defaults to mw-icon-question.
1905 class HTMLCheckMatrix extends HTMLFormField implements HTMLNestedFilterable {
1907 static private $requiredParams = array(
1908 // Required by underlying HTMLFormField
1909 'fieldname',
1910 // Required by HTMLCheckMatrix
1911 'rows', 'columns'
1914 public function __construct( $params ) {
1915 $missing = array_diff( self::$requiredParams, array_keys( $params ) );
1916 if ( $missing ) {
1917 throw new HTMLFormFieldRequiredOptionsException( $this, $missing );
1919 parent::__construct( $params );
1922 function validate( $value, $alldata ) {
1923 $rows = $this->mParams['rows'];
1924 $columns = $this->mParams['columns'];
1926 // Make sure user-defined validation callback is run
1927 $p = parent::validate( $value, $alldata );
1928 if ( $p !== true ) {
1929 return $p;
1932 // Make sure submitted value is an array
1933 if ( !is_array( $value ) ) {
1934 return false;
1937 // If all options are valid, array_intersect of the valid options
1938 // and the provided options will return the provided options.
1939 $validOptions = array();
1940 foreach ( $rows as $rowTag ) {
1941 foreach ( $columns as $columnTag ) {
1942 $validOptions[] = $columnTag . '-' . $rowTag;
1945 $validValues = array_intersect( $value, $validOptions );
1946 if ( count( $validValues ) == count( $value ) ) {
1947 return true;
1948 } else {
1949 return $this->msg( 'htmlform-select-badoption' )->parse();
1954 * Build a table containing a matrix of checkbox options.
1955 * The value of each option is a combination of the row tag and column tag.
1956 * mParams['rows'] is an array with row labels as keys and row tags as values.
1957 * mParams['columns'] is an array with column labels as keys and column tags as values.
1958 * @param array $value of the options that should be checked
1959 * @return String
1961 function getInputHTML( $value ) {
1962 $html = '';
1963 $tableContents = '';
1964 $attribs = array();
1965 $rows = $this->mParams['rows'];
1966 $columns = $this->mParams['columns'];
1968 // If the disabled param is set, disable all the options
1969 if ( !empty( $this->mParams['disabled'] ) ) {
1970 $attribs['disabled'] = 'disabled';
1973 // Build the column headers
1974 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
1975 foreach ( $columns as $columnLabel => $columnTag ) {
1976 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
1978 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
1980 $tooltipClass = 'mw-icon-question';
1981 if ( isset( $this->mParams['tooltip-class'] ) ) {
1982 $tooltipClass = $this->mParams['tooltip-class'];
1985 // Build the options matrix
1986 foreach ( $rows as $rowLabel => $rowTag ) {
1987 // Append tooltip if configured
1988 if ( isset( $this->mParams['tooltips'][$rowLabel] ) ) {
1989 $tooltipAttribs = array(
1990 'class' => "mw-htmlform-tooltip $tooltipClass",
1991 'title' => $this->mParams['tooltips'][$rowLabel],
1993 $rowLabel .= ' ' . Html::element( 'span', $tooltipAttribs, '' );
1995 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
1996 foreach ( $columns as $columnTag ) {
1997 $thisTag = "$columnTag-$rowTag";
1998 // Construct the checkbox
1999 $thisAttribs = array(
2000 'id' => "{$this->mID}-$thisTag",
2001 'value' => $thisTag,
2003 $checked = in_array( $thisTag, (array)$value, true );
2004 if ( $this->isTagForcedOff( $thisTag ) ) {
2005 $checked = false;
2006 $thisAttribs['disabled'] = 1;
2007 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2008 $checked = true;
2009 $thisAttribs['disabled'] = 1;
2011 $rowContents .= Html::rawElement(
2012 'td',
2013 array(),
2014 Xml::check( "{$this->mName}[]", $checked, $attribs + $thisAttribs )
2017 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
2020 // Put it all in a table
2021 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
2022 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
2024 return $html;
2027 protected function isTagForcedOff( $tag ) {
2028 return isset( $this->mParams['force-options-off'] )
2029 && in_array( $tag, $this->mParams['force-options-off'] );
2032 protected function isTagForcedOn( $tag ) {
2033 return isset( $this->mParams['force-options-on'] )
2034 && in_array( $tag, $this->mParams['force-options-on'] );
2038 * Get the complete table row for the input, including help text,
2039 * labels, and whatever.
2040 * We override this function since the label should always be on a separate
2041 * line above the options in the case of a checkbox matrix, i.e. it's always
2042 * a "vertical-label".
2043 * @param string $value the value to set the input to
2044 * @return String complete HTML table row
2046 function getTableRow( $value ) {
2047 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
2048 $inputHtml = $this->getInputHTML( $value );
2049 $fieldType = get_class( $this );
2050 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
2051 $cellAttributes = array( 'colspan' => 2 );
2053 $label = $this->getLabelHtml( $cellAttributes );
2055 $field = Html::rawElement(
2056 'td',
2057 array( 'class' => 'mw-input' ) + $cellAttributes,
2058 $inputHtml . "\n$errors"
2061 $html = Html::rawElement( 'tr',
2062 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
2063 $html .= Html::rawElement( 'tr',
2064 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
2065 $field );
2067 return $html . $helptext;
2071 * @param $request WebRequest
2072 * @return Array
2074 function loadDataFromRequest( $request ) {
2075 if ( $this->mParent->getMethod() == 'post' ) {
2076 if ( $request->wasPosted() ) {
2077 // Checkboxes are not added to the request arrays if they're not checked,
2078 // so it's perfectly possible for there not to be an entry at all
2079 return $request->getArray( $this->mName, array() );
2080 } else {
2081 // That's ok, the user has not yet submitted the form, so show the defaults
2082 return $this->getDefault();
2084 } else {
2085 // This is the impossible case: if we look at $_GET and see no data for our
2086 // field, is it because the user has not yet submitted the form, or that they
2087 // have submitted it with all the options unchecked. We will have to assume the
2088 // latter, which basically means that you can't specify 'positive' defaults
2089 // for GET forms.
2090 return $request->getArray( $this->mName, array() );
2094 function getDefault() {
2095 if ( isset( $this->mDefault ) ) {
2096 return $this->mDefault;
2097 } else {
2098 return array();
2102 function filterDataForSubmit( $data ) {
2103 $columns = HTMLFormField::flattenOptions( $this->mParams['columns'] );
2104 $rows = HTMLFormField::flattenOptions( $this->mParams['rows'] );
2105 $res = array();
2106 foreach ( $columns as $column ) {
2107 foreach ( $rows as $row ) {
2108 // Make sure option hasn't been forced
2109 $thisTag = "$column-$row";
2110 if ( $this->isTagForcedOff( $thisTag ) ) {
2111 $res[$thisTag] = false;
2112 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2113 $res[$thisTag] = true;
2114 } else {
2115 $res[$thisTag] = in_array( $thisTag, $data );
2120 return $res;
2125 * A select dropdown field. Basically a wrapper for Xmlselect class
2127 class HTMLSelectField extends HTMLFormField {
2128 function validate( $value, $alldata ) {
2129 $p = parent::validate( $value, $alldata );
2131 if ( $p !== true ) {
2132 return $p;
2135 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2137 if ( in_array( $value, $validOptions ) ) {
2138 return true;
2139 } else {
2140 return $this->msg( 'htmlform-select-badoption' )->parse();
2144 function getInputHTML( $value ) {
2145 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
2147 # If one of the options' 'name' is int(0), it is automatically selected.
2148 # because PHP sucks and thinks int(0) == 'some string'.
2149 # Working around this by forcing all of them to strings.
2150 foreach ( $this->mParams['options'] as &$opt ) {
2151 if ( is_int( $opt ) ) {
2152 $opt = strval( $opt );
2155 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2157 if ( !empty( $this->mParams['disabled'] ) ) {
2158 $select->setAttribute( 'disabled', 'disabled' );
2161 if ( $this->mClass !== '' ) {
2162 $select->setAttribute( 'class', $this->mClass );
2165 $select->addOptions( $this->mParams['options'] );
2167 return $select->getHTML();
2172 * Select dropdown field, with an additional "other" textbox.
2174 class HTMLSelectOrOtherField extends HTMLTextField {
2176 function __construct( $params ) {
2177 if ( !in_array( 'other', $params['options'], true ) ) {
2178 $msg = isset( $params['other'] ) ?
2179 $params['other'] :
2180 wfMessage( 'htmlform-selectorother-other' )->text();
2181 $params['options'][$msg] = 'other';
2184 parent::__construct( $params );
2187 static function forceToStringRecursive( $array ) {
2188 if ( is_array( $array ) ) {
2189 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2190 } else {
2191 return strval( $array );
2195 function getInputHTML( $value ) {
2196 $valInSelect = false;
2198 if ( $value !== false ) {
2199 $valInSelect = in_array(
2200 $value,
2201 HTMLFormField::flattenOptions( $this->mParams['options'] )
2205 $selected = $valInSelect ? $value : 'other';
2207 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2209 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2210 $select->addOptions( $opts );
2212 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2214 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2216 if ( !empty( $this->mParams['disabled'] ) ) {
2217 $select->setAttribute( 'disabled', 'disabled' );
2218 $tbAttribs['disabled'] = 'disabled';
2221 $select = $select->getHTML();
2223 if ( isset( $this->mParams['maxlength'] ) ) {
2224 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2227 if ( $this->mClass !== '' ) {
2228 $tbAttribs['class'] = $this->mClass;
2231 $textbox = Html::input(
2232 $this->mName . '-other',
2233 $valInSelect ? '' : $value,
2234 'text',
2235 $tbAttribs
2238 return "$select<br />\n$textbox";
2242 * @param $request WebRequest
2243 * @return String
2245 function loadDataFromRequest( $request ) {
2246 if ( $request->getCheck( $this->mName ) ) {
2247 $val = $request->getText( $this->mName );
2249 if ( $val == 'other' ) {
2250 $val = $request->getText( $this->mName . '-other' );
2253 return $val;
2254 } else {
2255 return $this->getDefault();
2261 * Multi-select field
2263 class HTMLMultiSelectField extends HTMLFormField implements HTMLNestedFilterable {
2265 function validate( $value, $alldata ) {
2266 $p = parent::validate( $value, $alldata );
2268 if ( $p !== true ) {
2269 return $p;
2272 if ( !is_array( $value ) ) {
2273 return false;
2276 # If all options are valid, array_intersect of the valid options
2277 # and the provided options will return the provided options.
2278 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2280 $validValues = array_intersect( $value, $validOptions );
2281 if ( count( $validValues ) == count( $value ) ) {
2282 return true;
2283 } else {
2284 return $this->msg( 'htmlform-select-badoption' )->parse();
2288 function getInputHTML( $value ) {
2289 $html = $this->formatOptions( $this->mParams['options'], $value );
2291 return $html;
2294 function formatOptions( $options, $value ) {
2295 $html = '';
2297 $attribs = array();
2299 if ( !empty( $this->mParams['disabled'] ) ) {
2300 $attribs['disabled'] = 'disabled';
2303 foreach ( $options as $label => $info ) {
2304 if ( is_array( $info ) ) {
2305 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2306 $html .= $this->formatOptions( $info, $value );
2307 } else {
2308 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2310 $checkbox = Xml::check(
2311 $this->mName . '[]',
2312 in_array( $info, $value, true ),
2313 $attribs + $thisAttribs );
2314 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2316 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2320 return $html;
2324 * @param $request WebRequest
2325 * @return String
2327 function loadDataFromRequest( $request ) {
2328 if ( $this->mParent->getMethod() == 'post' ) {
2329 if ( $request->wasPosted() ) {
2330 # Checkboxes are just not added to the request arrays if they're not checked,
2331 # so it's perfectly possible for there not to be an entry at all
2332 return $request->getArray( $this->mName, array() );
2333 } else {
2334 # That's ok, the user has not yet submitted the form, so show the defaults
2335 return $this->getDefault();
2337 } else {
2338 # This is the impossible case: if we look at $_GET and see no data for our
2339 # field, is it because the user has not yet submitted the form, or that they
2340 # have submitted it with all the options unchecked? We will have to assume the
2341 # latter, which basically means that you can't specify 'positive' defaults
2342 # for GET forms.
2343 # @todo FIXME...
2344 return $request->getArray( $this->mName, array() );
2348 function getDefault() {
2349 if ( isset( $this->mDefault ) ) {
2350 return $this->mDefault;
2351 } else {
2352 return array();
2356 function filterDataForSubmit( $data ) {
2357 $options = HTMLFormField::flattenOptions( $this->mParams['options'] );
2359 $res = array();
2360 foreach ( $options as $opt ) {
2361 $res["$opt"] = in_array( $opt, $data );
2364 return $res;
2367 protected function needsLabel() {
2368 return false;
2373 * Double field with a dropdown list constructed from a system message in the format
2374 * * Optgroup header
2375 * ** <option value>
2376 * * New Optgroup header
2377 * Plus a text field underneath for an additional reason. The 'value' of the field is
2378 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2379 * select dropdown.
2380 * @todo FIXME: If made 'required', only the text field should be compulsory.
2382 class HTMLSelectAndOtherField extends HTMLSelectField {
2384 function __construct( $params ) {
2385 if ( array_key_exists( 'other', $params ) ) {
2386 } elseif ( array_key_exists( 'other-message', $params ) ) {
2387 $params['other'] = wfMessage( $params['other-message'] )->plain();
2388 } else {
2389 $params['other'] = null;
2392 if ( array_key_exists( 'options', $params ) ) {
2393 # Options array already specified
2394 } elseif ( array_key_exists( 'options-message', $params ) ) {
2395 # Generate options array from a system message
2396 $params['options'] = self::parseMessage(
2397 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2398 $params['other']
2400 } else {
2401 # Sulk
2402 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2404 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2406 parent::__construct( $params );
2410 * Build a drop-down box from a textual list.
2411 * @param string $string message text
2412 * @param string $otherName name of "other reason" option
2413 * @return Array
2414 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2416 public static function parseMessage( $string, $otherName = null ) {
2417 if ( $otherName === null ) {
2418 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2421 $optgroup = false;
2422 $options = array( $otherName => 'other' );
2424 foreach ( explode( "\n", $string ) as $option ) {
2425 $value = trim( $option );
2426 if ( $value == '' ) {
2427 continue;
2428 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2429 # A new group is starting...
2430 $value = trim( substr( $value, 1 ) );
2431 $optgroup = $value;
2432 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2433 # groupmember
2434 $opt = trim( substr( $value, 2 ) );
2435 if ( $optgroup === false ) {
2436 $options[$opt] = $opt;
2437 } else {
2438 $options[$optgroup][$opt] = $opt;
2440 } else {
2441 # groupless reason list
2442 $optgroup = false;
2443 $options[$option] = $option;
2447 return $options;
2450 function getInputHTML( $value ) {
2451 $select = parent::getInputHTML( $value[1] );
2453 $textAttribs = array(
2454 'id' => $this->mID . '-other',
2455 'size' => $this->getSize(),
2458 if ( $this->mClass !== '' ) {
2459 $textAttribs['class'] = $this->mClass;
2462 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2463 if ( isset( $this->mParams[$param] ) ) {
2464 $textAttribs[$param] = '';
2468 $textbox = Html::input(
2469 $this->mName . '-other',
2470 $value[2],
2471 'text',
2472 $textAttribs
2475 return "$select<br />\n$textbox";
2479 * @param $request WebRequest
2480 * @return Array("<overall message>","<select value>","<text field value>")
2482 function loadDataFromRequest( $request ) {
2483 if ( $request->getCheck( $this->mName ) ) {
2485 $list = $request->getText( $this->mName );
2486 $text = $request->getText( $this->mName . '-other' );
2488 if ( $list == 'other' ) {
2489 $final = $text;
2490 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2491 # User has spoofed the select form to give an option which wasn't
2492 # in the original offer. Sulk...
2493 $final = $text;
2494 } elseif ( $text == '' ) {
2495 $final = $list;
2496 } else {
2497 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2500 } else {
2501 $final = $this->getDefault();
2503 $list = 'other';
2504 $text = $final;
2505 foreach ( $this->mFlatOptions as $option ) {
2506 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2507 if ( strpos( $text, $match ) === 0 ) {
2508 $list = $option;
2509 $text = substr( $text, strlen( $match ) );
2510 break;
2514 return array( $final, $list, $text );
2517 function getSize() {
2518 return isset( $this->mParams['size'] )
2519 ? $this->mParams['size']
2520 : 45;
2523 function validate( $value, $alldata ) {
2524 # HTMLSelectField forces $value to be one of the options in the select
2525 # field, which is not useful here. But we do want the validation further up
2526 # the chain
2527 $p = parent::validate( $value[1], $alldata );
2529 if ( $p !== true ) {
2530 return $p;
2533 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2534 return $this->msg( 'htmlform-required' )->parse();
2537 return true;
2542 * Radio checkbox fields.
2544 class HTMLRadioField extends HTMLFormField {
2546 function validate( $value, $alldata ) {
2547 $p = parent::validate( $value, $alldata );
2549 if ( $p !== true ) {
2550 return $p;
2553 if ( !is_string( $value ) && !is_int( $value ) ) {
2554 return false;
2557 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2559 if ( in_array( $value, $validOptions ) ) {
2560 return true;
2561 } else {
2562 return $this->msg( 'htmlform-select-badoption' )->parse();
2567 * This returns a block of all the radio options, in one cell.
2568 * @see includes/HTMLFormField#getInputHTML()
2569 * @param $value String
2570 * @return String
2572 function getInputHTML( $value ) {
2573 $html = $this->formatOptions( $this->mParams['options'], $value );
2575 return $html;
2578 function formatOptions( $options, $value ) {
2579 $html = '';
2581 $attribs = array();
2582 if ( !empty( $this->mParams['disabled'] ) ) {
2583 $attribs['disabled'] = 'disabled';
2586 # TODO: should this produce an unordered list perhaps?
2587 foreach ( $options as $label => $info ) {
2588 if ( is_array( $info ) ) {
2589 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2590 $html .= $this->formatOptions( $info, $value );
2591 } else {
2592 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2593 $radio = Xml::radio(
2594 $this->mName,
2595 $info,
2596 $info == $value,
2597 $attribs + array( 'id' => $id )
2599 $radio .= '&#160;' .
2600 Html::rawElement( 'label', array( 'for' => $id ), $label );
2602 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2606 return $html;
2609 protected function needsLabel() {
2610 return false;
2615 * An information field (text blob), not a proper input.
2617 class HTMLInfoField extends HTMLFormField {
2618 public function __construct( $info ) {
2619 $info['nodata'] = true;
2621 parent::__construct( $info );
2624 public function getInputHTML( $value ) {
2625 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2628 public function getTableRow( $value ) {
2629 if ( !empty( $this->mParams['rawrow'] ) ) {
2630 return $value;
2633 return parent::getTableRow( $value );
2637 * @since 1.20
2639 public function getDiv( $value ) {
2640 if ( !empty( $this->mParams['rawrow'] ) ) {
2641 return $value;
2644 return parent::getDiv( $value );
2648 * @since 1.20
2650 public function getRaw( $value ) {
2651 if ( !empty( $this->mParams['rawrow'] ) ) {
2652 return $value;
2655 return parent::getRaw( $value );
2658 protected function needsLabel() {
2659 return false;
2663 class HTMLHiddenField extends HTMLFormField {
2664 public function __construct( $params ) {
2665 parent::__construct( $params );
2667 # Per HTML5 spec, hidden fields cannot be 'required'
2668 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2669 unset( $this->mParams['required'] );
2672 public function getTableRow( $value ) {
2673 $params = array();
2674 if ( $this->mID ) {
2675 $params['id'] = $this->mID;
2678 $this->mParent->addHiddenField(
2679 $this->mName,
2680 $this->mDefault,
2681 $params
2684 return '';
2688 * @since 1.20
2690 public function getDiv( $value ) {
2691 return $this->getTableRow( $value );
2695 * @since 1.20
2697 public function getRaw( $value ) {
2698 return $this->getTableRow( $value );
2701 public function getInputHTML( $value ) {
2702 return '';
2707 * Add a submit button inline in the form (as opposed to
2708 * HTMLForm::addButton(), which will add it at the end).
2710 class HTMLSubmitField extends HTMLButtonField {
2711 protected $buttonType = 'submit';
2715 * Adds a generic button inline to the form. Does not do anything, you must add
2716 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2717 * wish to add a submit button to a form.
2719 * @since 1.22
2721 class HTMLButtonField extends HTMLFormField {
2722 protected $buttonType = 'button';
2724 public function __construct( $info ) {
2725 $info['nodata'] = true;
2726 parent::__construct( $info );
2729 public function getInputHTML( $value ) {
2730 $attr = array(
2731 'class' => 'mw-htmlform-submit ' . $this->mClass,
2732 'id' => $this->mID,
2735 if ( !empty( $this->mParams['disabled'] ) ) {
2736 $attr['disabled'] = 'disabled';
2739 return Html::input(
2740 $this->mName,
2741 $value,
2742 $this->buttonType,
2743 $attr
2747 protected function needsLabel() {
2748 return false;
2752 * Button cannot be invalid
2753 * @param $value String
2754 * @param $alldata Array
2755 * @return Bool
2757 public function validate( $value, $alldata ) {
2758 return true;
2762 class HTMLEditTools extends HTMLFormField {
2763 public function getInputHTML( $value ) {
2764 return '';
2767 public function getTableRow( $value ) {
2768 $msg = $this->formatMsg();
2770 return '<tr><td></td><td class="mw-input">'
2771 . '<div class="mw-editTools">'
2772 . $msg->parseAsBlock()
2773 . "</div></td></tr>\n";
2777 * @since 1.20
2779 public function getDiv( $value ) {
2780 $msg = $this->formatMsg();
2781 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2785 * @since 1.20
2787 public function getRaw( $value ) {
2788 return $this->getDiv( $value );
2791 protected function formatMsg() {
2792 if ( empty( $this->mParams['message'] ) ) {
2793 $msg = $this->msg( 'edittools' );
2794 } else {
2795 $msg = $this->msg( $this->mParams['message'] );
2796 if ( $msg->isDisabled() ) {
2797 $msg = $this->msg( 'edittools' );
2800 $msg->inContentLanguage();
2801 return $msg;
2805 class HTMLApiField extends HTMLFormField {
2806 public function getTableRow( $value ) {
2807 return '';
2810 public function getDiv( $value ) {
2811 return $this->getTableRow( $value );
2814 public function getRaw( $value ) {
2815 return $this->getTableRow( $value );
2818 public function getInputHTML( $value ) {
2819 return '';
2823 interface HTMLNestedFilterable {
2825 * Support for seperating multi-option preferences into multiple preferences
2826 * Due to lack of array support.
2827 * @param $data array
2829 function filterDataForSubmit( $data );
2832 class HTMLFormFieldRequiredOptionsException extends MWException {
2833 public function __construct( HTMLFormField $field, array $missing ) {
2834 parent::__construct( sprintf(
2835 "Form type `%s` expected the following parameters to be set: %s",
2836 get_class( $field ),
2837 implode( ', ', $missing )
2838 ) );