Merge "Add ss_active_users in SiteStats::isSane"
[mediawiki.git] / includes / HTMLForm.php
blob7adbfc89479629252f360042a1ee6b046969846c
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;
144 protected $mSubmitID;
145 protected $mSubmitName;
146 protected $mSubmitText;
147 protected $mSubmitTooltip;
149 protected $mTitle;
150 protected $mMethod = 'post';
153 * Form action URL. false means we will use the URL to set Title
154 * @since 1.19
155 * @var bool|string
157 protected $mAction = false;
159 protected $mUseMultipart = false;
160 protected $mHiddenFields = array();
161 protected $mButtons = array();
163 protected $mWrapperLegend = false;
166 * If true, sections that contain both fields and subsections will
167 * render their subsections before their fields.
169 * Subclasses may set this to false to render subsections after fields
170 * instead.
172 protected $mSubSectionBeforeFields = true;
175 * Format in which to display form. For viable options,
176 * @see $availableDisplayFormats
177 * @var String
179 protected $displayFormat = 'table';
182 * Available formats in which to display the form
183 * @var Array
185 protected $availableDisplayFormats = array(
186 'table',
187 'div',
188 'raw',
192 * Build a new HTMLForm from an array of field attributes
193 * @param array $descriptor of Field constructs, as described above
194 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
195 * Obviates the need to call $form->setTitle()
196 * @param string $messagePrefix a prefix to go in front of default messages
198 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
199 if ( $context instanceof IContextSource ) {
200 $this->setContext( $context );
201 $this->mTitle = false; // We don't need them to set a title
202 $this->mMessagePrefix = $messagePrefix;
203 } else {
204 // B/C since 1.18
205 if ( is_string( $context ) && $messagePrefix === '' ) {
206 // it's actually $messagePrefix
207 $this->mMessagePrefix = $context;
211 // Expand out into a tree.
212 $loadedDescriptor = array();
213 $this->mFlatFields = array();
215 foreach ( $descriptor as $fieldname => $info ) {
216 $section = isset( $info['section'] )
217 ? $info['section']
218 : '';
220 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
221 $this->mUseMultipart = true;
224 $field = self::loadInputFromParameters( $fieldname, $info );
225 $field->mParent = $this;
227 $setSection =& $loadedDescriptor;
228 if ( $section ) {
229 $sectionParts = explode( '/', $section );
231 while ( count( $sectionParts ) ) {
232 $newName = array_shift( $sectionParts );
234 if ( !isset( $setSection[$newName] ) ) {
235 $setSection[$newName] = array();
238 $setSection =& $setSection[$newName];
242 $setSection[$fieldname] = $field;
243 $this->mFlatFields[$fieldname] = $field;
246 $this->mFieldTree = $loadedDescriptor;
250 * Set format in which to display the form
251 * @param string $format the name of the format to use, must be one of
252 * $this->availableDisplayFormats
253 * @throws MWException
254 * @since 1.20
255 * @return HTMLForm $this for chaining calls (since 1.20)
257 public function setDisplayFormat( $format ) {
258 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
259 throw new MWException( 'Display format must be one of ' . print_r( $this->availableDisplayFormats, true ) );
261 $this->displayFormat = $format;
262 return $this;
266 * Getter for displayFormat
267 * @since 1.20
268 * @return String
270 public function getDisplayFormat() {
271 return $this->displayFormat;
275 * Add the HTMLForm-specific JavaScript, if it hasn't been
276 * done already.
277 * @deprecated since 1.18 load modules with ResourceLoader instead
279 static function addJS() {
280 wfDeprecated( __METHOD__, '1.18' );
284 * Initialise a new Object for the field
285 * @param $fieldname string
286 * @param string $descriptor input Descriptor, as described above
287 * @throws MWException
288 * @return HTMLFormField subclass
290 static function loadInputFromParameters( $fieldname, $descriptor ) {
291 if ( isset( $descriptor['class'] ) ) {
292 $class = $descriptor['class'];
293 } elseif ( isset( $descriptor['type'] ) ) {
294 $class = self::$typeMappings[$descriptor['type']];
295 $descriptor['class'] = $class;
296 } else {
297 $class = null;
300 if ( !$class ) {
301 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
304 $descriptor['fieldname'] = $fieldname;
306 # TODO
307 # This will throw a fatal error whenever someone try to use
308 # 'class' to feed a CSS class instead of 'cssclass'. Would be
309 # great to avoid the fatal error and show a nice error.
310 $obj = new $class( $descriptor );
312 return $obj;
316 * Prepare form for submission.
318 * @attention When doing method chaining, that should be the very last
319 * method call before displayForm().
321 * @throws MWException
322 * @return HTMLForm $this for chaining calls (since 1.20)
324 function prepareForm() {
325 # Check if we have the info we need
326 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
327 throw new MWException( "You must call setTitle() on an HTMLForm" );
330 # Load data from the request.
331 $this->loadData();
332 return $this;
336 * Try submitting, with edit token check first
337 * @return Status|boolean
339 function tryAuthorizedSubmit() {
340 $result = false;
342 $submit = false;
343 if ( $this->getMethod() != 'post' ) {
344 $submit = true; // no session check needed
345 } elseif ( $this->getRequest()->wasPosted() ) {
346 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
347 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
348 // Session tokens for logged-out users have no security value.
349 // However, if the user gave one, check it in order to give a nice
350 // "session expired" error instead of "permission denied" or such.
351 $submit = $this->getUser()->matchEditToken( $editToken );
352 } else {
353 $submit = true;
357 if ( $submit ) {
358 $result = $this->trySubmit();
361 return $result;
365 * The here's-one-I-made-earlier option: do the submission if
366 * posted, or display the form with or without funky validation
367 * errors
368 * @return Bool or Status whether submission was successful.
370 function show() {
371 $this->prepareForm();
373 $result = $this->tryAuthorizedSubmit();
374 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
375 return $result;
378 $this->displayForm( $result );
379 return false;
383 * Validate all the fields, and call the submission callback
384 * function if everything is kosher.
385 * @throws MWException
386 * @return Mixed Bool true == Successful submission, Bool false
387 * == No submission attempted, anything else == Error to
388 * display.
390 function trySubmit() {
391 # Check for validation
392 foreach ( $this->mFlatFields as $fieldname => $field ) {
393 if ( !empty( $field->mParams['nodata'] ) ) {
394 continue;
396 if ( $field->validate(
397 $this->mFieldData[$fieldname],
398 $this->mFieldData )
399 !== true
401 return isset( $this->mValidationErrorMessage )
402 ? $this->mValidationErrorMessage
403 : array( 'htmlform-invalid-input' );
407 $callback = $this->mSubmitCallback;
408 if ( !is_callable( $callback ) ) {
409 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
412 $data = $this->filterDataForSubmit( $this->mFieldData );
414 $res = call_user_func( $callback, $data, $this );
416 return $res;
420 * Set a callback to a function to do something with the form
421 * once it's been successfully validated.
422 * @param string $cb function name. The function will be passed
423 * the output from HTMLForm::filterDataForSubmit, and must
424 * return Bool true on success, Bool false if no submission
425 * was attempted, or String HTML output to display on error.
426 * @return HTMLForm $this for chaining calls (since 1.20)
428 function setSubmitCallback( $cb ) {
429 $this->mSubmitCallback = $cb;
430 return $this;
434 * Set a message to display on a validation error.
435 * @param $msg Mixed String or Array of valid inputs to wfMessage()
436 * (so each entry can be either a String or Array)
437 * @return HTMLForm $this for chaining calls (since 1.20)
439 function setValidationErrorMessage( $msg ) {
440 $this->mValidationErrorMessage = $msg;
441 return $this;
445 * Set the introductory message, overwriting any existing message.
446 * @param string $msg complete text of message to display
447 * @return HTMLForm $this for chaining calls (since 1.20)
449 function setIntro( $msg ) {
450 $this->setPreText( $msg );
451 return $this;
455 * Set the introductory message, overwriting any existing message.
456 * @since 1.19
457 * @param string $msg complete text of message to display
458 * @return HTMLForm $this for chaining calls (since 1.20)
460 function setPreText( $msg ) {
461 $this->mPre = $msg;
462 return $this;
466 * Add introductory text.
467 * @param string $msg complete text of message to display
468 * @return HTMLForm $this for chaining calls (since 1.20)
470 function addPreText( $msg ) {
471 $this->mPre .= $msg;
472 return $this;
476 * Add header text, inside the form.
477 * @param string $msg complete text of message to display
478 * @param string $section The section to add the header to
479 * @return HTMLForm $this for chaining calls (since 1.20)
481 function addHeaderText( $msg, $section = null ) {
482 if ( is_null( $section ) ) {
483 $this->mHeader .= $msg;
484 } else {
485 if ( !isset( $this->mSectionHeaders[$section] ) ) {
486 $this->mSectionHeaders[$section] = '';
488 $this->mSectionHeaders[$section] .= $msg;
490 return $this;
494 * Set header text, inside the form.
495 * @since 1.19
496 * @param string $msg complete text of message to display
497 * @param $section The section to add the header to
498 * @return HTMLForm $this for chaining calls (since 1.20)
500 function setHeaderText( $msg, $section = null ) {
501 if ( is_null( $section ) ) {
502 $this->mHeader = $msg;
503 } else {
504 $this->mSectionHeaders[$section] = $msg;
506 return $this;
510 * Add footer text, inside the form.
511 * @param string $msg complete text of message to display
512 * @param string $section The section to add the footer text to
513 * @return HTMLForm $this for chaining calls (since 1.20)
515 function addFooterText( $msg, $section = null ) {
516 if ( is_null( $section ) ) {
517 $this->mFooter .= $msg;
518 } else {
519 if ( !isset( $this->mSectionFooters[$section] ) ) {
520 $this->mSectionFooters[$section] = '';
522 $this->mSectionFooters[$section] .= $msg;
524 return $this;
528 * Set footer text, inside the form.
529 * @since 1.19
530 * @param string $msg complete text of message to display
531 * @param string $section The section to add the footer text to
532 * @return HTMLForm $this for chaining calls (since 1.20)
534 function setFooterText( $msg, $section = null ) {
535 if ( is_null( $section ) ) {
536 $this->mFooter = $msg;
537 } else {
538 $this->mSectionFooters[$section] = $msg;
540 return $this;
544 * Add text to the end of the display.
545 * @param string $msg complete text of message to display
546 * @return HTMLForm $this for chaining calls (since 1.20)
548 function addPostText( $msg ) {
549 $this->mPost .= $msg;
550 return $this;
554 * Set text at the end of the display.
555 * @param string $msg complete text of message to display
556 * @return HTMLForm $this for chaining calls (since 1.20)
558 function setPostText( $msg ) {
559 $this->mPost = $msg;
560 return $this;
564 * Add a hidden field to the output
565 * @param string $name field name. This will be used exactly as entered
566 * @param string $value field value
567 * @param $attribs Array
568 * @return HTMLForm $this for chaining calls (since 1.20)
570 public function addHiddenField( $name, $value, $attribs = array() ) {
571 $attribs += array( 'name' => $name );
572 $this->mHiddenFields[] = array( $value, $attribs );
573 return $this;
577 * Add a button to the form
578 * @param string $name field name.
579 * @param string $value field value
580 * @param string $id DOM id for the button (default: null)
581 * @param $attribs Array
582 * @return HTMLForm $this for chaining calls (since 1.20)
584 public function addButton( $name, $value, $id = null, $attribs = null ) {
585 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
586 return $this;
590 * Display the form (sending to $wgOut), with an appropriate error
591 * message or stack of messages, and any validation errors, etc.
593 * @attention You should call prepareForm() before calling this function.
594 * Moreover, when doing method chaining this should be the very last method
595 * call just after prepareForm().
597 * @param $submitResult Mixed output from HTMLForm::trySubmit()
598 * @return Nothing, should be last call
600 function displayForm( $submitResult ) {
601 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
605 * Returns the raw HTML generated by the form
606 * @param $submitResult Mixed output from HTMLForm::trySubmit()
607 * @return string
609 function getHTML( $submitResult ) {
610 # For good measure (it is the default)
611 $this->getOutput()->preventClickjacking();
612 $this->getOutput()->addModules( 'mediawiki.htmlform' );
614 $html = ''
615 . $this->getErrors( $submitResult )
616 . $this->mHeader
617 . $this->getBody()
618 . $this->getHiddenFields()
619 . $this->getButtons()
620 . $this->mFooter
623 $html = $this->wrapForm( $html );
625 return '' . $this->mPre . $html . $this->mPost;
629 * Wrap the form innards in an actual "<form>" element
630 * @param string $html HTML contents to wrap.
631 * @return String wrapped HTML.
633 function wrapForm( $html ) {
635 # Include a <fieldset> wrapper for style, if requested.
636 if ( $this->mWrapperLegend !== false ) {
637 $html = Xml::fieldset( $this->mWrapperLegend, $html );
639 # Use multipart/form-data
640 $encType = $this->mUseMultipart
641 ? 'multipart/form-data'
642 : 'application/x-www-form-urlencoded';
643 # Attributes
644 $attribs = array(
645 'action' => $this->mAction === false ? $this->getTitle()->getFullURL() : $this->mAction,
646 'method' => $this->mMethod,
647 'class' => 'visualClear',
648 'enctype' => $encType,
650 if ( !empty( $this->mId ) ) {
651 $attribs['id'] = $this->mId;
654 return Html::rawElement( 'form', $attribs, $html );
658 * Get the hidden fields that should go inside the form.
659 * @return String HTML.
661 function getHiddenFields() {
662 global $wgArticlePath;
664 $html = '';
665 if ( $this->getMethod() == 'post' ) {
666 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
667 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
670 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
671 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
674 foreach ( $this->mHiddenFields as $data ) {
675 list( $value, $attribs ) = $data;
676 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
679 return $html;
683 * Get the submit and (potentially) reset buttons.
684 * @return String HTML.
686 function getButtons() {
687 $html = '';
689 if ( $this->mShowSubmit ) {
690 $attribs = array();
692 if ( isset( $this->mSubmitID ) ) {
693 $attribs['id'] = $this->mSubmitID;
696 if ( isset( $this->mSubmitName ) ) {
697 $attribs['name'] = $this->mSubmitName;
700 if ( isset( $this->mSubmitTooltip ) ) {
701 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
704 $attribs['class'] = 'mw-htmlform-submit';
706 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
709 if ( $this->mShowReset ) {
710 $html .= Html::element(
711 'input',
712 array(
713 'type' => 'reset',
714 'value' => $this->msg( 'htmlform-reset' )->text()
716 ) . "\n";
719 foreach ( $this->mButtons as $button ) {
720 $attrs = array(
721 'type' => 'submit',
722 'name' => $button['name'],
723 'value' => $button['value']
726 if ( $button['attribs'] ) {
727 $attrs += $button['attribs'];
730 if ( isset( $button['id'] ) ) {
731 $attrs['id'] = $button['id'];
734 $html .= Html::element( 'input', $attrs );
737 return $html;
741 * Get the whole body of the form.
742 * @return String
744 function getBody() {
745 return $this->displaySection( $this->mFieldTree );
749 * Format and display an error message stack.
750 * @param $errors String|Array|Status
751 * @return String
753 function getErrors( $errors ) {
754 if ( $errors instanceof Status ) {
755 if ( $errors->isOK() ) {
756 $errorstr = '';
757 } else {
758 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
760 } elseif ( is_array( $errors ) ) {
761 $errorstr = $this->formatErrors( $errors );
762 } else {
763 $errorstr = $errors;
766 return $errorstr
767 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
768 : '';
772 * Format a stack of error messages into a single HTML string
773 * @param array $errors of message keys/values
774 * @return String HTML, a "<ul>" list of errors
776 public static function formatErrors( $errors ) {
777 $errorstr = '';
779 foreach ( $errors as $error ) {
780 if ( is_array( $error ) ) {
781 $msg = array_shift( $error );
782 } else {
783 $msg = $error;
784 $error = array();
787 $errorstr .= Html::rawElement(
788 'li',
789 array(),
790 wfMessage( $msg, $error )->parse()
794 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
796 return $errorstr;
800 * Set the text for the submit button
801 * @param string $t plaintext.
802 * @return HTMLForm $this for chaining calls (since 1.20)
804 function setSubmitText( $t ) {
805 $this->mSubmitText = $t;
806 return $this;
810 * Set the text for the submit button to a message
811 * @since 1.19
812 * @param string $msg message key
813 * @return HTMLForm $this for chaining calls (since 1.20)
815 public function setSubmitTextMsg( $msg ) {
816 $this->setSubmitText( $this->msg( $msg )->text() );
817 return $this;
821 * Get the text for the submit button, either customised or a default.
822 * @return string
824 function getSubmitText() {
825 return $this->mSubmitText
826 ? $this->mSubmitText
827 : $this->msg( 'htmlform-submit' )->text();
831 * @param string $name Submit button name
832 * @return HTMLForm $this for chaining calls (since 1.20)
834 public function setSubmitName( $name ) {
835 $this->mSubmitName = $name;
836 return $this;
840 * @param string $name Tooltip for the submit button
841 * @return HTMLForm $this for chaining calls (since 1.20)
843 public function setSubmitTooltip( $name ) {
844 $this->mSubmitTooltip = $name;
845 return $this;
849 * Set the id for the submit button.
850 * @param $t String.
851 * @todo FIXME: Integrity of $t is *not* validated
852 * @return HTMLForm $this for chaining calls (since 1.20)
854 function setSubmitID( $t ) {
855 $this->mSubmitID = $t;
856 return $this;
860 * Stop a default submit button being shown for this form. This implies that an
861 * alternate submit method must be provided manually.
863 * @since 1.22
865 * @param bool $suppressSubmit Set to false to re-enable the button again
867 * @return HTMLForm $this for chaining calls
869 function suppressDefaultSubmit( $suppressSubmit = true ) {
870 $this->mShowSubmit = !$suppressSubmit;
871 return $this;
875 * @param string $id DOM id for the form
876 * @return HTMLForm $this for chaining calls (since 1.20)
878 public function setId( $id ) {
879 $this->mId = $id;
880 return $this;
883 * Prompt the whole form to be wrapped in a "<fieldset>", with
884 * this text as its "<legend>" element.
885 * @param string $legend HTML to go inside the "<legend>" element.
886 * Will be escaped
887 * @return HTMLForm $this for chaining calls (since 1.20)
889 public function setWrapperLegend( $legend ) {
890 $this->mWrapperLegend = $legend;
891 return $this;
895 * Prompt the whole form to be wrapped in a "<fieldset>", with
896 * this message as its "<legend>" element.
897 * @since 1.19
898 * @param string $msg message key
899 * @return HTMLForm $this for chaining calls (since 1.20)
901 public function setWrapperLegendMsg( $msg ) {
902 $this->setWrapperLegend( $this->msg( $msg )->text() );
903 return $this;
907 * Set the prefix for various default messages
908 * @todo currently only used for the "<fieldset>" legend on forms
909 * with multiple sections; should be used elsewhere?
910 * @param $p String
911 * @return HTMLForm $this for chaining calls (since 1.20)
913 function setMessagePrefix( $p ) {
914 $this->mMessagePrefix = $p;
915 return $this;
919 * Set the title for form submission
920 * @param $t Title of page the form is on/should be posted to
921 * @return HTMLForm $this for chaining calls (since 1.20)
923 function setTitle( $t ) {
924 $this->mTitle = $t;
925 return $this;
929 * Get the title
930 * @return Title
932 function getTitle() {
933 return $this->mTitle === false
934 ? $this->getContext()->getTitle()
935 : $this->mTitle;
939 * Set the method used to submit the form
940 * @param $method String
941 * @return HTMLForm $this for chaining calls (since 1.20)
943 public function setMethod( $method = 'post' ) {
944 $this->mMethod = $method;
945 return $this;
948 public function getMethod() {
949 return $this->mMethod;
953 * @todo Document
954 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
955 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
956 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
957 * @return String
959 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
960 $displayFormat = $this->getDisplayFormat();
962 $html = '';
963 $subsectionHtml = '';
964 $hasLabel = false;
966 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ? 'getTableRow' : 'get' . ucfirst( $displayFormat );
968 foreach ( $fields as $key => $value ) {
969 if ( $value instanceof HTMLFormField ) {
970 $v = empty( $value->mParams['nodata'] )
971 ? $this->mFieldData[$key]
972 : $value->getDefault();
973 $html .= $value->$getFieldHtmlMethod( $v );
975 $labelValue = trim( $value->getLabel() );
976 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
977 $hasLabel = true;
979 } elseif ( is_array( $value ) ) {
980 $section = $this->displaySection( $value, $key, "$fieldsetIDPrefix$key-" );
981 $legend = $this->getLegend( $key );
982 if ( isset( $this->mSectionHeaders[$key] ) ) {
983 $section = $this->mSectionHeaders[$key] . $section;
985 if ( isset( $this->mSectionFooters[$key] ) ) {
986 $section .= $this->mSectionFooters[$key];
988 $attributes = array();
989 if ( $fieldsetIDPrefix ) {
990 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
992 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
996 if ( $displayFormat !== 'raw' ) {
997 $classes = array();
999 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1000 $classes[] = 'mw-htmlform-nolabel';
1003 $attribs = array(
1004 'class' => implode( ' ', $classes ),
1007 if ( $sectionName ) {
1008 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
1011 if ( $displayFormat === 'table' ) {
1012 $html = Html::rawElement( 'table', $attribs,
1013 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1014 } elseif ( $displayFormat === 'div' ) {
1015 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1019 if ( $this->mSubSectionBeforeFields ) {
1020 return $subsectionHtml . "\n" . $html;
1021 } else {
1022 return $html . "\n" . $subsectionHtml;
1027 * Construct the form fields from the Descriptor array
1029 function loadData() {
1030 $fieldData = array();
1032 foreach ( $this->mFlatFields as $fieldname => $field ) {
1033 if ( !empty( $field->mParams['nodata'] ) ) {
1034 continue;
1035 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1036 $fieldData[$fieldname] = $field->getDefault();
1037 } else {
1038 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1042 # Filter data.
1043 foreach ( $fieldData as $name => &$value ) {
1044 $field = $this->mFlatFields[$name];
1045 $value = $field->filter( $value, $this->mFlatFields );
1048 $this->mFieldData = $fieldData;
1052 * Stop a reset button being shown for this form
1053 * @param bool $suppressReset set to false to re-enable the
1054 * button again
1055 * @return HTMLForm $this for chaining calls (since 1.20)
1057 function suppressReset( $suppressReset = true ) {
1058 $this->mShowReset = !$suppressReset;
1059 return $this;
1063 * Overload this if you want to apply special filtration routines
1064 * to the form as a whole, after it's submitted but before it's
1065 * processed.
1066 * @param $data
1067 * @return
1069 function filterDataForSubmit( $data ) {
1070 return $data;
1074 * Get a string to go in the "<legend>" of a section fieldset.
1075 * Override this if you want something more complicated.
1076 * @param $key String
1077 * @return String
1079 public function getLegend( $key ) {
1080 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1084 * Set the value for the action attribute of the form.
1085 * When set to false (which is the default state), the set title is used.
1087 * @since 1.19
1089 * @param string|bool $action
1090 * @return HTMLForm $this for chaining calls (since 1.20)
1092 public function setAction( $action ) {
1093 $this->mAction = $action;
1094 return $this;
1099 * The parent class to generate form fields. Any field type should
1100 * be a subclass of this.
1102 abstract class HTMLFormField {
1104 protected $mValidationCallback;
1105 protected $mFilterCallback;
1106 protected $mName;
1107 public $mParams;
1108 protected $mLabel; # String label. Set on construction
1109 protected $mID;
1110 protected $mClass = '';
1111 protected $mDefault;
1114 * @var bool If true will generate an empty div element with no label
1115 * @since 1.22
1117 protected $mShowEmptyLabels = true;
1120 * @var HTMLForm
1122 public $mParent;
1125 * This function must be implemented to return the HTML to generate
1126 * the input object itself. It should not implement the surrounding
1127 * table cells/rows, or labels/help messages.
1128 * @param string $value the value to set the input to; eg a default
1129 * text for a text input.
1130 * @return String valid HTML.
1132 abstract function getInputHTML( $value );
1135 * Get a translated interface message
1137 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1138 * and wfMessage() otherwise.
1140 * Parameters are the same as wfMessage().
1142 * @return Message object
1144 function msg() {
1145 $args = func_get_args();
1147 if ( $this->mParent ) {
1148 $callback = array( $this->mParent, 'msg' );
1149 } else {
1150 $callback = 'wfMessage';
1153 return call_user_func_array( $callback, $args );
1157 * Override this function to add specific validation checks on the
1158 * field input. Don't forget to call parent::validate() to ensure
1159 * that the user-defined callback mValidationCallback is still run
1160 * @param string $value the value the field was submitted with
1161 * @param array $alldata the data collected from the form
1162 * @return Mixed Bool true on success, or String error to display.
1164 function validate( $value, $alldata ) {
1165 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1166 return $this->msg( 'htmlform-required' )->parse();
1169 if ( isset( $this->mValidationCallback ) ) {
1170 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1173 return true;
1176 function filter( $value, $alldata ) {
1177 if ( isset( $this->mFilterCallback ) ) {
1178 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1181 return $value;
1185 * Should this field have a label, or is there no input element with the
1186 * appropriate id for the label to point to?
1188 * @return bool True to output a label, false to suppress
1190 protected function needsLabel() {
1191 return true;
1195 * Get the value that this input has been set to from a posted form,
1196 * or the input's default value if it has not been set.
1197 * @param $request WebRequest
1198 * @return String the value
1200 function loadDataFromRequest( $request ) {
1201 if ( $request->getCheck( $this->mName ) ) {
1202 return $request->getText( $this->mName );
1203 } else {
1204 return $this->getDefault();
1209 * Initialise the object
1210 * @param array $params Associative Array. See HTMLForm doc for syntax.
1212 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
1213 * @throws MWException
1215 function __construct( $params ) {
1216 $this->mParams = $params;
1218 # Generate the label from a message, if possible
1219 if ( isset( $params['label-message'] ) ) {
1220 $msgInfo = $params['label-message'];
1222 if ( is_array( $msgInfo ) ) {
1223 $msg = array_shift( $msgInfo );
1224 } else {
1225 $msg = $msgInfo;
1226 $msgInfo = array();
1229 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1230 } elseif ( isset( $params['label'] ) ) {
1231 if ( $params['label'] === '&#160;' ) {
1232 // Apparently some things set &nbsp directly and in an odd format
1233 $this->mLabel = '&#160;';
1234 } else {
1235 $this->mLabel = htmlspecialchars( $params['label'] );
1237 } elseif ( isset( $params['label-raw'] ) ) {
1238 $this->mLabel = $params['label-raw'];
1241 $this->mName = "wp{$params['fieldname']}";
1242 if ( isset( $params['name'] ) ) {
1243 $this->mName = $params['name'];
1246 $validName = Sanitizer::escapeId( $this->mName );
1247 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1248 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1251 $this->mID = "mw-input-{$this->mName}";
1253 if ( isset( $params['default'] ) ) {
1254 $this->mDefault = $params['default'];
1257 if ( isset( $params['id'] ) ) {
1258 $id = $params['id'];
1259 $validId = Sanitizer::escapeId( $id );
1261 if ( $id != $validId ) {
1262 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1265 $this->mID = $id;
1268 if ( isset( $params['cssclass'] ) ) {
1269 $this->mClass = $params['cssclass'];
1272 if ( isset( $params['validation-callback'] ) ) {
1273 $this->mValidationCallback = $params['validation-callback'];
1276 if ( isset( $params['filter-callback'] ) ) {
1277 $this->mFilterCallback = $params['filter-callback'];
1280 if ( isset( $params['flatlist'] ) ) {
1281 $this->mClass .= ' mw-htmlform-flatlist';
1284 if ( isset( $params['hidelabel'] ) ) {
1285 $this->mShowEmptyLabels = false;
1290 * Get the complete table row for the input, including help text,
1291 * labels, and whatever.
1292 * @param string $value the value to set the input to.
1293 * @return String complete HTML table row.
1295 function getTableRow( $value ) {
1296 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1297 $inputHtml = $this->getInputHTML( $value );
1298 $fieldType = get_class( $this );
1299 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1300 $cellAttributes = array();
1302 if ( !empty( $this->mParams['vertical-label'] ) ) {
1303 $cellAttributes['colspan'] = 2;
1304 $verticalLabel = true;
1305 } else {
1306 $verticalLabel = false;
1309 $label = $this->getLabelHtml( $cellAttributes );
1311 $field = Html::rawElement(
1312 'td',
1313 array( 'class' => 'mw-input' ) + $cellAttributes,
1314 $inputHtml . "\n$errors"
1317 if ( $verticalLabel ) {
1318 $html = Html::rawElement( 'tr',
1319 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1320 $html .= Html::rawElement( 'tr',
1321 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1322 $field );
1323 } else {
1324 $html = Html::rawElement( 'tr',
1325 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1326 $label . $field );
1329 return $html . $helptext;
1333 * Get the complete div for the input, including help text,
1334 * labels, and whatever.
1335 * @since 1.20
1336 * @param string $value the value to set the input to.
1337 * @return String complete HTML table row.
1339 public function getDiv( $value ) {
1340 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1341 $inputHtml = $this->getInputHTML( $value );
1342 $fieldType = get_class( $this );
1343 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1344 $cellAttributes = array();
1345 $label = $this->getLabelHtml( $cellAttributes );
1347 $outerDivClass = array(
1348 'mw-input',
1349 'mw-htmlform-nolabel' => ( $label === '' )
1352 $field = Html::rawElement(
1353 'div',
1354 array( 'class' => $outerDivClass ) + $cellAttributes,
1355 $inputHtml . "\n$errors"
1357 $html = Html::rawElement( 'div',
1358 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1359 $label . $field );
1360 $html .= $helptext;
1361 return $html;
1365 * Get the complete raw fields for the input, including help text,
1366 * labels, and whatever.
1367 * @since 1.20
1368 * @param string $value the value to set the input to.
1369 * @return String complete HTML table row.
1371 public function getRaw( $value ) {
1372 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1373 $inputHtml = $this->getInputHTML( $value );
1374 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1375 $cellAttributes = array();
1376 $label = $this->getLabelHtml( $cellAttributes );
1378 $html = "\n$errors";
1379 $html .= $label;
1380 $html .= $inputHtml;
1381 $html .= $helptext;
1382 return $html;
1386 * Generate help text HTML in table format
1387 * @since 1.20
1388 * @param $helptext String|null
1389 * @return String
1391 public function getHelpTextHtmlTable( $helptext ) {
1392 if ( is_null( $helptext ) ) {
1393 return '';
1396 $row = Html::rawElement(
1397 'td',
1398 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1399 $helptext
1401 $row = Html::rawElement( 'tr', array(), $row );
1402 return $row;
1406 * Generate help text HTML in div format
1407 * @since 1.20
1408 * @param $helptext String|null
1409 * @return String
1411 public function getHelpTextHtmlDiv( $helptext ) {
1412 if ( is_null( $helptext ) ) {
1413 return '';
1416 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1417 return $div;
1421 * Generate help text HTML formatted for raw output
1422 * @since 1.20
1423 * @param $helptext String|null
1424 * @return String
1426 public function getHelpTextHtmlRaw( $helptext ) {
1427 return $this->getHelpTextHtmlDiv( $helptext );
1431 * Determine the help text to display
1432 * @since 1.20
1433 * @return String
1435 public function getHelpText() {
1436 $helptext = null;
1438 if ( isset( $this->mParams['help-message'] ) ) {
1439 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1442 if ( isset( $this->mParams['help-messages'] ) ) {
1443 foreach ( $this->mParams['help-messages'] as $name ) {
1444 $helpMessage = (array)$name;
1445 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1447 if ( $msg->exists() ) {
1448 if ( is_null( $helptext ) ) {
1449 $helptext = '';
1450 } else {
1451 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1453 $helptext .= $msg->parse(); // Append message
1457 elseif ( isset( $this->mParams['help'] ) ) {
1458 $helptext = $this->mParams['help'];
1460 return $helptext;
1464 * Determine form errors to display and their classes
1465 * @since 1.20
1466 * @param string $value the value of the input
1467 * @return Array
1469 public function getErrorsAndErrorClass( $value ) {
1470 $errors = $this->validate( $value, $this->mParent->mFieldData );
1472 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1473 $errors = '';
1474 $errorClass = '';
1475 } else {
1476 $errors = self::formatErrors( $errors );
1477 $errorClass = 'mw-htmlform-invalid-input';
1479 return array( $errors, $errorClass );
1482 function getLabel() {
1483 return is_null( $this->mLabel ) ? '' : $this->mLabel;
1486 function getLabelHtml( $cellAttributes = array() ) {
1487 # Don't output a for= attribute for labels with no associated input.
1488 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1489 $for = array();
1491 if ( $this->needsLabel() ) {
1492 $for['for'] = $this->mID;
1495 $labelValue = trim( $this->getLabel() );
1496 $hasLabel = false;
1497 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
1498 $hasLabel = true;
1501 $displayFormat = $this->mParent->getDisplayFormat();
1502 $html = '';
1504 if ( $displayFormat === 'table' ) {
1505 $html = Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1506 Html::rawElement( 'label', $for, $labelValue )
1508 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
1509 if ( $displayFormat === 'div' ) {
1510 $html = Html::rawElement(
1511 'div',
1512 array( 'class' => 'mw-label' ) + $cellAttributes,
1513 Html::rawElement( 'label', $for, $labelValue )
1515 } else {
1516 $html = Html::rawElement( 'label', $for, $labelValue );
1520 return $html;
1523 function getDefault() {
1524 if ( isset( $this->mDefault ) ) {
1525 return $this->mDefault;
1526 } else {
1527 return null;
1532 * Returns the attributes required for the tooltip and accesskey.
1534 * @return array Attributes
1536 public function getTooltipAndAccessKey() {
1537 if ( empty( $this->mParams['tooltip'] ) ) {
1538 return array();
1540 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1544 * flatten an array of options to a single array, for instance,
1545 * a set of "<options>" inside "<optgroups>".
1546 * @param array $options Associative Array with values either Strings
1547 * or Arrays
1548 * @return Array flattened input
1550 public static function flattenOptions( $options ) {
1551 $flatOpts = array();
1553 foreach ( $options as $value ) {
1554 if ( is_array( $value ) ) {
1555 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1556 } else {
1557 $flatOpts[] = $value;
1561 return $flatOpts;
1565 * Formats one or more errors as accepted by field validation-callback.
1566 * @param $errors String|Message|Array of strings or Message instances
1567 * @return String html
1568 * @since 1.18
1570 protected static function formatErrors( $errors ) {
1571 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1572 $errors = array_shift( $errors );
1575 if ( is_array( $errors ) ) {
1576 $lines = array();
1577 foreach ( $errors as $error ) {
1578 if ( $error instanceof Message ) {
1579 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1580 } else {
1581 $lines[] = Html::rawElement( 'li', array(), $error );
1584 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1585 } else {
1586 if ( $errors instanceof Message ) {
1587 $errors = $errors->parse();
1589 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1594 class HTMLTextField extends HTMLFormField {
1595 function getSize() {
1596 return isset( $this->mParams['size'] )
1597 ? $this->mParams['size']
1598 : 45;
1601 function getInputHTML( $value ) {
1602 $attribs = array(
1603 'id' => $this->mID,
1604 'name' => $this->mName,
1605 'size' => $this->getSize(),
1606 'value' => $value,
1607 ) + $this->getTooltipAndAccessKey();
1609 if ( $this->mClass !== '' ) {
1610 $attribs['class'] = $this->mClass;
1613 if ( !empty( $this->mParams['disabled'] ) ) {
1614 $attribs['disabled'] = 'disabled';
1617 # TODO: Enforce pattern, step, required, readonly on the server side as
1618 # well
1619 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1620 'placeholder', 'list', 'maxlength' );
1621 foreach ( $allowedParams as $param ) {
1622 if ( isset( $this->mParams[$param] ) ) {
1623 $attribs[$param] = $this->mParams[$param];
1627 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1628 if ( isset( $this->mParams[$param] ) ) {
1629 $attribs[$param] = '';
1633 # Implement tiny differences between some field variants
1634 # here, rather than creating a new class for each one which
1635 # is essentially just a clone of this one.
1636 if ( isset( $this->mParams['type'] ) ) {
1637 switch ( $this->mParams['type'] ) {
1638 case 'email':
1639 $attribs['type'] = 'email';
1640 break;
1641 case 'int':
1642 $attribs['type'] = 'number';
1643 break;
1644 case 'float':
1645 $attribs['type'] = 'number';
1646 $attribs['step'] = 'any';
1647 break;
1648 # Pass through
1649 case 'password':
1650 case 'file':
1651 $attribs['type'] = $this->mParams['type'];
1652 break;
1656 return Html::element( 'input', $attribs );
1659 class HTMLTextAreaField extends HTMLFormField {
1660 const DEFAULT_COLS = 80;
1661 const DEFAULT_ROWS = 25;
1663 function getCols() {
1664 return isset( $this->mParams['cols'] )
1665 ? $this->mParams['cols']
1666 : static::DEFAULT_COLS;
1669 function getRows() {
1670 return isset( $this->mParams['rows'] )
1671 ? $this->mParams['rows']
1672 : static::DEFAULT_ROWS;
1675 function getInputHTML( $value ) {
1676 $attribs = array(
1677 'id' => $this->mID,
1678 'name' => $this->mName,
1679 'cols' => $this->getCols(),
1680 'rows' => $this->getRows(),
1681 ) + $this->getTooltipAndAccessKey();
1683 if ( $this->mClass !== '' ) {
1684 $attribs['class'] = $this->mClass;
1687 if ( !empty( $this->mParams['disabled'] ) ) {
1688 $attribs['disabled'] = 'disabled';
1691 if ( !empty( $this->mParams['readonly'] ) ) {
1692 $attribs['readonly'] = 'readonly';
1695 if ( isset( $this->mParams['placeholder'] ) ) {
1696 $attribs['placeholder'] = $this->mParams['placeholder'];
1699 foreach ( array( 'required', 'autofocus' ) as $param ) {
1700 if ( isset( $this->mParams[$param] ) ) {
1701 $attribs[$param] = '';
1705 return Html::element( 'textarea', $attribs, $value );
1710 * A field that will contain a numeric value
1712 class HTMLFloatField extends HTMLTextField {
1713 function getSize() {
1714 return isset( $this->mParams['size'] )
1715 ? $this->mParams['size']
1716 : 20;
1719 function validate( $value, $alldata ) {
1720 $p = parent::validate( $value, $alldata );
1722 if ( $p !== true ) {
1723 return $p;
1726 $value = trim( $value );
1728 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1729 # with the addition that a leading '+' sign is ok.
1730 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1731 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1734 # The "int" part of these message names is rather confusing.
1735 # They make equal sense for all numbers.
1736 if ( isset( $this->mParams['min'] ) ) {
1737 $min = $this->mParams['min'];
1739 if ( $min > $value ) {
1740 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1744 if ( isset( $this->mParams['max'] ) ) {
1745 $max = $this->mParams['max'];
1747 if ( $max < $value ) {
1748 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1752 return true;
1757 * A field that must contain a number
1759 class HTMLIntField extends HTMLFloatField {
1760 function validate( $value, $alldata ) {
1761 $p = parent::validate( $value, $alldata );
1763 if ( $p !== true ) {
1764 return $p;
1767 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1768 # with the addition that a leading '+' sign is ok. Note that leading zeros
1769 # are fine, and will be left in the input, which is useful for things like
1770 # phone numbers when you know that they are integers (the HTML5 type=tel
1771 # input does not require its value to be numeric). If you want a tidier
1772 # value to, eg, save in the DB, clean it up with intval().
1773 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1775 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1778 return true;
1783 * A checkbox field
1785 class HTMLCheckField extends HTMLFormField {
1786 function getInputHTML( $value ) {
1787 if ( !empty( $this->mParams['invert'] ) ) {
1788 $value = !$value;
1791 $attr = $this->getTooltipAndAccessKey();
1792 $attr['id'] = $this->mID;
1794 if ( !empty( $this->mParams['disabled'] ) ) {
1795 $attr['disabled'] = 'disabled';
1798 if ( $this->mClass !== '' ) {
1799 $attr['class'] = $this->mClass;
1802 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1803 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1807 * For a checkbox, the label goes on the right hand side, and is
1808 * added in getInputHTML(), rather than HTMLFormField::getRow()
1809 * @return String
1811 function getLabel() {
1812 return '&#160;';
1816 * @param $request WebRequest
1817 * @return String
1819 function loadDataFromRequest( $request ) {
1820 $invert = false;
1821 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1822 $invert = true;
1825 // GetCheck won't work like we want for checks.
1826 // Fetch the value in either one of the two following case:
1827 // - we have a valid token (form got posted or GET forged by the user)
1828 // - checkbox name has a value (false or true), ie is not null
1829 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1830 // XOR has the following truth table, which is what we want
1831 // INVERT VALUE | OUTPUT
1832 // true true | false
1833 // false true | true
1834 // false false | false
1835 // true false | true
1836 return $request->getBool( $this->mName ) xor $invert;
1837 } else {
1838 return $this->getDefault();
1844 * A checkbox matrix
1845 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1846 * options, uses an array of rows and an array of columns to dynamically
1847 * construct a matrix of options. The tags used to identify a particular cell
1848 * are of the form "columnName-rowName"
1850 * Options:
1851 * columns: Required list of columns in the matrix.
1852 * rows: Required list of rows in the matrix.
1853 * force-options-on: Accepts array of column-row tags to be displayed as enabled
1854 * but unavailable to change
1855 * force-options-off: Accepts array of column-row tags to be displayed as disabled
1856 * but unavailable to change.
1858 class HTMLCheckMatrix extends HTMLFormField implements HTMLNestedFilterable {
1860 static private $requiredParams = array(
1861 // Required by underlying HTMLFormField
1862 'fieldname',
1863 // Required by HTMLCheckMatrix
1864 'rows', 'columns'
1867 public function __construct( $params ) {
1868 $missing = array_diff( self::$requiredParams, array_keys( $params ) );
1869 if ( $missing ) {
1870 throw HTMLFormFieldRequiredOptionsException::create( $this, $missing );
1872 parent::__construct( $params );
1875 function validate( $value, $alldata ) {
1876 $rows = $this->mParams['rows'];
1877 $columns = $this->mParams['columns'];
1879 // Make sure user-defined validation callback is run
1880 $p = parent::validate( $value, $alldata );
1881 if ( $p !== true ) {
1882 return $p;
1885 // Make sure submitted value is an array
1886 if ( !is_array( $value ) ) {
1887 return false;
1890 // If all options are valid, array_intersect of the valid options
1891 // and the provided options will return the provided options.
1892 $validOptions = array();
1893 foreach ( $rows as $rowTag ) {
1894 foreach ( $columns as $columnTag ) {
1895 $validOptions[] = $columnTag . '-' . $rowTag;
1898 $validValues = array_intersect( $value, $validOptions );
1899 if ( count( $validValues ) == count( $value ) ) {
1900 return true;
1901 } else {
1902 return $this->msg( 'htmlform-select-badoption' )->parse();
1907 * Build a table containing a matrix of checkbox options.
1908 * The value of each option is a combination of the row tag and column tag.
1909 * mParams['rows'] is an array with row labels as keys and row tags as values.
1910 * mParams['columns'] is an array with column labels as keys and column tags as values.
1911 * @param array $value of the options that should be checked
1912 * @return String
1914 function getInputHTML( $value ) {
1915 $html = '';
1916 $tableContents = '';
1917 $attribs = array();
1918 $rows = $this->mParams['rows'];
1919 $columns = $this->mParams['columns'];
1921 // If the disabled param is set, disable all the options
1922 if ( !empty( $this->mParams['disabled'] ) ) {
1923 $attribs['disabled'] = 'disabled';
1926 // Build the column headers
1927 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
1928 foreach ( $columns as $columnLabel => $columnTag ) {
1929 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
1931 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
1933 // Build the options matrix
1934 foreach ( $rows as $rowLabel => $rowTag ) {
1935 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
1936 foreach ( $columns as $columnTag ) {
1937 $thisTag = "$columnTag-$rowTag";
1938 // Construct the checkbox
1939 $thisAttribs = array(
1940 'id' => "{$this->mID}-$thisTag",
1941 'value' => $thisTag,
1943 $checked = in_array( $thisTag, (array)$value, true );
1944 if ( $this->isTagForcedOff( $thisTag ) ) {
1945 $checked = false;
1946 $thisAttribs['disabled'] = 1;
1947 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
1948 $checked = true;
1949 $thisAttribs['disabled'] = 1;
1951 $rowContents .= Html::rawElement(
1952 'td',
1953 array(),
1954 Xml::check( "{$this->mName}[]", $checked, $attribs + $thisAttribs )
1957 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
1960 // Put it all in a table
1961 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
1962 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
1964 return $html;
1967 protected function isTagForcedOff( $tag ) {
1968 return isset( $this->mParams['force-options-off'] )
1969 && in_array( $tag, $this->mParams['force-options-off'] );
1972 protected function isTagForcedOn( $tag ) {
1973 return isset( $this->mParams['force-options-on'] )
1974 && in_array( $tag, $this->mParams['force-options-on'] );
1978 * Get the complete table row for the input, including help text,
1979 * labels, and whatever.
1980 * We override this function since the label should always be on a separate
1981 * line above the options in the case of a checkbox matrix, i.e. it's always
1982 * a "vertical-label".
1983 * @param string $value the value to set the input to
1984 * @return String complete HTML table row
1986 function getTableRow( $value ) {
1987 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1988 $inputHtml = $this->getInputHTML( $value );
1989 $fieldType = get_class( $this );
1990 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1991 $cellAttributes = array( 'colspan' => 2 );
1993 $label = $this->getLabelHtml( $cellAttributes );
1995 $field = Html::rawElement(
1996 'td',
1997 array( 'class' => 'mw-input' ) + $cellAttributes,
1998 $inputHtml . "\n$errors"
2001 $html = Html::rawElement( 'tr',
2002 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
2003 $html .= Html::rawElement( 'tr',
2004 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
2005 $field );
2007 return $html . $helptext;
2011 * @param $request WebRequest
2012 * @return Array
2014 function loadDataFromRequest( $request ) {
2015 if ( $this->mParent->getMethod() == 'post' ) {
2016 if ( $request->wasPosted() ) {
2017 // Checkboxes are not added to the request arrays if they're not checked,
2018 // so it's perfectly possible for there not to be an entry at all
2019 return $request->getArray( $this->mName, array() );
2020 } else {
2021 // That's ok, the user has not yet submitted the form, so show the defaults
2022 return $this->getDefault();
2024 } else {
2025 // This is the impossible case: if we look at $_GET and see no data for our
2026 // field, is it because the user has not yet submitted the form, or that they
2027 // have submitted it with all the options unchecked. We will have to assume the
2028 // latter, which basically means that you can't specify 'positive' defaults
2029 // for GET forms.
2030 return $request->getArray( $this->mName, array() );
2034 function getDefault() {
2035 if ( isset( $this->mDefault ) ) {
2036 return $this->mDefault;
2037 } else {
2038 return array();
2042 function filterDataForSubmit( $data ) {
2043 $columns = HTMLFormField::flattenOptions( $this->mParams['columns'] );
2044 $rows = HTMLFormField::flattenOptions( $this->mParams['rows'] );
2045 $res = array();
2046 foreach ( $columns as $column ) {
2047 foreach ( $rows as $row ) {
2048 // Make sure option hasn't been forced
2049 $thisTag = "$column-$row";
2050 if ( $this->isTagForcedOff( $thisTag ) ) {
2051 $res[$thisTag] = false;
2052 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2053 $res[$thisTag] = true;
2054 } else {
2055 $res[$thisTag] = in_array( $thisTag, $data );
2060 return $res;
2065 * A select dropdown field. Basically a wrapper for Xmlselect class
2067 class HTMLSelectField extends HTMLFormField {
2068 function validate( $value, $alldata ) {
2069 $p = parent::validate( $value, $alldata );
2071 if ( $p !== true ) {
2072 return $p;
2075 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2077 if ( in_array( $value, $validOptions ) ) {
2078 return true;
2079 } else {
2080 return $this->msg( 'htmlform-select-badoption' )->parse();
2084 function getInputHTML( $value ) {
2085 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
2087 # If one of the options' 'name' is int(0), it is automatically selected.
2088 # because PHP sucks and thinks int(0) == 'some string'.
2089 # Working around this by forcing all of them to strings.
2090 foreach ( $this->mParams['options'] as &$opt ) {
2091 if ( is_int( $opt ) ) {
2092 $opt = strval( $opt );
2095 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2097 if ( !empty( $this->mParams['disabled'] ) ) {
2098 $select->setAttribute( 'disabled', 'disabled' );
2101 if ( $this->mClass !== '' ) {
2102 $select->setAttribute( 'class', $this->mClass );
2105 $select->addOptions( $this->mParams['options'] );
2107 return $select->getHTML();
2112 * Select dropdown field, with an additional "other" textbox.
2114 class HTMLSelectOrOtherField extends HTMLTextField {
2116 function __construct( $params ) {
2117 if ( !in_array( 'other', $params['options'], true ) ) {
2118 $msg = isset( $params['other'] ) ?
2119 $params['other'] :
2120 wfMessage( 'htmlform-selectorother-other' )->text();
2121 $params['options'][$msg] = 'other';
2124 parent::__construct( $params );
2127 static function forceToStringRecursive( $array ) {
2128 if ( is_array( $array ) ) {
2129 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2130 } else {
2131 return strval( $array );
2135 function getInputHTML( $value ) {
2136 $valInSelect = false;
2138 if ( $value !== false ) {
2139 $valInSelect = in_array(
2140 $value,
2141 HTMLFormField::flattenOptions( $this->mParams['options'] )
2145 $selected = $valInSelect ? $value : 'other';
2147 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2149 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2150 $select->addOptions( $opts );
2152 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2154 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2156 if ( !empty( $this->mParams['disabled'] ) ) {
2157 $select->setAttribute( 'disabled', 'disabled' );
2158 $tbAttribs['disabled'] = 'disabled';
2161 $select = $select->getHTML();
2163 if ( isset( $this->mParams['maxlength'] ) ) {
2164 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2167 if ( $this->mClass !== '' ) {
2168 $tbAttribs['class'] = $this->mClass;
2171 $textbox = Html::input(
2172 $this->mName . '-other',
2173 $valInSelect ? '' : $value,
2174 'text',
2175 $tbAttribs
2178 return "$select<br />\n$textbox";
2182 * @param $request WebRequest
2183 * @return String
2185 function loadDataFromRequest( $request ) {
2186 if ( $request->getCheck( $this->mName ) ) {
2187 $val = $request->getText( $this->mName );
2189 if ( $val == 'other' ) {
2190 $val = $request->getText( $this->mName . '-other' );
2193 return $val;
2194 } else {
2195 return $this->getDefault();
2201 * Multi-select field
2203 class HTMLMultiSelectField extends HTMLFormField implements HTMLNestedFilterable {
2205 function validate( $value, $alldata ) {
2206 $p = parent::validate( $value, $alldata );
2208 if ( $p !== true ) {
2209 return $p;
2212 if ( !is_array( $value ) ) {
2213 return false;
2216 # If all options are valid, array_intersect of the valid options
2217 # and the provided options will return the provided options.
2218 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2220 $validValues = array_intersect( $value, $validOptions );
2221 if ( count( $validValues ) == count( $value ) ) {
2222 return true;
2223 } else {
2224 return $this->msg( 'htmlform-select-badoption' )->parse();
2228 function getInputHTML( $value ) {
2229 $html = $this->formatOptions( $this->mParams['options'], $value );
2231 return $html;
2234 function formatOptions( $options, $value ) {
2235 $html = '';
2237 $attribs = array();
2239 if ( !empty( $this->mParams['disabled'] ) ) {
2240 $attribs['disabled'] = 'disabled';
2243 foreach ( $options as $label => $info ) {
2244 if ( is_array( $info ) ) {
2245 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2246 $html .= $this->formatOptions( $info, $value );
2247 } else {
2248 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2250 $checkbox = Xml::check(
2251 $this->mName . '[]',
2252 in_array( $info, $value, true ),
2253 $attribs + $thisAttribs );
2254 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2256 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2260 return $html;
2264 * @param $request WebRequest
2265 * @return String
2267 function loadDataFromRequest( $request ) {
2268 if ( $this->mParent->getMethod() == 'post' ) {
2269 if ( $request->wasPosted() ) {
2270 # Checkboxes are just not added to the request arrays if they're not checked,
2271 # so it's perfectly possible for there not to be an entry at all
2272 return $request->getArray( $this->mName, array() );
2273 } else {
2274 # That's ok, the user has not yet submitted the form, so show the defaults
2275 return $this->getDefault();
2277 } else {
2278 # This is the impossible case: if we look at $_GET and see no data for our
2279 # field, is it because the user has not yet submitted the form, or that they
2280 # have submitted it with all the options unchecked? We will have to assume the
2281 # latter, which basically means that you can't specify 'positive' defaults
2282 # for GET forms.
2283 # @todo FIXME...
2284 return $request->getArray( $this->mName, array() );
2288 function getDefault() {
2289 if ( isset( $this->mDefault ) ) {
2290 return $this->mDefault;
2291 } else {
2292 return array();
2296 function filterDataForSubmit( $data ) {
2297 $options = HTMLFormField::flattenOptions( $this->mParams['options'] );
2299 $res = array();
2300 foreach ( $options as $opt ) {
2301 $res["$opt"] = in_array( $opt, $data );
2304 return $res;
2307 protected function needsLabel() {
2308 return false;
2313 * Double field with a dropdown list constructed from a system message in the format
2314 * * Optgroup header
2315 * ** <option value>
2316 * * New Optgroup header
2317 * Plus a text field underneath for an additional reason. The 'value' of the field is
2318 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2319 * select dropdown.
2320 * @todo FIXME: If made 'required', only the text field should be compulsory.
2322 class HTMLSelectAndOtherField extends HTMLSelectField {
2324 function __construct( $params ) {
2325 if ( array_key_exists( 'other', $params ) ) {
2326 } elseif ( array_key_exists( 'other-message', $params ) ) {
2327 $params['other'] = wfMessage( $params['other-message'] )->plain();
2328 } else {
2329 $params['other'] = null;
2332 if ( array_key_exists( 'options', $params ) ) {
2333 # Options array already specified
2334 } elseif ( array_key_exists( 'options-message', $params ) ) {
2335 # Generate options array from a system message
2336 $params['options'] = self::parseMessage(
2337 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2338 $params['other']
2340 } else {
2341 # Sulk
2342 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2344 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2346 parent::__construct( $params );
2350 * Build a drop-down box from a textual list.
2351 * @param string $string message text
2352 * @param string $otherName name of "other reason" option
2353 * @return Array
2354 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2356 public static function parseMessage( $string, $otherName = null ) {
2357 if ( $otherName === null ) {
2358 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2361 $optgroup = false;
2362 $options = array( $otherName => 'other' );
2364 foreach ( explode( "\n", $string ) as $option ) {
2365 $value = trim( $option );
2366 if ( $value == '' ) {
2367 continue;
2368 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2369 # A new group is starting...
2370 $value = trim( substr( $value, 1 ) );
2371 $optgroup = $value;
2372 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2373 # groupmember
2374 $opt = trim( substr( $value, 2 ) );
2375 if ( $optgroup === false ) {
2376 $options[$opt] = $opt;
2377 } else {
2378 $options[$optgroup][$opt] = $opt;
2380 } else {
2381 # groupless reason list
2382 $optgroup = false;
2383 $options[$option] = $option;
2387 return $options;
2390 function getInputHTML( $value ) {
2391 $select = parent::getInputHTML( $value[1] );
2393 $textAttribs = array(
2394 'id' => $this->mID . '-other',
2395 'size' => $this->getSize(),
2398 if ( $this->mClass !== '' ) {
2399 $textAttribs['class'] = $this->mClass;
2402 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2403 if ( isset( $this->mParams[$param] ) ) {
2404 $textAttribs[$param] = '';
2408 $textbox = Html::input(
2409 $this->mName . '-other',
2410 $value[2],
2411 'text',
2412 $textAttribs
2415 return "$select<br />\n$textbox";
2419 * @param $request WebRequest
2420 * @return Array("<overall message>","<select value>","<text field value>")
2422 function loadDataFromRequest( $request ) {
2423 if ( $request->getCheck( $this->mName ) ) {
2425 $list = $request->getText( $this->mName );
2426 $text = $request->getText( $this->mName . '-other' );
2428 if ( $list == 'other' ) {
2429 $final = $text;
2430 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2431 # User has spoofed the select form to give an option which wasn't
2432 # in the original offer. Sulk...
2433 $final = $text;
2434 } elseif ( $text == '' ) {
2435 $final = $list;
2436 } else {
2437 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2440 } else {
2441 $final = $this->getDefault();
2443 $list = 'other';
2444 $text = $final;
2445 foreach ( $this->mFlatOptions as $option ) {
2446 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2447 if ( strpos( $text, $match ) === 0 ) {
2448 $list = $option;
2449 $text = substr( $text, strlen( $match ) );
2450 break;
2454 return array( $final, $list, $text );
2457 function getSize() {
2458 return isset( $this->mParams['size'] )
2459 ? $this->mParams['size']
2460 : 45;
2463 function validate( $value, $alldata ) {
2464 # HTMLSelectField forces $value to be one of the options in the select
2465 # field, which is not useful here. But we do want the validation further up
2466 # the chain
2467 $p = parent::validate( $value[1], $alldata );
2469 if ( $p !== true ) {
2470 return $p;
2473 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2474 return $this->msg( 'htmlform-required' )->parse();
2477 return true;
2482 * Radio checkbox fields.
2484 class HTMLRadioField extends HTMLFormField {
2486 function validate( $value, $alldata ) {
2487 $p = parent::validate( $value, $alldata );
2489 if ( $p !== true ) {
2490 return $p;
2493 if ( !is_string( $value ) && !is_int( $value ) ) {
2494 return false;
2497 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2499 if ( in_array( $value, $validOptions ) ) {
2500 return true;
2501 } else {
2502 return $this->msg( 'htmlform-select-badoption' )->parse();
2507 * This returns a block of all the radio options, in one cell.
2508 * @see includes/HTMLFormField#getInputHTML()
2509 * @param $value String
2510 * @return String
2512 function getInputHTML( $value ) {
2513 $html = $this->formatOptions( $this->mParams['options'], $value );
2515 return $html;
2518 function formatOptions( $options, $value ) {
2519 $html = '';
2521 $attribs = array();
2522 if ( !empty( $this->mParams['disabled'] ) ) {
2523 $attribs['disabled'] = 'disabled';
2526 # TODO: should this produce an unordered list perhaps?
2527 foreach ( $options as $label => $info ) {
2528 if ( is_array( $info ) ) {
2529 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2530 $html .= $this->formatOptions( $info, $value );
2531 } else {
2532 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2533 $radio = Xml::radio(
2534 $this->mName,
2535 $info,
2536 $info == $value,
2537 $attribs + array( 'id' => $id )
2539 $radio .= '&#160;' .
2540 Html::rawElement( 'label', array( 'for' => $id ), $label );
2542 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2546 return $html;
2549 protected function needsLabel() {
2550 return false;
2555 * An information field (text blob), not a proper input.
2557 class HTMLInfoField extends HTMLFormField {
2558 public function __construct( $info ) {
2559 $info['nodata'] = true;
2561 parent::__construct( $info );
2564 public function getInputHTML( $value ) {
2565 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2568 public function getTableRow( $value ) {
2569 if ( !empty( $this->mParams['rawrow'] ) ) {
2570 return $value;
2573 return parent::getTableRow( $value );
2577 * @since 1.20
2579 public function getDiv( $value ) {
2580 if ( !empty( $this->mParams['rawrow'] ) ) {
2581 return $value;
2584 return parent::getDiv( $value );
2588 * @since 1.20
2590 public function getRaw( $value ) {
2591 if ( !empty( $this->mParams['rawrow'] ) ) {
2592 return $value;
2595 return parent::getRaw( $value );
2598 protected function needsLabel() {
2599 return false;
2603 class HTMLHiddenField extends HTMLFormField {
2604 public function __construct( $params ) {
2605 parent::__construct( $params );
2607 # Per HTML5 spec, hidden fields cannot be 'required'
2608 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2609 unset( $this->mParams['required'] );
2612 public function getTableRow( $value ) {
2613 $params = array();
2614 if ( $this->mID ) {
2615 $params['id'] = $this->mID;
2618 $this->mParent->addHiddenField(
2619 $this->mName,
2620 $this->mDefault,
2621 $params
2624 return '';
2628 * @since 1.20
2630 public function getDiv( $value ) {
2631 return $this->getTableRow( $value );
2635 * @since 1.20
2637 public function getRaw( $value ) {
2638 return $this->getTableRow( $value );
2641 public function getInputHTML( $value ) {
2642 return '';
2647 * Add a submit button inline in the form (as opposed to
2648 * HTMLForm::addButton(), which will add it at the end).
2650 class HTMLSubmitField extends HTMLButtonField {
2651 protected $buttonType = 'submit';
2655 * Adds a generic button inline to the form. Does not do anything, you must add
2656 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2657 * wish to add a submit button to a form.
2659 * @since 1.22
2661 class HTMLButtonField extends HTMLFormField {
2662 protected $buttonType = 'button';
2664 public function __construct( $info ) {
2665 $info['nodata'] = true;
2666 parent::__construct( $info );
2669 public function getInputHTML( $value ) {
2670 $attr = array(
2671 'class' => 'mw-htmlform-submit ' . $this->mClass,
2672 'id' => $this->mID,
2675 if ( !empty( $this->mParams['disabled'] ) ) {
2676 $attr['disabled'] = 'disabled';
2679 return Html::input(
2680 $this->mName,
2681 $value,
2682 $this->buttonType,
2683 $attr
2687 protected function needsLabel() {
2688 return false;
2692 * Button cannot be invalid
2693 * @param $value String
2694 * @param $alldata Array
2695 * @return Bool
2697 public function validate( $value, $alldata ) {
2698 return true;
2702 class HTMLEditTools extends HTMLFormField {
2703 public function getInputHTML( $value ) {
2704 return '';
2707 public function getTableRow( $value ) {
2708 $msg = $this->formatMsg();
2710 return '<tr><td></td><td class="mw-input">'
2711 . '<div class="mw-editTools">'
2712 . $msg->parseAsBlock()
2713 . "</div></td></tr>\n";
2717 * @since 1.20
2719 public function getDiv( $value ) {
2720 $msg = $this->formatMsg();
2721 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2725 * @since 1.20
2727 public function getRaw( $value ) {
2728 return $this->getDiv( $value );
2731 protected function formatMsg() {
2732 if ( empty( $this->mParams['message'] ) ) {
2733 $msg = $this->msg( 'edittools' );
2734 } else {
2735 $msg = $this->msg( $this->mParams['message'] );
2736 if ( $msg->isDisabled() ) {
2737 $msg = $this->msg( 'edittools' );
2740 $msg->inContentLanguage();
2741 return $msg;
2745 class HTMLApiField extends HTMLFormField {
2746 public function getTableRow( $value ) {
2747 return '';
2750 public function getDiv( $value ) {
2751 return $this->getTableRow( $value );
2754 public function getRaw( $value ) {
2755 return $this->getTableRow( $value );
2758 public function getInputHTML( $value ) {
2759 return '';
2763 interface HTMLNestedFilterable {
2765 * Support for seperating multi-option preferences into multiple preferences
2766 * Due to lack of array support.
2767 * @param $data array
2769 function filterDataForSubmit( $data );
2772 class HTMLFormFieldRequiredOptionsException extends MWException {
2773 static public function create( HTMLFormField $field, array $missing ) {
2774 return new self( sprintf(
2775 "Form type `%s` expected the following parameters to be set: %s",
2776 get_class( $field ),
2777 implode( ', ', $missing )
2778 ) );