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
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
56 * 'label' -- alternatively, a raw text message. Overridden by
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
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.
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:
83 * $form = new HTMLForm( $someFields );
84 * $form->setMethod( 'get' )
85 * ->setWrapperLegendMsg( 'message-key' )
90 * Note that you will have prepareForm and displayForm at the end. Other
91 * methods call done after that would simply not be part of the form :(
93 * TODO: Document 'section' / 'subsection' stuff
95 class HTMLForm
extends ContextSource
{
97 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
98 private static $typeMappings = array(
99 'api' => 'HTMLApiField',
100 'text' => 'HTMLTextField',
101 'textarea' => 'HTMLTextAreaField',
102 'select' => 'HTMLSelectField',
103 'radio' => 'HTMLRadioField',
104 'multiselect' => 'HTMLMultiSelectField',
105 'check' => 'HTMLCheckField',
106 'toggle' => 'HTMLCheckField',
107 'int' => 'HTMLIntField',
108 'float' => 'HTMLFloatField',
109 'info' => 'HTMLInfoField',
110 'selectorother' => 'HTMLSelectOrOtherField',
111 'selectandother' => 'HTMLSelectAndOtherField',
112 'submit' => 'HTMLSubmitField',
113 'hidden' => 'HTMLHiddenField',
114 'edittools' => 'HTMLEditTools',
115 'checkmatrix' => 'HTMLCheckMatrix',
117 // HTMLTextField will output the correct type="" attribute automagically.
118 // There are about four zillion other HTML5 input types, like url, but
119 // we don't use those at the moment, so no point in adding all of them.
120 'email' => 'HTMLTextField',
121 'password' => 'HTMLTextField',
124 protected $mMessagePrefix;
126 /** @var HTMLFormField[] */
127 protected $mFlatFields;
129 protected $mFieldTree;
130 protected $mShowReset = false;
131 protected $mShowSubmit = true;
134 protected $mSubmitCallback;
135 protected $mValidationErrorMessage;
137 protected $mPre = '';
138 protected $mHeader = '';
139 protected $mFooter = '';
140 protected $mSectionHeaders = array();
141 protected $mSectionFooters = array();
142 protected $mPost = '';
145 protected $mSubmitID;
146 protected $mSubmitName;
147 protected $mSubmitText;
148 protected $mSubmitTooltip;
151 protected $mMethod = 'post';
154 * Form action URL. false means we will use the URL to set Title
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
173 protected $mSubSectionBeforeFields = true;
176 * Format in which to display form. For viable options,
177 * @see $availableDisplayFormats
180 protected $displayFormat = 'table';
183 * Available formats in which to display the form
186 protected $availableDisplayFormats = array(
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;
206 if ( is_string( $context ) && $messagePrefix === '' ) {
207 // it's actually $messagePrefix
208 $this->mMessagePrefix
= $context;
212 // Expand out into a tree.
213 $loadedDescriptor = array();
214 $this->mFlatFields
= array();
216 foreach ( $descriptor as $fieldname => $info ) {
217 $section = isset( $info['section'] )
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;
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
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;
267 * Getter for displayFormat
271 public function getDisplayFormat() {
272 return $this->displayFormat
;
276 * Add the HTMLForm-specific JavaScript, if it hasn't been
278 * @deprecated since 1.18 load modules with ResourceLoader instead
280 static function addJS() { wfDeprecated( __METHOD__
, '1.18' ); }
283 * Initialise a new Object for the field
284 * @param $fieldname string
285 * @param string $descriptor input Descriptor, as described above
286 * @throws MWException
287 * @return HTMLFormField subclass
289 static function loadInputFromParameters( $fieldname, $descriptor ) {
290 if ( isset( $descriptor['class'] ) ) {
291 $class = $descriptor['class'];
292 } elseif ( isset( $descriptor['type'] ) ) {
293 $class = self
::$typeMappings[$descriptor['type']];
294 $descriptor['class'] = $class;
300 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
303 $descriptor['fieldname'] = $fieldname;
306 # This will throw a fatal error whenever someone try to use
307 # 'class' to feed a CSS class instead of 'cssclass'. Would be
308 # great to avoid the fatal error and show a nice error.
309 $obj = new $class( $descriptor );
315 * Prepare form for submission.
317 * @attention When doing method chaining, that should be the very last
318 * method call before displayForm().
320 * @throws MWException
321 * @return HTMLForm $this for chaining calls (since 1.20)
323 function prepareForm() {
324 # Check if we have the info we need
325 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
326 throw new MWException( "You must call setTitle() on an HTMLForm" );
329 # Load data from the request.
335 * Try submitting, with edit token check first
336 * @return Status|boolean
338 function tryAuthorizedSubmit() {
342 if ( $this->getMethod() != 'post' ) {
343 $submit = true; // no session check needed
344 } elseif ( $this->getRequest()->wasPosted() ) {
345 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
346 if ( $this->getUser()->isLoggedIn() ||
$editToken != null ) {
347 // Session tokens for logged-out users have no security value.
348 // However, if the user gave one, check it in order to give a nice
349 // "session expired" error instead of "permission denied" or such.
350 $submit = $this->getUser()->matchEditToken( $editToken );
357 $result = $this->trySubmit();
364 * The here's-one-I-made-earlier option: do the submission if
365 * posted, or display the form with or without funky validation
367 * @return Bool or Status whether submission was successful.
370 $this->prepareForm();
372 $result = $this->tryAuthorizedSubmit();
373 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
377 $this->displayForm( $result );
382 * Validate all the fields, and call the submission callback
383 * function if everything is kosher.
384 * @throws MWException
385 * @return Mixed Bool true == Successful submission, Bool false
386 * == No submission attempted, anything else == Error to
389 function trySubmit() {
390 # Check for validation
391 foreach ( $this->mFlatFields
as $fieldname => $field ) {
392 if ( !empty( $field->mParams
['nodata'] ) ) {
395 if ( $field->validate(
396 $this->mFieldData
[$fieldname],
400 return isset( $this->mValidationErrorMessage
)
401 ?
$this->mValidationErrorMessage
402 : array( 'htmlform-invalid-input' );
406 $callback = $this->mSubmitCallback
;
407 if ( !is_callable( $callback ) ) {
408 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
411 $data = $this->filterDataForSubmit( $this->mFieldData
);
413 $res = call_user_func( $callback, $data, $this );
419 * Set a callback to a function to do something with the form
420 * once it's been successfully validated.
421 * @param string $cb function name. The function will be passed
422 * the output from HTMLForm::filterDataForSubmit, and must
423 * return Bool true on success, Bool false if no submission
424 * was attempted, or String HTML output to display on error.
425 * @return HTMLForm $this for chaining calls (since 1.20)
427 function setSubmitCallback( $cb ) {
428 $this->mSubmitCallback
= $cb;
433 * Set a message to display on a validation error.
434 * @param $msg Mixed String or Array of valid inputs to wfMessage()
435 * (so each entry can be either a String or Array)
436 * @return HTMLForm $this for chaining calls (since 1.20)
438 function setValidationErrorMessage( $msg ) {
439 $this->mValidationErrorMessage
= $msg;
444 * Set the introductory message, overwriting any existing message.
445 * @param string $msg complete text of message to display
446 * @return HTMLForm $this for chaining calls (since 1.20)
448 function setIntro( $msg ) {
449 $this->setPreText( $msg );
454 * Set the introductory message, overwriting any existing message.
456 * @param string $msg complete text of message to display
457 * @return HTMLForm $this for chaining calls (since 1.20)
459 function setPreText( $msg ) {
465 * Add introductory text.
466 * @param string $msg complete text of message to display
467 * @return HTMLForm $this for chaining calls (since 1.20)
469 function addPreText( $msg ) {
475 * Add header text, inside the form.
476 * @param string $msg complete text of message to display
477 * @param string $section The section to add the header to
478 * @return HTMLForm $this for chaining calls (since 1.20)
480 function addHeaderText( $msg, $section = null ) {
481 if ( is_null( $section ) ) {
482 $this->mHeader
.= $msg;
484 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
485 $this->mSectionHeaders
[$section] = '';
487 $this->mSectionHeaders
[$section] .= $msg;
493 * Set header text, inside the form.
495 * @param string $msg complete text of message to display
496 * @param $section The section to add the header to
497 * @return HTMLForm $this for chaining calls (since 1.20)
499 function setHeaderText( $msg, $section = null ) {
500 if ( is_null( $section ) ) {
501 $this->mHeader
= $msg;
503 $this->mSectionHeaders
[$section] = $msg;
509 * Add footer text, inside the form.
510 * @param string $msg complete text of message to display
511 * @param string $section The section to add the footer text to
512 * @return HTMLForm $this for chaining calls (since 1.20)
514 function addFooterText( $msg, $section = null ) {
515 if ( is_null( $section ) ) {
516 $this->mFooter
.= $msg;
518 if ( !isset( $this->mSectionFooters
[$section] ) ) {
519 $this->mSectionFooters
[$section] = '';
521 $this->mSectionFooters
[$section] .= $msg;
527 * Set footer text, inside the form.
529 * @param string $msg complete text of message to display
530 * @param string $section The section to add the footer text to
531 * @return HTMLForm $this for chaining calls (since 1.20)
533 function setFooterText( $msg, $section = null ) {
534 if ( is_null( $section ) ) {
535 $this->mFooter
= $msg;
537 $this->mSectionFooters
[$section] = $msg;
543 * Add text to the end of the display.
544 * @param string $msg complete text of message to display
545 * @return HTMLForm $this for chaining calls (since 1.20)
547 function addPostText( $msg ) {
548 $this->mPost
.= $msg;
553 * Set text at the end of the display.
554 * @param string $msg complete text of message to display
555 * @return HTMLForm $this for chaining calls (since 1.20)
557 function setPostText( $msg ) {
563 * Add a hidden field to the output
564 * @param string $name field name. This will be used exactly as entered
565 * @param string $value field value
566 * @param $attribs Array
567 * @return HTMLForm $this for chaining calls (since 1.20)
569 public function addHiddenField( $name, $value, $attribs = array() ) {
570 $attribs +
= array( 'name' => $name );
571 $this->mHiddenFields
[] = array( $value, $attribs );
576 * Add a button to the form
577 * @param string $name field name.
578 * @param string $value field value
579 * @param string $id DOM id for the button (default: null)
580 * @param $attribs Array
581 * @return HTMLForm $this for chaining calls (since 1.20)
583 public function addButton( $name, $value, $id = null, $attribs = null ) {
584 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
589 * Display the form (sending to $wgOut), with an appropriate error
590 * message or stack of messages, and any validation errors, etc.
592 * @attention You should call prepareForm() before calling this function.
593 * Moreover, when doing method chaining this should be the very last method
594 * call just after prepareForm().
596 * @param $submitResult Mixed output from HTMLForm::trySubmit()
597 * @return Nothing, should be last call
599 function displayForm( $submitResult ) {
600 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
604 * Returns the raw HTML generated by the form
605 * @param $submitResult Mixed output from HTMLForm::trySubmit()
608 function getHTML( $submitResult ) {
609 # For good measure (it is the default)
610 $this->getOutput()->preventClickjacking();
611 $this->getOutput()->addModules( 'mediawiki.htmlform' );
614 . $this->getErrors( $submitResult )
617 . $this->getHiddenFields()
618 . $this->getButtons()
622 $html = $this->wrapForm( $html );
624 return '' . $this->mPre
. $html . $this->mPost
;
628 * Wrap the form innards in an actual "<form>" element
629 * @param string $html HTML contents to wrap.
630 * @return String wrapped HTML.
632 function wrapForm( $html ) {
634 # Include a <fieldset> wrapper for style, if requested.
635 if ( $this->mWrapperLegend
!== false ) {
636 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
638 # Use multipart/form-data
639 $encType = $this->mUseMultipart
640 ?
'multipart/form-data'
641 : 'application/x-www-form-urlencoded';
644 'action' => $this->mAction
=== false ?
$this->getTitle()->getFullURL() : $this->mAction
,
645 'method' => $this->mMethod
,
646 'class' => 'visualClear',
647 'enctype' => $encType,
649 if ( !empty( $this->mId
) ) {
650 $attribs['id'] = $this->mId
;
653 return Html
::rawElement( 'form', $attribs, $html );
657 * Get the hidden fields that should go inside the form.
658 * @return String HTML.
660 function getHiddenFields() {
661 global $wgArticlePath;
664 if ( $this->getMethod() == 'post' ) {
665 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
666 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
669 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
670 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
673 foreach ( $this->mHiddenFields
as $data ) {
674 list( $value, $attribs ) = $data;
675 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
682 * Get the submit and (potentially) reset buttons.
683 * @return String HTML.
685 function getButtons() {
688 if ( $this->mShowSubmit
) {
691 if ( isset( $this->mSubmitID
) ) {
692 $attribs['id'] = $this->mSubmitID
;
695 if ( isset( $this->mSubmitName
) ) {
696 $attribs['name'] = $this->mSubmitName
;
699 if ( isset( $this->mSubmitTooltip
) ) {
700 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
703 $attribs['class'] = 'mw-htmlform-submit';
705 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
708 if ( $this->mShowReset
) {
709 $html .= Html
::element(
713 'value' => $this->msg( 'htmlform-reset' )->text()
718 foreach ( $this->mButtons
as $button ) {
721 'name' => $button['name'],
722 'value' => $button['value']
725 if ( $button['attribs'] ) {
726 $attrs +
= $button['attribs'];
729 if ( isset( $button['id'] ) ) {
730 $attrs['id'] = $button['id'];
733 $html .= Html
::element( 'input', $attrs );
740 * Get the whole body of the form.
744 return $this->displaySection( $this->mFieldTree
);
748 * Format and display an error message stack.
749 * @param $errors String|Array|Status
752 function getErrors( $errors ) {
753 if ( $errors instanceof Status
) {
754 if ( $errors->isOK() ) {
757 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
759 } elseif ( is_array( $errors ) ) {
760 $errorstr = $this->formatErrors( $errors );
766 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
771 * Format a stack of error messages into a single HTML string
772 * @param array $errors of message keys/values
773 * @return String HTML, a "<ul>" list of errors
775 public static function formatErrors( $errors ) {
778 foreach ( $errors as $error ) {
779 if ( is_array( $error ) ) {
780 $msg = array_shift( $error );
786 $errorstr .= Html
::rawElement(
789 wfMessage( $msg, $error )->parse()
793 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
799 * Set the text for the submit button
800 * @param string $t plaintext.
801 * @return HTMLForm $this for chaining calls (since 1.20)
803 function setSubmitText( $t ) {
804 $this->mSubmitText
= $t;
809 * Set the text for the submit button to a message
811 * @param string $msg message key
812 * @return HTMLForm $this for chaining calls (since 1.20)
814 public function setSubmitTextMsg( $msg ) {
815 $this->setSubmitText( $this->msg( $msg )->text() );
820 * Get the text for the submit button, either customised or a default.
823 function getSubmitText() {
824 return $this->mSubmitText
826 : $this->msg( 'htmlform-submit' )->text();
830 * @param string $name Submit button name
831 * @return HTMLForm $this for chaining calls (since 1.20)
833 public function setSubmitName( $name ) {
834 $this->mSubmitName
= $name;
839 * @param string $name Tooltip for the submit button
840 * @return HTMLForm $this for chaining calls (since 1.20)
842 public function setSubmitTooltip( $name ) {
843 $this->mSubmitTooltip
= $name;
848 * Set the id for the submit button.
850 * @todo FIXME: Integrity of $t is *not* validated
851 * @return HTMLForm $this for chaining calls (since 1.20)
853 function setSubmitID( $t ) {
854 $this->mSubmitID
= $t;
859 * Stop a default submit button being shown for this form. This implies that an
860 * alternate submit method must be provided manually.
864 * @param bool $suppressSubmit Set to false to re-enable the button again
866 * @return HTMLForm $this for chaining calls
868 function suppressDefaultSubmit( $suppressSubmit = true ) {
869 $this->mShowSubmit
= !$suppressSubmit;
874 * @param string $id DOM id for the form
875 * @return HTMLForm $this for chaining calls (since 1.20)
877 public function setId( $id ) {
882 * Prompt the whole form to be wrapped in a "<fieldset>", with
883 * this text as its "<legend>" element.
884 * @param string $legend HTML to go inside the "<legend>" element.
886 * @return HTMLForm $this for chaining calls (since 1.20)
888 public function setWrapperLegend( $legend ) {
889 $this->mWrapperLegend
= $legend;
894 * Prompt the whole form to be wrapped in a "<fieldset>", with
895 * this message as its "<legend>" element.
897 * @param string $msg message key
898 * @return HTMLForm $this for chaining calls (since 1.20)
900 public function setWrapperLegendMsg( $msg ) {
901 $this->setWrapperLegend( $this->msg( $msg )->text() );
906 * Set the prefix for various default messages
907 * @todo currently only used for the "<fieldset>" legend on forms
908 * with multiple sections; should be used elsewhere?
910 * @return HTMLForm $this for chaining calls (since 1.20)
912 function setMessagePrefix( $p ) {
913 $this->mMessagePrefix
= $p;
918 * Set the title for form submission
919 * @param $t Title of page the form is on/should be posted to
920 * @return HTMLForm $this for chaining calls (since 1.20)
922 function setTitle( $t ) {
931 function getTitle() {
932 return $this->mTitle
=== false
933 ?
$this->getContext()->getTitle()
938 * Set the method used to submit the form
939 * @param $method String
940 * @return HTMLForm $this for chaining calls (since 1.20)
942 public function setMethod( $method = 'post' ) {
943 $this->mMethod
= $method;
947 public function getMethod() {
948 return $this->mMethod
;
953 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
954 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
955 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
958 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
959 $displayFormat = $this->getDisplayFormat();
962 $subsectionHtml = '';
965 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ?
'getTableRow' : 'get' . ucfirst( $displayFormat );
967 foreach ( $fields as $key => $value ) {
968 if ( $value instanceof HTMLFormField
) {
969 $v = empty( $value->mParams
['nodata'] )
970 ?
$this->mFieldData
[$key]
971 : $value->getDefault();
972 $html .= $value->$getFieldHtmlMethod( $v );
974 $labelValue = trim( $value->getLabel() );
975 if ( $labelValue != ' ' && $labelValue !== '' ) {
978 } elseif ( is_array( $value ) ) {
979 $section = $this->displaySection( $value, $key, "$fieldsetIDPrefix$key-" );
980 $legend = $this->getLegend( $key );
981 if ( isset( $this->mSectionHeaders
[$key] ) ) {
982 $section = $this->mSectionHeaders
[$key] . $section;
984 if ( isset( $this->mSectionFooters
[$key] ) ) {
985 $section .= $this->mSectionFooters
[$key];
987 $attributes = array();
988 if ( $fieldsetIDPrefix ) {
989 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
991 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
995 if ( $displayFormat !== 'raw' ) {
998 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
999 $classes[] = 'mw-htmlform-nolabel';
1003 'class' => implode( ' ', $classes ),
1006 if ( $sectionName ) {
1007 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
1010 if ( $displayFormat === 'table' ) {
1011 $html = Html
::rawElement( 'table', $attribs,
1012 Html
::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1013 } elseif ( $displayFormat === 'div' ) {
1014 $html = Html
::rawElement( 'div', $attribs, "\n$html\n" );
1018 if ( $this->mSubSectionBeforeFields
) {
1019 return $subsectionHtml . "\n" . $html;
1021 return $html . "\n" . $subsectionHtml;
1026 * Construct the form fields from the Descriptor array
1028 function loadData() {
1029 $fieldData = array();
1031 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1032 if ( !empty( $field->mParams
['nodata'] ) ) {
1034 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1035 $fieldData[$fieldname] = $field->getDefault();
1037 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1042 foreach ( $fieldData as $name => &$value ) {
1043 $field = $this->mFlatFields
[$name];
1044 $value = $field->filter( $value, $this->mFlatFields
);
1047 $this->mFieldData
= $fieldData;
1051 * Stop a reset button being shown for this form
1052 * @param bool $suppressReset set to false to re-enable the
1054 * @return HTMLForm $this for chaining calls (since 1.20)
1056 function suppressReset( $suppressReset = true ) {
1057 $this->mShowReset
= !$suppressReset;
1062 * Overload this if you want to apply special filtration routines
1063 * to the form as a whole, after it's submitted but before it's
1068 function filterDataForSubmit( $data ) {
1073 * Get a string to go in the "<legend>" of a section fieldset.
1074 * Override this if you want something more complicated.
1075 * @param $key String
1078 public function getLegend( $key ) {
1079 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1083 * Set the value for the action attribute of the form.
1084 * When set to false (which is the default state), the set title is used.
1088 * @param string|bool $action
1089 * @return HTMLForm $this for chaining calls (since 1.20)
1091 public function setAction( $action ) {
1092 $this->mAction
= $action;
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;
1108 protected $mLabel; # String label. Set on construction
1110 protected $mClass = '';
1111 protected $mDefault;
1119 * This function must be implemented to return the HTML to generate
1120 * the input object itself. It should not implement the surrounding
1121 * table cells/rows, or labels/help messages.
1122 * @param string $value the value to set the input to; eg a default
1123 * text for a text input.
1124 * @return String valid HTML.
1126 abstract function getInputHTML( $value );
1129 * Get a translated interface message
1131 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1132 * and wfMessage() otherwise.
1134 * Parameters are the same as wfMessage().
1136 * @return Message object
1139 $args = func_get_args();
1141 if ( $this->mParent
) {
1142 $callback = array( $this->mParent
, 'msg' );
1144 $callback = 'wfMessage';
1147 return call_user_func_array( $callback, $args );
1151 * Override this function to add specific validation checks on the
1152 * field input. Don't forget to call parent::validate() to ensure
1153 * that the user-defined callback mValidationCallback is still run
1154 * @param string $value the value the field was submitted with
1155 * @param array $alldata the data collected from the form
1156 * @return Mixed Bool true on success, or String error to display.
1158 function validate( $value, $alldata ) {
1159 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value === '' ) {
1160 return $this->msg( 'htmlform-required' )->parse();
1163 if ( isset( $this->mValidationCallback
) ) {
1164 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
1170 function filter( $value, $alldata ) {
1171 if ( isset( $this->mFilterCallback
) ) {
1172 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
1179 * Should this field have a label, or is there no input element with the
1180 * appropriate id for the label to point to?
1182 * @return bool True to output a label, false to suppress
1184 protected function needsLabel() {
1189 * Get the value that this input has been set to from a posted form,
1190 * or the input's default value if it has not been set.
1191 * @param $request WebRequest
1192 * @return String the value
1194 function loadDataFromRequest( $request ) {
1195 if ( $request->getCheck( $this->mName
) ) {
1196 return $request->getText( $this->mName
);
1198 return $this->getDefault();
1203 * Initialise the object
1204 * @param array $params Associative Array. See HTMLForm doc for syntax.
1205 * @throws MWException
1207 function __construct( $params ) {
1208 $this->mParams
= $params;
1210 # Generate the label from a message, if possible
1211 if ( isset( $params['label-message'] ) ) {
1212 $msgInfo = $params['label-message'];
1214 if ( is_array( $msgInfo ) ) {
1215 $msg = array_shift( $msgInfo );
1221 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
1222 } elseif ( isset( $params['label'] ) ) {
1223 $this->mLabel
= $params['label'];
1226 $this->mName
= "wp{$params['fieldname']}";
1227 if ( isset( $params['name'] ) ) {
1228 $this->mName
= $params['name'];
1231 $validName = Sanitizer
::escapeId( $this->mName
);
1232 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
1233 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
1236 $this->mID
= "mw-input-{$this->mName}";
1238 if ( isset( $params['default'] ) ) {
1239 $this->mDefault
= $params['default'];
1242 if ( isset( $params['id'] ) ) {
1243 $id = $params['id'];
1244 $validId = Sanitizer
::escapeId( $id );
1246 if ( $id != $validId ) {
1247 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1253 if ( isset( $params['cssclass'] ) ) {
1254 $this->mClass
= $params['cssclass'];
1257 if ( isset( $params['validation-callback'] ) ) {
1258 $this->mValidationCallback
= $params['validation-callback'];
1261 if ( isset( $params['filter-callback'] ) ) {
1262 $this->mFilterCallback
= $params['filter-callback'];
1265 if ( isset( $params['flatlist'] ) ) {
1266 $this->mClass
.= ' mw-htmlform-flatlist';
1271 * Get the complete table row for the input, including help text,
1272 * labels, and whatever.
1273 * @param string $value the value to set the input to.
1274 * @return String complete HTML table row.
1276 function getTableRow( $value ) {
1277 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1278 $inputHtml = $this->getInputHTML( $value );
1279 $fieldType = get_class( $this );
1280 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1281 $cellAttributes = array();
1283 if ( !empty( $this->mParams
['vertical-label'] ) ) {
1284 $cellAttributes['colspan'] = 2;
1285 $verticalLabel = true;
1287 $verticalLabel = false;
1290 $label = $this->getLabelHtml( $cellAttributes );
1292 $field = Html
::rawElement(
1294 array( 'class' => 'mw-input' ) +
$cellAttributes,
1295 $inputHtml . "\n$errors"
1298 if ( $verticalLabel ) {
1299 $html = Html
::rawElement( 'tr',
1300 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1301 $html .= Html
::rawElement( 'tr',
1302 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1305 $html = Html
::rawElement( 'tr',
1306 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1310 return $html . $helptext;
1314 * Get the complete div for the input, including help text,
1315 * labels, and whatever.
1317 * @param string $value the value to set the input to.
1318 * @return String complete HTML table row.
1320 public function getDiv( $value ) {
1321 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1322 $inputHtml = $this->getInputHTML( $value );
1323 $fieldType = get_class( $this );
1324 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1325 $cellAttributes = array();
1326 $label = $this->getLabelHtml( $cellAttributes );
1328 $field = Html
::rawElement(
1330 array( 'class' => 'mw-input' ) +
$cellAttributes,
1331 $inputHtml . "\n$errors"
1333 $html = Html
::rawElement( 'div',
1334 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1341 * Get the complete raw fields for the input, including help text,
1342 * labels, and whatever.
1344 * @param string $value the value to set the input to.
1345 * @return String complete HTML table row.
1347 public function getRaw( $value ) {
1348 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1349 $inputHtml = $this->getInputHTML( $value );
1350 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1351 $cellAttributes = array();
1352 $label = $this->getLabelHtml( $cellAttributes );
1354 $html = "\n$errors";
1356 $html .= $inputHtml;
1362 * Generate help text HTML in table format
1364 * @param $helptext String|null
1367 public function getHelpTextHtmlTable( $helptext ) {
1368 if ( is_null( $helptext ) ) {
1372 $row = Html
::rawElement(
1374 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1377 $row = Html
::rawElement( 'tr', array(), $row );
1382 * Generate help text HTML in div format
1384 * @param $helptext String|null
1387 public function getHelpTextHtmlDiv( $helptext ) {
1388 if ( is_null( $helptext ) ) {
1392 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1397 * Generate help text HTML formatted for raw output
1399 * @param $helptext String|null
1402 public function getHelpTextHtmlRaw( $helptext ) {
1403 return $this->getHelpTextHtmlDiv( $helptext );
1407 * Determine the help text to display
1411 public function getHelpText() {
1414 if ( isset( $this->mParams
['help-message'] ) ) {
1415 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
1418 if ( isset( $this->mParams
['help-messages'] ) ) {
1419 foreach ( $this->mParams
['help-messages'] as $name ) {
1420 $helpMessage = (array)$name;
1421 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1423 if ( $msg->exists() ) {
1424 if ( is_null( $helptext ) ) {
1427 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1429 $helptext .= $msg->parse(); // Append message
1433 elseif ( isset( $this->mParams
['help'] ) ) {
1434 $helptext = $this->mParams
['help'];
1440 * Determine form errors to display and their classes
1442 * @param string $value the value of the input
1445 public function getErrorsAndErrorClass( $value ) {
1446 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1448 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1452 $errors = self
::formatErrors( $errors );
1453 $errorClass = 'mw-htmlform-invalid-input';
1455 return array( $errors, $errorClass );
1458 function getLabel() {
1459 return $this->mLabel
;
1462 function getLabelHtml( $cellAttributes = array() ) {
1463 # Don't output a for= attribute for labels with no associated input.
1464 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1467 if ( $this->needsLabel() ) {
1468 $for['for'] = $this->mID
;
1471 $displayFormat = $this->mParent
->getDisplayFormat();
1472 $labelElement = Html
::rawElement( 'label', $for, $this->getLabel() );
1474 if ( $displayFormat == 'table' ) {
1475 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1476 Html
::rawElement( 'label', $for, $this->getLabel() )
1478 } elseif ( $displayFormat == 'div' ) {
1479 return Html
::rawElement( 'div', array( 'class' => 'mw-label' ) +
$cellAttributes,
1480 Html
::rawElement( 'label', $for, $this->getLabel() )
1483 return $labelElement;
1487 function getDefault() {
1488 if ( isset( $this->mDefault
) ) {
1489 return $this->mDefault
;
1496 * Returns the attributes required for the tooltip and accesskey.
1498 * @return array Attributes
1500 public function getTooltipAndAccessKey() {
1501 if ( empty( $this->mParams
['tooltip'] ) ) {
1504 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1508 * flatten an array of options to a single array, for instance,
1509 * a set of "<options>" inside "<optgroups>".
1510 * @param array $options Associative Array with values either Strings
1512 * @return Array flattened input
1514 public static function flattenOptions( $options ) {
1515 $flatOpts = array();
1517 foreach ( $options as $value ) {
1518 if ( is_array( $value ) ) {
1519 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1521 $flatOpts[] = $value;
1529 * Formats one or more errors as accepted by field validation-callback.
1530 * @param $errors String|Message|Array of strings or Message instances
1531 * @return String html
1534 protected static function formatErrors( $errors ) {
1535 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1536 $errors = array_shift( $errors );
1539 if ( is_array( $errors ) ) {
1541 foreach ( $errors as $error ) {
1542 if ( $error instanceof Message
) {
1543 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1545 $lines[] = Html
::rawElement( 'li', array(), $error );
1548 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1550 if ( $errors instanceof Message
) {
1551 $errors = $errors->parse();
1553 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1558 class HTMLTextField
extends HTMLFormField
{
1559 function getSize() {
1560 return isset( $this->mParams
['size'] )
1561 ?
$this->mParams
['size']
1565 function getInputHTML( $value ) {
1568 'name' => $this->mName
,
1569 'size' => $this->getSize(),
1571 ) +
$this->getTooltipAndAccessKey();
1573 if ( $this->mClass
!== '' ) {
1574 $attribs['class'] = $this->mClass
;
1577 if ( !empty( $this->mParams
['disabled'] ) ) {
1578 $attribs['disabled'] = 'disabled';
1581 # TODO: Enforce pattern, step, required, readonly on the server side as
1583 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1584 'placeholder', 'list', 'maxlength' );
1585 foreach ( $allowedParams as $param ) {
1586 if ( isset( $this->mParams
[$param] ) ) {
1587 $attribs[$param] = $this->mParams
[$param];
1591 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1592 if ( isset( $this->mParams
[$param] ) ) {
1593 $attribs[$param] = '';
1597 # Implement tiny differences between some field variants
1598 # here, rather than creating a new class for each one which
1599 # is essentially just a clone of this one.
1600 if ( isset( $this->mParams
['type'] ) ) {
1601 switch ( $this->mParams
['type'] ) {
1603 $attribs['type'] = 'email';
1606 $attribs['type'] = 'number';
1609 $attribs['type'] = 'number';
1610 $attribs['step'] = 'any';
1615 $attribs['type'] = $this->mParams
['type'];
1620 return Html
::element( 'input', $attribs );
1623 class HTMLTextAreaField
extends HTMLFormField
{
1624 function getCols() {
1625 return isset( $this->mParams
['cols'] )
1626 ?
$this->mParams
['cols']
1630 function getRows() {
1631 return isset( $this->mParams
['rows'] )
1632 ?
$this->mParams
['rows']
1636 function getInputHTML( $value ) {
1639 'name' => $this->mName
,
1640 'cols' => $this->getCols(),
1641 'rows' => $this->getRows(),
1642 ) +
$this->getTooltipAndAccessKey();
1644 if ( $this->mClass
!== '' ) {
1645 $attribs['class'] = $this->mClass
;
1648 if ( !empty( $this->mParams
['disabled'] ) ) {
1649 $attribs['disabled'] = 'disabled';
1652 if ( !empty( $this->mParams
['readonly'] ) ) {
1653 $attribs['readonly'] = 'readonly';
1656 if ( isset( $this->mParams
['placeholder'] ) ) {
1657 $attribs['placeholder'] = $this->mParams
['placeholder'];
1660 foreach ( array( 'required', 'autofocus' ) as $param ) {
1661 if ( isset( $this->mParams
[$param] ) ) {
1662 $attribs[$param] = '';
1666 return Html
::element( 'textarea', $attribs, $value );
1671 * A field that will contain a numeric value
1673 class HTMLFloatField
extends HTMLTextField
{
1674 function getSize() {
1675 return isset( $this->mParams
['size'] )
1676 ?
$this->mParams
['size']
1680 function validate( $value, $alldata ) {
1681 $p = parent
::validate( $value, $alldata );
1683 if ( $p !== true ) {
1687 $value = trim( $value );
1689 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1690 # with the addition that a leading '+' sign is ok.
1691 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1692 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1695 # The "int" part of these message names is rather confusing.
1696 # They make equal sense for all numbers.
1697 if ( isset( $this->mParams
['min'] ) ) {
1698 $min = $this->mParams
['min'];
1700 if ( $min > $value ) {
1701 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1705 if ( isset( $this->mParams
['max'] ) ) {
1706 $max = $this->mParams
['max'];
1708 if ( $max < $value ) {
1709 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1718 * A field that must contain a number
1720 class HTMLIntField
extends HTMLFloatField
{
1721 function validate( $value, $alldata ) {
1722 $p = parent
::validate( $value, $alldata );
1724 if ( $p !== true ) {
1728 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1729 # with the addition that a leading '+' sign is ok. Note that leading zeros
1730 # are fine, and will be left in the input, which is useful for things like
1731 # phone numbers when you know that they are integers (the HTML5 type=tel
1732 # input does not require its value to be numeric). If you want a tidier
1733 # value to, eg, save in the DB, clean it up with intval().
1734 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1736 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1746 class HTMLCheckField
extends HTMLFormField
{
1747 function getInputHTML( $value ) {
1748 if ( !empty( $this->mParams
['invert'] ) ) {
1752 $attr = $this->getTooltipAndAccessKey();
1753 $attr['id'] = $this->mID
;
1755 if ( !empty( $this->mParams
['disabled'] ) ) {
1756 $attr['disabled'] = 'disabled';
1759 if ( $this->mClass
!== '' ) {
1760 $attr['class'] = $this->mClass
;
1763 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1764 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1768 * For a checkbox, the label goes on the right hand side, and is
1769 * added in getInputHTML(), rather than HTMLFormField::getRow()
1772 function getLabel() {
1777 * @param $request WebRequest
1780 function loadDataFromRequest( $request ) {
1782 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1786 // GetCheck won't work like we want for checks.
1787 // Fetch the value in either one of the two following case:
1788 // - we have a valid token (form got posted or GET forged by the user)
1789 // - checkbox name has a value (false or true), ie is not null
1790 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
) !== null ) {
1791 // XOR has the following truth table, which is what we want
1792 // INVERT VALUE | OUTPUT
1793 // true true | false
1794 // false true | true
1795 // false false | false
1796 // true false | true
1797 return $request->getBool( $this->mName
) xor $invert;
1799 return $this->getDefault();
1806 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1807 * options, uses an array of rows and an array of columns to dynamically
1808 * construct a matrix of options.
1810 class HTMLCheckMatrix
extends HTMLFormField
{
1812 function validate( $value, $alldata ) {
1813 $rows = $this->mParams
['rows'];
1814 $columns = $this->mParams
['columns'];
1816 // Make sure user-defined validation callback is run
1817 $p = parent
::validate( $value, $alldata );
1818 if ( $p !== true ) {
1822 // Make sure submitted value is an array
1823 if ( !is_array( $value ) ) {
1827 // If all options are valid, array_intersect of the valid options
1828 // and the provided options will return the provided options.
1829 $validOptions = array();
1830 foreach ( $rows as $rowTag ) {
1831 foreach ( $columns as $columnTag ) {
1832 $validOptions[] = $columnTag . '-' . $rowTag;
1835 $validValues = array_intersect( $value, $validOptions );
1836 if ( count( $validValues ) == count( $value ) ) {
1839 return $this->msg( 'htmlform-select-badoption' )->parse();
1844 * Build a table containing a matrix of checkbox options.
1845 * The value of each option is a combination of the row tag and column tag.
1846 * mParams['rows'] is an array with row labels as keys and row tags as values.
1847 * mParams['columns'] is an array with column labels as keys and column tags as values.
1848 * @param array $value of the options that should be checked
1851 function getInputHTML( $value ) {
1853 $tableContents = '';
1855 $rows = $this->mParams
['rows'];
1856 $columns = $this->mParams
['columns'];
1858 // If the disabled param is set, disable all the options
1859 if ( !empty( $this->mParams
['disabled'] ) ) {
1860 $attribs['disabled'] = 'disabled';
1863 // Build the column headers
1864 $headerContents = Html
::rawElement( 'td', array(), ' ' );
1865 foreach ( $columns as $columnLabel => $columnTag ) {
1866 $headerContents .= Html
::rawElement( 'td', array(), $columnLabel );
1868 $tableContents .= Html
::rawElement( 'tr', array(), "\n$headerContents\n" );
1870 // Build the options matrix
1871 foreach ( $rows as $rowLabel => $rowTag ) {
1872 $rowContents = Html
::rawElement( 'td', array(), $rowLabel );
1873 foreach ( $columns as $columnTag ) {
1874 // Knock out any options that are not wanted
1875 if ( isset( $this->mParams
['remove-options'] )
1876 && in_array( "$columnTag-$rowTag", $this->mParams
['remove-options'] ) )
1878 $rowContents .= Html
::rawElement( 'td', array(), ' ' );
1880 // Construct the checkbox
1881 $thisAttribs = array(
1882 'id' => "{$this->mID}-$columnTag-$rowTag",
1883 'value' => $columnTag . '-' . $rowTag
1885 $checkbox = Xml
::check(
1886 $this->mName
. '[]',
1887 in_array( $columnTag . '-' . $rowTag, (array)$value, true ),
1888 $attribs +
$thisAttribs );
1889 $rowContents .= Html
::rawElement( 'td', array(), $checkbox );
1892 $tableContents .= Html
::rawElement( 'tr', array(), "\n$rowContents\n" );
1895 // Put it all in a table
1896 $html .= Html
::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
1897 Html
::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
1903 * Get the complete table row for the input, including help text,
1904 * labels, and whatever.
1905 * We override this function since the label should always be on a separate
1906 * line above the options in the case of a checkbox matrix, i.e. it's always
1907 * a "vertical-label".
1908 * @param string $value the value to set the input to
1909 * @return String complete HTML table row
1911 function getTableRow( $value ) {
1912 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1913 $inputHtml = $this->getInputHTML( $value );
1914 $fieldType = get_class( $this );
1915 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1916 $cellAttributes = array( 'colspan' => 2 );
1918 $label = $this->getLabelHtml( $cellAttributes );
1920 $field = Html
::rawElement(
1922 array( 'class' => 'mw-input' ) +
$cellAttributes,
1923 $inputHtml . "\n$errors"
1926 $html = Html
::rawElement( 'tr',
1927 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1928 $html .= Html
::rawElement( 'tr',
1929 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1932 return $html . $helptext;
1936 * @param $request WebRequest
1939 function loadDataFromRequest( $request ) {
1940 if ( $this->mParent
->getMethod() == 'post' ) {
1941 if ( $request->wasPosted() ) {
1942 // Checkboxes are not added to the request arrays if they're not checked,
1943 // so it's perfectly possible for there not to be an entry at all
1944 return $request->getArray( $this->mName
, array() );
1946 // That's ok, the user has not yet submitted the form, so show the defaults
1947 return $this->getDefault();
1950 // This is the impossible case: if we look at $_GET and see no data for our
1951 // field, is it because the user has not yet submitted the form, or that they
1952 // have submitted it with all the options unchecked. We will have to assume the
1953 // latter, which basically means that you can't specify 'positive' defaults
1955 return $request->getArray( $this->mName
, array() );
1959 function getDefault() {
1960 if ( isset( $this->mDefault
) ) {
1961 return $this->mDefault
;
1969 * A select dropdown field. Basically a wrapper for Xmlselect class
1971 class HTMLSelectField
extends HTMLFormField
{
1972 function validate( $value, $alldata ) {
1973 $p = parent
::validate( $value, $alldata );
1975 if ( $p !== true ) {
1979 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1981 if ( in_array( $value, $validOptions ) )
1984 return $this->msg( 'htmlform-select-badoption' )->parse();
1987 function getInputHTML( $value ) {
1988 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1990 # If one of the options' 'name' is int(0), it is automatically selected.
1991 # because PHP sucks and thinks int(0) == 'some string'.
1992 # Working around this by forcing all of them to strings.
1993 foreach ( $this->mParams
['options'] as &$opt ) {
1994 if ( is_int( $opt ) ) {
1995 $opt = strval( $opt );
1998 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2000 if ( !empty( $this->mParams
['disabled'] ) ) {
2001 $select->setAttribute( 'disabled', 'disabled' );
2004 if ( $this->mClass
!== '' ) {
2005 $select->setAttribute( 'class', $this->mClass
);
2008 $select->addOptions( $this->mParams
['options'] );
2010 return $select->getHTML();
2015 * Select dropdown field, with an additional "other" textbox.
2017 class HTMLSelectOrOtherField
extends HTMLTextField
{
2019 function __construct( $params ) {
2020 if ( !in_array( 'other', $params['options'], true ) ) {
2021 $msg = isset( $params['other'] ) ?
2023 wfMessage( 'htmlform-selectorother-other' )->text();
2024 $params['options'][$msg] = 'other';
2027 parent
::__construct( $params );
2030 static function forceToStringRecursive( $array ) {
2031 if ( is_array( $array ) ) {
2032 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
2034 return strval( $array );
2038 function getInputHTML( $value ) {
2039 $valInSelect = false;
2041 if ( $value !== false ) {
2042 $valInSelect = in_array(
2044 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
2048 $selected = $valInSelect ?
$value : 'other';
2050 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
2052 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
2053 $select->addOptions( $opts );
2055 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2057 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
2059 if ( !empty( $this->mParams
['disabled'] ) ) {
2060 $select->setAttribute( 'disabled', 'disabled' );
2061 $tbAttribs['disabled'] = 'disabled';
2064 $select = $select->getHTML();
2066 if ( isset( $this->mParams
['maxlength'] ) ) {
2067 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
2070 if ( $this->mClass
!== '' ) {
2071 $tbAttribs['class'] = $this->mClass
;
2074 $textbox = Html
::input(
2075 $this->mName
. '-other',
2076 $valInSelect ?
'' : $value,
2081 return "$select<br />\n$textbox";
2085 * @param $request WebRequest
2088 function loadDataFromRequest( $request ) {
2089 if ( $request->getCheck( $this->mName
) ) {
2090 $val = $request->getText( $this->mName
);
2092 if ( $val == 'other' ) {
2093 $val = $request->getText( $this->mName
. '-other' );
2098 return $this->getDefault();
2104 * Multi-select field
2106 class HTMLMultiSelectField
extends HTMLFormField
{
2108 function validate( $value, $alldata ) {
2109 $p = parent
::validate( $value, $alldata );
2111 if ( $p !== true ) {
2115 if ( !is_array( $value ) ) {
2119 # If all options are valid, array_intersect of the valid options
2120 # and the provided options will return the provided options.
2121 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2123 $validValues = array_intersect( $value, $validOptions );
2124 if ( count( $validValues ) == count( $value ) ) {
2127 return $this->msg( 'htmlform-select-badoption' )->parse();
2131 function getInputHTML( $value ) {
2132 $html = $this->formatOptions( $this->mParams
['options'], $value );
2137 function formatOptions( $options, $value ) {
2142 if ( !empty( $this->mParams
['disabled'] ) ) {
2143 $attribs['disabled'] = 'disabled';
2146 foreach ( $options as $label => $info ) {
2147 if ( is_array( $info ) ) {
2148 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2149 $html .= $this->formatOptions( $info, $value );
2151 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2153 $checkbox = Xml
::check(
2154 $this->mName
. '[]',
2155 in_array( $info, $value, true ),
2156 $attribs +
$thisAttribs );
2157 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2159 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2167 * @param $request WebRequest
2170 function loadDataFromRequest( $request ) {
2171 if ( $this->mParent
->getMethod() == 'post' ) {
2172 if ( $request->wasPosted() ) {
2173 # Checkboxes are just not added to the request arrays if they're not checked,
2174 # so it's perfectly possible for there not to be an entry at all
2175 return $request->getArray( $this->mName
, array() );
2177 # That's ok, the user has not yet submitted the form, so show the defaults
2178 return $this->getDefault();
2181 # This is the impossible case: if we look at $_GET and see no data for our
2182 # field, is it because the user has not yet submitted the form, or that they
2183 # have submitted it with all the options unchecked? We will have to assume the
2184 # latter, which basically means that you can't specify 'positive' defaults
2187 return $request->getArray( $this->mName
, array() );
2191 function getDefault() {
2192 if ( isset( $this->mDefault
) ) {
2193 return $this->mDefault
;
2199 protected function needsLabel() {
2205 * Double field with a dropdown list constructed from a system message in the format
2208 * * New Optgroup header
2209 * Plus a text field underneath for an additional reason. The 'value' of the field is
2210 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2212 * @todo FIXME: If made 'required', only the text field should be compulsory.
2214 class HTMLSelectAndOtherField
extends HTMLSelectField
{
2216 function __construct( $params ) {
2217 if ( array_key_exists( 'other', $params ) ) {
2218 } elseif ( array_key_exists( 'other-message', $params ) ) {
2219 $params['other'] = wfMessage( $params['other-message'] )->plain();
2221 $params['other'] = null;
2224 if ( array_key_exists( 'options', $params ) ) {
2225 # Options array already specified
2226 } elseif ( array_key_exists( 'options-message', $params ) ) {
2227 # Generate options array from a system message
2228 $params['options'] = self
::parseMessage(
2229 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2234 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2236 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
2238 parent
::__construct( $params );
2242 * Build a drop-down box from a textual list.
2243 * @param string $string message text
2244 * @param string $otherName name of "other reason" option
2246 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2248 public static function parseMessage( $string, $otherName = null ) {
2249 if ( $otherName === null ) {
2250 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2254 $options = array( $otherName => 'other' );
2256 foreach ( explode( "\n", $string ) as $option ) {
2257 $value = trim( $option );
2258 if ( $value == '' ) {
2260 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2261 # A new group is starting...
2262 $value = trim( substr( $value, 1 ) );
2264 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2266 $opt = trim( substr( $value, 2 ) );
2267 if ( $optgroup === false ) {
2268 $options[$opt] = $opt;
2270 $options[$optgroup][$opt] = $opt;
2273 # groupless reason list
2275 $options[$option] = $option;
2282 function getInputHTML( $value ) {
2283 $select = parent
::getInputHTML( $value[1] );
2285 $textAttribs = array(
2286 'id' => $this->mID
. '-other',
2287 'size' => $this->getSize(),
2290 if ( $this->mClass
!== '' ) {
2291 $textAttribs['class'] = $this->mClass
;
2294 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2295 if ( isset( $this->mParams
[$param] ) ) {
2296 $textAttribs[$param] = '';
2300 $textbox = Html
::input(
2301 $this->mName
. '-other',
2307 return "$select<br />\n$textbox";
2311 * @param $request WebRequest
2312 * @return Array("<overall message>","<select value>","<text field value>")
2314 function loadDataFromRequest( $request ) {
2315 if ( $request->getCheck( $this->mName
) ) {
2317 $list = $request->getText( $this->mName
);
2318 $text = $request->getText( $this->mName
. '-other' );
2320 if ( $list == 'other' ) {
2322 } elseif ( !in_array( $list, $this->mFlatOptions
) ) {
2323 # User has spoofed the select form to give an option which wasn't
2324 # in the original offer. Sulk...
2326 } elseif ( $text == '' ) {
2329 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2333 $final = $this->getDefault();
2337 foreach ( $this->mFlatOptions
as $option ) {
2338 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2339 if ( strpos( $text, $match ) === 0 ) {
2341 $text = substr( $text, strlen( $match ) );
2346 return array( $final, $list, $text );
2349 function getSize() {
2350 return isset( $this->mParams
['size'] )
2351 ?
$this->mParams
['size']
2355 function validate( $value, $alldata ) {
2356 # HTMLSelectField forces $value to be one of the options in the select
2357 # field, which is not useful here. But we do want the validation further up
2359 $p = parent
::validate( $value[1], $alldata );
2361 if ( $p !== true ) {
2365 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value[1] === '' ) {
2366 return $this->msg( 'htmlform-required' )->parse();
2374 * Radio checkbox fields.
2376 class HTMLRadioField
extends HTMLFormField
{
2378 function validate( $value, $alldata ) {
2379 $p = parent
::validate( $value, $alldata );
2381 if ( $p !== true ) {
2385 if ( !is_string( $value ) && !is_int( $value ) ) {
2389 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2391 if ( in_array( $value, $validOptions ) ) {
2394 return $this->msg( 'htmlform-select-badoption' )->parse();
2399 * This returns a block of all the radio options, in one cell.
2400 * @see includes/HTMLFormField#getInputHTML()
2401 * @param $value String
2404 function getInputHTML( $value ) {
2405 $html = $this->formatOptions( $this->mParams
['options'], $value );
2410 function formatOptions( $options, $value ) {
2414 if ( !empty( $this->mParams
['disabled'] ) ) {
2415 $attribs['disabled'] = 'disabled';
2418 # TODO: should this produce an unordered list perhaps?
2419 foreach ( $options as $label => $info ) {
2420 if ( is_array( $info ) ) {
2421 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2422 $html .= $this->formatOptions( $info, $value );
2424 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
2425 $radio = Xml
::radio(
2429 $attribs +
array( 'id' => $id )
2431 $radio .= ' ' .
2432 Html
::rawElement( 'label', array( 'for' => $id ), $label );
2434 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2441 protected function needsLabel() {
2447 * An information field (text blob), not a proper input.
2449 class HTMLInfoField
extends HTMLFormField
{
2450 public function __construct( $info ) {
2451 $info['nodata'] = true;
2453 parent
::__construct( $info );
2456 public function getInputHTML( $value ) {
2457 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
2460 public function getTableRow( $value ) {
2461 if ( !empty( $this->mParams
['rawrow'] ) ) {
2465 return parent
::getTableRow( $value );
2471 public function getDiv( $value ) {
2472 if ( !empty( $this->mParams
['rawrow'] ) ) {
2476 return parent
::getDiv( $value );
2482 public function getRaw( $value ) {
2483 if ( !empty( $this->mParams
['rawrow'] ) ) {
2487 return parent
::getRaw( $value );
2490 protected function needsLabel() {
2495 class HTMLHiddenField
extends HTMLFormField
{
2496 public function __construct( $params ) {
2497 parent
::__construct( $params );
2499 # Per HTML5 spec, hidden fields cannot be 'required'
2500 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2501 unset( $this->mParams
['required'] );
2504 public function getTableRow( $value ) {
2507 $params['id'] = $this->mID
;
2510 $this->mParent
->addHiddenField(
2522 public function getDiv( $value ) {
2523 return $this->getTableRow( $value );
2529 public function getRaw( $value ) {
2530 return $this->getTableRow( $value );
2533 public function getInputHTML( $value ) { return ''; }
2537 * Add a submit button inline in the form (as opposed to
2538 * HTMLForm::addButton(), which will add it at the end).
2540 class HTMLSubmitField
extends HTMLFormField
{
2542 public function __construct( $info ) {
2543 $info['nodata'] = true;
2544 parent
::__construct( $info );
2547 public function getInputHTML( $value ) {
2549 'class' => 'mw-htmlform-submit ' . $this->mClass
,
2550 'name' => $this->mName
,
2554 if ( !empty( $this->mParams
['disabled'] ) ) {
2555 $attr['disabled'] = 'disabled';
2558 return Xml
::submitButton( $value, $attr );
2561 protected function needsLabel() {
2566 * Button cannot be invalid
2567 * @param $value String
2568 * @param $alldata Array
2571 public function validate( $value, $alldata ) {
2576 class HTMLEditTools
extends HTMLFormField
{
2577 public function getInputHTML( $value ) {
2581 public function getTableRow( $value ) {
2582 $msg = $this->formatMsg();
2584 return '<tr><td></td><td class="mw-input">'
2585 . '<div class="mw-editTools">'
2586 . $msg->parseAsBlock()
2587 . "</div></td></tr>\n";
2593 public function getDiv( $value ) {
2594 $msg = $this->formatMsg();
2595 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2601 public function getRaw( $value ) {
2602 return $this->getDiv( $value );
2605 protected function formatMsg() {
2606 if ( empty( $this->mParams
['message'] ) ) {
2607 $msg = $this->msg( 'edittools' );
2609 $msg = $this->msg( $this->mParams
['message'] );
2610 if ( $msg->isDisabled() ) {
2611 $msg = $this->msg( 'edittools' );
2614 $msg->inContentLanguage();
2619 class HTMLApiField
extends HTMLFormField
{
2620 public function getTableRow( $value ) {
2624 public function getDiv( $value ) {
2625 return $this->getTableRow( $value );
2628 public function getRaw( $value ) {
2629 return $this->getTableRow( $value );
2632 public function getInputHTML( $value ) {