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' )
87 * ->displayForm( '' );
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;
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 = '';
144 protected $mSubmitID;
145 protected $mSubmitName;
146 protected $mSubmitText;
147 protected $mSubmitTooltip;
150 protected $mMethod = 'post';
153 * Form action URL. false means we will use the URL to set Title
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
172 protected $mSubSectionBeforeFields = true;
175 * Format in which to display form. For viable options,
176 * @see $availableDisplayFormats
179 protected $displayFormat = 'table';
182 * Available formats in which to display the form
185 protected $availableDisplayFormats = array(
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;
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'] )
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;
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
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;
266 * Getter for displayFormat
270 public function getDisplayFormat() {
271 return $this->displayFormat
;
275 * Add the HTMLForm-specific JavaScript, if it hasn't been
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;
301 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
304 $descriptor['fieldname'] = $fieldname;
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 );
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.
336 * Try submitting, with edit token check first
337 * @return Status|boolean
339 function tryAuthorizedSubmit() {
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 );
358 $result = $this->trySubmit();
365 * The here's-one-I-made-earlier option: do the submission if
366 * posted, or display the form with or without funky validation
368 * @return Bool or Status whether submission was successful.
371 $this->prepareForm();
373 $result = $this->tryAuthorizedSubmit();
374 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ) {
378 $this->displayForm( $result );
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
390 function trySubmit() {
391 # Check for validation
392 foreach ( $this->mFlatFields
as $fieldname => $field ) {
393 if ( !empty( $field->mParams
['nodata'] ) ) {
396 if ( $field->validate(
397 $this->mFieldData
[$fieldname],
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 );
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;
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;
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 );
455 * Set the introductory message, overwriting any existing message.
457 * @param string $msg complete text of message to display
458 * @return HTMLForm $this for chaining calls (since 1.20)
460 function setPreText( $msg ) {
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 ) {
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;
485 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
486 $this->mSectionHeaders
[$section] = '';
488 $this->mSectionHeaders
[$section] .= $msg;
494 * Set header text, inside the form.
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;
504 $this->mSectionHeaders
[$section] = $msg;
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;
519 if ( !isset( $this->mSectionFooters
[$section] ) ) {
520 $this->mSectionFooters
[$section] = '';
522 $this->mSectionFooters
[$section] .= $msg;
528 * Set footer text, inside the form.
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;
538 $this->mSectionFooters
[$section] = $msg;
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;
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 ) {
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 );
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' );
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()
609 function getHTML( $submitResult ) {
610 # For good measure (it is the default)
611 $this->getOutput()->preventClickjacking();
612 $this->getOutput()->addModules( 'mediawiki.htmlform' );
615 . $this->getErrors( $submitResult )
618 . $this->getHiddenFields()
619 . $this->getButtons()
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';
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;
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";
683 * Get the submit and (potentially) reset buttons.
684 * @return String HTML.
686 function getButtons() {
689 if ( $this->mShowSubmit
) {
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(
714 'value' => $this->msg( 'htmlform-reset' )->text()
719 foreach ( $this->mButtons
as $button ) {
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 );
741 * Get the whole body of the form.
745 return $this->displaySection( $this->mFieldTree
);
749 * Format and display an error message stack.
750 * @param $errors String|Array|Status
753 function getErrors( $errors ) {
754 if ( $errors instanceof Status
) {
755 if ( $errors->isOK() ) {
758 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
760 } elseif ( is_array( $errors ) ) {
761 $errorstr = $this->formatErrors( $errors );
767 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
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 ) {
779 foreach ( $errors as $error ) {
780 if ( is_array( $error ) ) {
781 $msg = array_shift( $error );
787 $errorstr .= Html
::rawElement(
790 wfMessage( $msg, $error )->parse()
794 $errorstr = Html
::rawElement( 'ul', array(), $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;
810 * Set the text for the submit button to a message
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() );
821 * Get the text for the submit button, either customised or a default.
824 function getSubmitText() {
825 return $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;
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;
849 * Set the id for the submit button.
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;
860 * Stop a default submit button being shown for this form. This implies that an
861 * alternate submit method must be provided manually.
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;
875 * @param string $id DOM id for the form
876 * @return HTMLForm $this for chaining calls (since 1.20)
878 public function setId( $id ) {
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.
887 * @return HTMLForm $this for chaining calls (since 1.20)
889 public function setWrapperLegend( $legend ) {
890 $this->mWrapperLegend
= $legend;
895 * Prompt the whole form to be wrapped in a "<fieldset>", with
896 * this message as its "<legend>" element.
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() );
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?
911 * @return HTMLForm $this for chaining calls (since 1.20)
913 function setMessagePrefix( $p ) {
914 $this->mMessagePrefix
= $p;
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 ) {
932 function getTitle() {
933 return $this->mTitle
=== false
934 ?
$this->getContext()->getTitle()
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;
948 public function getMethod() {
949 return $this->mMethod
;
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
959 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
960 $displayFormat = $this->getDisplayFormat();
963 $subsectionHtml = '';
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 != ' ' && $labelValue !== '' ) {
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' ) {
999 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1000 $classes[] = 'mw-htmlform-nolabel';
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;
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'] ) ) {
1035 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
1036 $fieldData[$fieldname] = $field->getDefault();
1038 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
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
1055 * @return HTMLForm $this for chaining calls (since 1.20)
1057 function suppressReset( $suppressReset = true ) {
1058 $this->mShowReset
= !$suppressReset;
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
1069 function filterDataForSubmit( $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
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.
1089 * @param string|bool $action
1090 * @return HTMLForm $this for chaining calls (since 1.20)
1092 public function setAction( $action ) {
1093 $this->mAction
= $action;
1100 * The parent class to generate form fields. Any field type should
1101 * be a subclass of this.
1103 abstract class HTMLFormField
{
1105 protected $mValidationCallback;
1106 protected $mFilterCallback;
1109 protected $mLabel; # String label. Set on construction
1111 protected $mClass = '';
1112 protected $mDefault;
1120 * This function must be implemented to return the HTML to generate
1121 * the input object itself. It should not implement the surrounding
1122 * table cells/rows, or labels/help messages.
1123 * @param string $value the value to set the input to; eg a default
1124 * text for a text input.
1125 * @return String valid HTML.
1127 abstract function getInputHTML( $value );
1130 * Get a translated interface message
1132 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1133 * and wfMessage() otherwise.
1135 * Parameters are the same as wfMessage().
1137 * @return Message object
1140 $args = func_get_args();
1142 if ( $this->mParent
) {
1143 $callback = array( $this->mParent
, 'msg' );
1145 $callback = 'wfMessage';
1148 return call_user_func_array( $callback, $args );
1152 * Override this function to add specific validation checks on the
1153 * field input. Don't forget to call parent::validate() to ensure
1154 * that the user-defined callback mValidationCallback is still run
1155 * @param string $value the value the field was submitted with
1156 * @param array $alldata the data collected from the form
1157 * @return Mixed Bool true on success, or String error to display.
1159 function validate( $value, $alldata ) {
1160 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value === '' ) {
1161 return $this->msg( 'htmlform-required' )->parse();
1164 if ( isset( $this->mValidationCallback
) ) {
1165 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
1171 function filter( $value, $alldata ) {
1172 if ( isset( $this->mFilterCallback
) ) {
1173 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
1180 * Should this field have a label, or is there no input element with the
1181 * appropriate id for the label to point to?
1183 * @return bool True to output a label, false to suppress
1185 protected function needsLabel() {
1190 * Get the value that this input has been set to from a posted form,
1191 * or the input's default value if it has not been set.
1192 * @param $request WebRequest
1193 * @return String the value
1195 function loadDataFromRequest( $request ) {
1196 if ( $request->getCheck( $this->mName
) ) {
1197 return $request->getText( $this->mName
);
1199 return $this->getDefault();
1204 * Initialise the object
1205 * @param array $params Associative Array. See HTMLForm doc for syntax.
1206 * @throws MWException
1208 function __construct( $params ) {
1209 $this->mParams
= $params;
1211 # Generate the label from a message, if possible
1212 if ( isset( $params['label-message'] ) ) {
1213 $msgInfo = $params['label-message'];
1215 if ( is_array( $msgInfo ) ) {
1216 $msg = array_shift( $msgInfo );
1222 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
1223 } elseif ( isset( $params['label'] ) ) {
1224 $this->mLabel
= $params['label'];
1227 $this->mName
= "wp{$params['fieldname']}";
1228 if ( isset( $params['name'] ) ) {
1229 $this->mName
= $params['name'];
1232 $validName = Sanitizer
::escapeId( $this->mName
);
1233 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
1234 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
1237 $this->mID
= "mw-input-{$this->mName}";
1239 if ( isset( $params['default'] ) ) {
1240 $this->mDefault
= $params['default'];
1243 if ( isset( $params['id'] ) ) {
1244 $id = $params['id'];
1245 $validId = Sanitizer
::escapeId( $id );
1247 if ( $id != $validId ) {
1248 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
1254 if ( isset( $params['cssclass'] ) ) {
1255 $this->mClass
= $params['cssclass'];
1258 if ( isset( $params['validation-callback'] ) ) {
1259 $this->mValidationCallback
= $params['validation-callback'];
1262 if ( isset( $params['filter-callback'] ) ) {
1263 $this->mFilterCallback
= $params['filter-callback'];
1266 if ( isset( $params['flatlist'] ) ) {
1267 $this->mClass
.= ' mw-htmlform-flatlist';
1272 * Get the complete table row for the input, including help text,
1273 * labels, and whatever.
1274 * @param string $value the value to set the input to.
1275 * @return String complete HTML table row.
1277 function getTableRow( $value ) {
1278 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1279 $inputHtml = $this->getInputHTML( $value );
1280 $fieldType = get_class( $this );
1281 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1282 $cellAttributes = array();
1284 if ( !empty( $this->mParams
['vertical-label'] ) ) {
1285 $cellAttributes['colspan'] = 2;
1286 $verticalLabel = true;
1288 $verticalLabel = false;
1291 $label = $this->getLabelHtml( $cellAttributes );
1293 $field = Html
::rawElement(
1295 array( 'class' => 'mw-input' ) +
$cellAttributes,
1296 $inputHtml . "\n$errors"
1299 if ( $verticalLabel ) {
1300 $html = Html
::rawElement( 'tr',
1301 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1302 $html .= Html
::rawElement( 'tr',
1303 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1306 $html = Html
::rawElement( 'tr',
1307 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1311 return $html . $helptext;
1315 * Get the complete div for the input, including help text,
1316 * labels, and whatever.
1318 * @param string $value the value to set the input to.
1319 * @return String complete HTML table row.
1321 public function getDiv( $value ) {
1322 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1323 $inputHtml = $this->getInputHTML( $value );
1324 $fieldType = get_class( $this );
1325 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1326 $cellAttributes = array();
1327 $label = $this->getLabelHtml( $cellAttributes );
1329 $field = Html
::rawElement(
1331 array( 'class' => 'mw-input' ) +
$cellAttributes,
1332 $inputHtml . "\n$errors"
1334 $html = Html
::rawElement( 'div',
1335 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1342 * Get the complete raw fields for the input, including help text,
1343 * labels, and whatever.
1345 * @param string $value the value to set the input to.
1346 * @return String complete HTML table row.
1348 public function getRaw( $value ) {
1349 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1350 $inputHtml = $this->getInputHTML( $value );
1351 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1352 $cellAttributes = array();
1353 $label = $this->getLabelHtml( $cellAttributes );
1355 $html = "\n$errors";
1357 $html .= $inputHtml;
1363 * Generate help text HTML in table format
1365 * @param $helptext String|null
1368 public function getHelpTextHtmlTable( $helptext ) {
1369 if ( is_null( $helptext ) ) {
1373 $row = Html
::rawElement(
1375 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1378 $row = Html
::rawElement( 'tr', array(), $row );
1383 * Generate help text HTML in div format
1385 * @param $helptext String|null
1388 public function getHelpTextHtmlDiv( $helptext ) {
1389 if ( is_null( $helptext ) ) {
1393 $div = Html
::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1398 * Generate help text HTML formatted for raw output
1400 * @param $helptext String|null
1403 public function getHelpTextHtmlRaw( $helptext ) {
1404 return $this->getHelpTextHtmlDiv( $helptext );
1408 * Determine the help text to display
1412 public function getHelpText() {
1415 if ( isset( $this->mParams
['help-message'] ) ) {
1416 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
1419 if ( isset( $this->mParams
['help-messages'] ) ) {
1420 foreach ( $this->mParams
['help-messages'] as $name ) {
1421 $helpMessage = (array)$name;
1422 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1424 if ( $msg->exists() ) {
1425 if ( is_null( $helptext ) ) {
1428 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1430 $helptext .= $msg->parse(); // Append message
1434 elseif ( isset( $this->mParams
['help'] ) ) {
1435 $helptext = $this->mParams
['help'];
1441 * Determine form errors to display and their classes
1443 * @param string $value the value of the input
1446 public function getErrorsAndErrorClass( $value ) {
1447 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
1449 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
1453 $errors = self
::formatErrors( $errors );
1454 $errorClass = 'mw-htmlform-invalid-input';
1456 return array( $errors, $errorClass );
1459 function getLabel() {
1460 return $this->mLabel
;
1463 function getLabelHtml( $cellAttributes = array() ) {
1464 # Don't output a for= attribute for labels with no associated input.
1465 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1468 if ( $this->needsLabel() ) {
1469 $for['for'] = $this->mID
;
1472 $displayFormat = $this->mParent
->getDisplayFormat();
1473 $labelElement = Html
::rawElement( 'label', $for, $this->getLabel() );
1475 if ( $displayFormat == 'table' ) {
1476 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1477 Html
::rawElement( 'label', $for, $this->getLabel() )
1479 } elseif ( $displayFormat == 'div' ) {
1480 return Html
::rawElement( 'div', array( 'class' => 'mw-label' ) +
$cellAttributes,
1481 Html
::rawElement( 'label', $for, $this->getLabel() )
1484 return $labelElement;
1488 function getDefault() {
1489 if ( isset( $this->mDefault
) ) {
1490 return $this->mDefault
;
1497 * Returns the attributes required for the tooltip and accesskey.
1499 * @return array Attributes
1501 public function getTooltipAndAccessKey() {
1502 if ( empty( $this->mParams
['tooltip'] ) ) {
1505 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1509 * flatten an array of options to a single array, for instance,
1510 * a set of "<options>" inside "<optgroups>".
1511 * @param array $options Associative Array with values either Strings
1513 * @return Array flattened input
1515 public static function flattenOptions( $options ) {
1516 $flatOpts = array();
1518 foreach ( $options as $value ) {
1519 if ( is_array( $value ) ) {
1520 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1522 $flatOpts[] = $value;
1530 * Formats one or more errors as accepted by field validation-callback.
1531 * @param $errors String|Message|Array of strings or Message instances
1532 * @return String html
1535 protected static function formatErrors( $errors ) {
1536 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1537 $errors = array_shift( $errors );
1540 if ( is_array( $errors ) ) {
1542 foreach ( $errors as $error ) {
1543 if ( $error instanceof Message
) {
1544 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1546 $lines[] = Html
::rawElement( 'li', array(), $error );
1549 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1551 if ( $errors instanceof Message
) {
1552 $errors = $errors->parse();
1554 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1559 class HTMLTextField
extends HTMLFormField
{
1560 function getSize() {
1561 return isset( $this->mParams
['size'] )
1562 ?
$this->mParams
['size']
1566 function getInputHTML( $value ) {
1569 'name' => $this->mName
,
1570 'size' => $this->getSize(),
1572 ) +
$this->getTooltipAndAccessKey();
1574 if ( $this->mClass
!== '' ) {
1575 $attribs['class'] = $this->mClass
;
1578 if ( !empty( $this->mParams
['disabled'] ) ) {
1579 $attribs['disabled'] = 'disabled';
1582 # TODO: Enforce pattern, step, required, readonly on the server side as
1584 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1585 'placeholder', 'list', 'maxlength' );
1586 foreach ( $allowedParams as $param ) {
1587 if ( isset( $this->mParams
[$param] ) ) {
1588 $attribs[$param] = $this->mParams
[$param];
1592 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1593 if ( isset( $this->mParams
[$param] ) ) {
1594 $attribs[$param] = '';
1598 # Implement tiny differences between some field variants
1599 # here, rather than creating a new class for each one which
1600 # is essentially just a clone of this one.
1601 if ( isset( $this->mParams
['type'] ) ) {
1602 switch ( $this->mParams
['type'] ) {
1604 $attribs['type'] = 'email';
1607 $attribs['type'] = 'number';
1610 $attribs['type'] = 'number';
1611 $attribs['step'] = 'any';
1616 $attribs['type'] = $this->mParams
['type'];
1621 return Html
::element( 'input', $attribs );
1624 class HTMLTextAreaField
extends HTMLFormField
{
1625 function getCols() {
1626 return isset( $this->mParams
['cols'] )
1627 ?
$this->mParams
['cols']
1631 function getRows() {
1632 return isset( $this->mParams
['rows'] )
1633 ?
$this->mParams
['rows']
1637 function getInputHTML( $value ) {
1640 'name' => $this->mName
,
1641 'cols' => $this->getCols(),
1642 'rows' => $this->getRows(),
1643 ) +
$this->getTooltipAndAccessKey();
1645 if ( $this->mClass
!== '' ) {
1646 $attribs['class'] = $this->mClass
;
1649 if ( !empty( $this->mParams
['disabled'] ) ) {
1650 $attribs['disabled'] = 'disabled';
1653 if ( !empty( $this->mParams
['readonly'] ) ) {
1654 $attribs['readonly'] = 'readonly';
1657 if ( isset( $this->mParams
['placeholder'] ) ) {
1658 $attribs['placeholder'] = $this->mParams
['placeholder'];
1661 foreach ( array( 'required', 'autofocus' ) as $param ) {
1662 if ( isset( $this->mParams
[$param] ) ) {
1663 $attribs[$param] = '';
1667 return Html
::element( 'textarea', $attribs, $value );
1672 * A field that will contain a numeric value
1674 class HTMLFloatField
extends HTMLTextField
{
1675 function getSize() {
1676 return isset( $this->mParams
['size'] )
1677 ?
$this->mParams
['size']
1681 function validate( $value, $alldata ) {
1682 $p = parent
::validate( $value, $alldata );
1684 if ( $p !== true ) {
1688 $value = trim( $value );
1690 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1691 # with the addition that a leading '+' sign is ok.
1692 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1693 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1696 # The "int" part of these message names is rather confusing.
1697 # They make equal sense for all numbers.
1698 if ( isset( $this->mParams
['min'] ) ) {
1699 $min = $this->mParams
['min'];
1701 if ( $min > $value ) {
1702 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1706 if ( isset( $this->mParams
['max'] ) ) {
1707 $max = $this->mParams
['max'];
1709 if ( $max < $value ) {
1710 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1719 * A field that must contain a number
1721 class HTMLIntField
extends HTMLFloatField
{
1722 function validate( $value, $alldata ) {
1723 $p = parent
::validate( $value, $alldata );
1725 if ( $p !== true ) {
1729 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1730 # with the addition that a leading '+' sign is ok. Note that leading zeros
1731 # are fine, and will be left in the input, which is useful for things like
1732 # phone numbers when you know that they are integers (the HTML5 type=tel
1733 # input does not require its value to be numeric). If you want a tidier
1734 # value to, eg, save in the DB, clean it up with intval().
1735 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1737 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1747 class HTMLCheckField
extends HTMLFormField
{
1748 function getInputHTML( $value ) {
1749 if ( !empty( $this->mParams
['invert'] ) ) {
1753 $attr = $this->getTooltipAndAccessKey();
1754 $attr['id'] = $this->mID
;
1756 if ( !empty( $this->mParams
['disabled'] ) ) {
1757 $attr['disabled'] = 'disabled';
1760 if ( $this->mClass
!== '' ) {
1761 $attr['class'] = $this->mClass
;
1764 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1765 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1769 * For a checkbox, the label goes on the right hand side, and is
1770 * added in getInputHTML(), rather than HTMLFormField::getRow()
1773 function getLabel() {
1778 * @param $request WebRequest
1781 function loadDataFromRequest( $request ) {
1783 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1787 // GetCheck won't work like we want for checks.
1788 // Fetch the value in either one of the two following case:
1789 // - we have a valid token (form got posted or GET forged by the user)
1790 // - checkbox name has a value (false or true), ie is not null
1791 if ( $request->getCheck( 'wpEditToken' ) ||
$request->getVal( $this->mName
) !== null ) {
1792 // XOR has the following truth table, which is what we want
1793 // INVERT VALUE | OUTPUT
1794 // true true | false
1795 // false true | true
1796 // false false | false
1797 // true false | true
1798 return $request->getBool( $this->mName
) xor $invert;
1800 return $this->getDefault();
1807 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1808 * options, uses an array of rows and an array of columns to dynamically
1809 * construct a matrix of options.
1811 class HTMLCheckMatrix
extends HTMLFormField
{
1813 function validate( $value, $alldata ) {
1814 $rows = $this->mParams
['rows'];
1815 $columns = $this->mParams
['columns'];
1817 // Make sure user-defined validation callback is run
1818 $p = parent
::validate( $value, $alldata );
1819 if ( $p !== true ) {
1823 // Make sure submitted value is an array
1824 if ( !is_array( $value ) ) {
1828 // If all options are valid, array_intersect of the valid options
1829 // and the provided options will return the provided options.
1830 $validOptions = array();
1831 foreach ( $rows as $rowTag ) {
1832 foreach ( $columns as $columnTag ) {
1833 $validOptions[] = $columnTag . '-' . $rowTag;
1836 $validValues = array_intersect( $value, $validOptions );
1837 if ( count( $validValues ) == count( $value ) ) {
1840 return $this->msg( 'htmlform-select-badoption' )->parse();
1845 * Build a table containing a matrix of checkbox options.
1846 * The value of each option is a combination of the row tag and column tag.
1847 * mParams['rows'] is an array with row labels as keys and row tags as values.
1848 * mParams['columns'] is an array with column labels as keys and column tags as values.
1849 * @param array $value of the options that should be checked
1852 function getInputHTML( $value ) {
1854 $tableContents = '';
1856 $rows = $this->mParams
['rows'];
1857 $columns = $this->mParams
['columns'];
1859 // If the disabled param is set, disable all the options
1860 if ( !empty( $this->mParams
['disabled'] ) ) {
1861 $attribs['disabled'] = 'disabled';
1864 // Build the column headers
1865 $headerContents = Html
::rawElement( 'td', array(), ' ' );
1866 foreach ( $columns as $columnLabel => $columnTag ) {
1867 $headerContents .= Html
::rawElement( 'td', array(), $columnLabel );
1869 $tableContents .= Html
::rawElement( 'tr', array(), "\n$headerContents\n" );
1871 // Build the options matrix
1872 foreach ( $rows as $rowLabel => $rowTag ) {
1873 $rowContents = Html
::rawElement( 'td', array(), $rowLabel );
1874 foreach ( $columns as $columnTag ) {
1875 // Knock out any options that are not wanted
1876 if ( isset( $this->mParams
['remove-options'] )
1877 && in_array( "$columnTag-$rowTag", $this->mParams
['remove-options'] ) )
1879 $rowContents .= Html
::rawElement( 'td', array(), ' ' );
1881 // Construct the checkbox
1882 $thisAttribs = array(
1883 'id' => "{$this->mID}-$columnTag-$rowTag",
1884 'value' => $columnTag . '-' . $rowTag
1886 $checkbox = Xml
::check(
1887 $this->mName
. '[]',
1888 in_array( $columnTag . '-' . $rowTag, (array)$value, true ),
1889 $attribs +
$thisAttribs );
1890 $rowContents .= Html
::rawElement( 'td', array(), $checkbox );
1893 $tableContents .= Html
::rawElement( 'tr', array(), "\n$rowContents\n" );
1896 // Put it all in a table
1897 $html .= Html
::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
1898 Html
::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
1904 * Get the complete table row for the input, including help text,
1905 * labels, and whatever.
1906 * We override this function since the label should always be on a separate
1907 * line above the options in the case of a checkbox matrix, i.e. it's always
1908 * a "vertical-label".
1909 * @param string $value the value to set the input to
1910 * @return String complete HTML table row
1912 function getTableRow( $value ) {
1913 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1914 $inputHtml = $this->getInputHTML( $value );
1915 $fieldType = get_class( $this );
1916 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1917 $cellAttributes = array( 'colspan' => 2 );
1919 $label = $this->getLabelHtml( $cellAttributes );
1921 $field = Html
::rawElement(
1923 array( 'class' => 'mw-input' ) +
$cellAttributes,
1924 $inputHtml . "\n$errors"
1927 $html = Html
::rawElement( 'tr',
1928 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1929 $html .= Html
::rawElement( 'tr',
1930 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1933 return $html . $helptext;
1937 * @param $request WebRequest
1940 function loadDataFromRequest( $request ) {
1941 if ( $this->mParent
->getMethod() == 'post' ) {
1942 if ( $request->wasPosted() ) {
1943 // Checkboxes are not added to the request arrays if they're not checked,
1944 // so it's perfectly possible for there not to be an entry at all
1945 return $request->getArray( $this->mName
, array() );
1947 // That's ok, the user has not yet submitted the form, so show the defaults
1948 return $this->getDefault();
1951 // This is the impossible case: if we look at $_GET and see no data for our
1952 // field, is it because the user has not yet submitted the form, or that they
1953 // have submitted it with all the options unchecked. We will have to assume the
1954 // latter, which basically means that you can't specify 'positive' defaults
1956 return $request->getArray( $this->mName
, array() );
1960 function getDefault() {
1961 if ( isset( $this->mDefault
) ) {
1962 return $this->mDefault
;
1970 * A select dropdown field. Basically a wrapper for Xmlselect class
1972 class HTMLSelectField
extends HTMLFormField
{
1973 function validate( $value, $alldata ) {
1974 $p = parent
::validate( $value, $alldata );
1976 if ( $p !== true ) {
1980 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1982 if ( in_array( $value, $validOptions ) ) {
1985 return $this->msg( 'htmlform-select-badoption' )->parse();
1989 function getInputHTML( $value ) {
1990 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1992 # If one of the options' 'name' is int(0), it is automatically selected.
1993 # because PHP sucks and thinks int(0) == 'some string'.
1994 # Working around this by forcing all of them to strings.
1995 foreach ( $this->mParams
['options'] as &$opt ) {
1996 if ( is_int( $opt ) ) {
1997 $opt = strval( $opt );
2000 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2002 if ( !empty( $this->mParams
['disabled'] ) ) {
2003 $select->setAttribute( 'disabled', 'disabled' );
2006 if ( $this->mClass
!== '' ) {
2007 $select->setAttribute( 'class', $this->mClass
);
2010 $select->addOptions( $this->mParams
['options'] );
2012 return $select->getHTML();
2017 * Select dropdown field, with an additional "other" textbox.
2019 class HTMLSelectOrOtherField
extends HTMLTextField
{
2021 function __construct( $params ) {
2022 if ( !in_array( 'other', $params['options'], true ) ) {
2023 $msg = isset( $params['other'] ) ?
2025 wfMessage( 'htmlform-selectorother-other' )->text();
2026 $params['options'][$msg] = 'other';
2029 parent
::__construct( $params );
2032 static function forceToStringRecursive( $array ) {
2033 if ( is_array( $array ) ) {
2034 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
2036 return strval( $array );
2040 function getInputHTML( $value ) {
2041 $valInSelect = false;
2043 if ( $value !== false ) {
2044 $valInSelect = in_array(
2046 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
2050 $selected = $valInSelect ?
$value : 'other';
2052 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
2054 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
2055 $select->addOptions( $opts );
2057 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2059 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
2061 if ( !empty( $this->mParams
['disabled'] ) ) {
2062 $select->setAttribute( 'disabled', 'disabled' );
2063 $tbAttribs['disabled'] = 'disabled';
2066 $select = $select->getHTML();
2068 if ( isset( $this->mParams
['maxlength'] ) ) {
2069 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
2072 if ( $this->mClass
!== '' ) {
2073 $tbAttribs['class'] = $this->mClass
;
2076 $textbox = Html
::input(
2077 $this->mName
. '-other',
2078 $valInSelect ?
'' : $value,
2083 return "$select<br />\n$textbox";
2087 * @param $request WebRequest
2090 function loadDataFromRequest( $request ) {
2091 if ( $request->getCheck( $this->mName
) ) {
2092 $val = $request->getText( $this->mName
);
2094 if ( $val == 'other' ) {
2095 $val = $request->getText( $this->mName
. '-other' );
2100 return $this->getDefault();
2106 * Multi-select field
2108 class HTMLMultiSelectField
extends HTMLFormField
{
2110 function validate( $value, $alldata ) {
2111 $p = parent
::validate( $value, $alldata );
2113 if ( $p !== true ) {
2117 if ( !is_array( $value ) ) {
2121 # If all options are valid, array_intersect of the valid options
2122 # and the provided options will return the provided options.
2123 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2125 $validValues = array_intersect( $value, $validOptions );
2126 if ( count( $validValues ) == count( $value ) ) {
2129 return $this->msg( 'htmlform-select-badoption' )->parse();
2133 function getInputHTML( $value ) {
2134 $html = $this->formatOptions( $this->mParams
['options'], $value );
2139 function formatOptions( $options, $value ) {
2144 if ( !empty( $this->mParams
['disabled'] ) ) {
2145 $attribs['disabled'] = 'disabled';
2148 foreach ( $options as $label => $info ) {
2149 if ( is_array( $info ) ) {
2150 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2151 $html .= $this->formatOptions( $info, $value );
2153 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2155 $checkbox = Xml
::check(
2156 $this->mName
. '[]',
2157 in_array( $info, $value, true ),
2158 $attribs +
$thisAttribs );
2159 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2161 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2169 * @param $request WebRequest
2172 function loadDataFromRequest( $request ) {
2173 if ( $this->mParent
->getMethod() == 'post' ) {
2174 if ( $request->wasPosted() ) {
2175 # Checkboxes are just not added to the request arrays if they're not checked,
2176 # so it's perfectly possible for there not to be an entry at all
2177 return $request->getArray( $this->mName
, array() );
2179 # That's ok, the user has not yet submitted the form, so show the defaults
2180 return $this->getDefault();
2183 # This is the impossible case: if we look at $_GET and see no data for our
2184 # field, is it because the user has not yet submitted the form, or that they
2185 # have submitted it with all the options unchecked? We will have to assume the
2186 # latter, which basically means that you can't specify 'positive' defaults
2189 return $request->getArray( $this->mName
, array() );
2193 function getDefault() {
2194 if ( isset( $this->mDefault
) ) {
2195 return $this->mDefault
;
2201 protected function needsLabel() {
2207 * Double field with a dropdown list constructed from a system message in the format
2210 * * New Optgroup header
2211 * Plus a text field underneath for an additional reason. The 'value' of the field is
2212 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2214 * @todo FIXME: If made 'required', only the text field should be compulsory.
2216 class HTMLSelectAndOtherField
extends HTMLSelectField
{
2218 function __construct( $params ) {
2219 if ( array_key_exists( 'other', $params ) ) {
2220 } elseif ( array_key_exists( 'other-message', $params ) ) {
2221 $params['other'] = wfMessage( $params['other-message'] )->plain();
2223 $params['other'] = null;
2226 if ( array_key_exists( 'options', $params ) ) {
2227 # Options array already specified
2228 } elseif ( array_key_exists( 'options-message', $params ) ) {
2229 # Generate options array from a system message
2230 $params['options'] = self
::parseMessage(
2231 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2236 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2238 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
2240 parent
::__construct( $params );
2244 * Build a drop-down box from a textual list.
2245 * @param string $string message text
2246 * @param string $otherName name of "other reason" option
2248 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2250 public static function parseMessage( $string, $otherName = null ) {
2251 if ( $otherName === null ) {
2252 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2256 $options = array( $otherName => 'other' );
2258 foreach ( explode( "\n", $string ) as $option ) {
2259 $value = trim( $option );
2260 if ( $value == '' ) {
2262 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2263 # A new group is starting...
2264 $value = trim( substr( $value, 1 ) );
2266 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2268 $opt = trim( substr( $value, 2 ) );
2269 if ( $optgroup === false ) {
2270 $options[$opt] = $opt;
2272 $options[$optgroup][$opt] = $opt;
2275 # groupless reason list
2277 $options[$option] = $option;
2284 function getInputHTML( $value ) {
2285 $select = parent
::getInputHTML( $value[1] );
2287 $textAttribs = array(
2288 'id' => $this->mID
. '-other',
2289 'size' => $this->getSize(),
2292 if ( $this->mClass
!== '' ) {
2293 $textAttribs['class'] = $this->mClass
;
2296 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2297 if ( isset( $this->mParams
[$param] ) ) {
2298 $textAttribs[$param] = '';
2302 $textbox = Html
::input(
2303 $this->mName
. '-other',
2309 return "$select<br />\n$textbox";
2313 * @param $request WebRequest
2314 * @return Array("<overall message>","<select value>","<text field value>")
2316 function loadDataFromRequest( $request ) {
2317 if ( $request->getCheck( $this->mName
) ) {
2319 $list = $request->getText( $this->mName
);
2320 $text = $request->getText( $this->mName
. '-other' );
2322 if ( $list == 'other' ) {
2324 } elseif ( !in_array( $list, $this->mFlatOptions
) ) {
2325 # User has spoofed the select form to give an option which wasn't
2326 # in the original offer. Sulk...
2328 } elseif ( $text == '' ) {
2331 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2335 $final = $this->getDefault();
2339 foreach ( $this->mFlatOptions
as $option ) {
2340 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2341 if ( strpos( $text, $match ) === 0 ) {
2343 $text = substr( $text, strlen( $match ) );
2348 return array( $final, $list, $text );
2351 function getSize() {
2352 return isset( $this->mParams
['size'] )
2353 ?
$this->mParams
['size']
2357 function validate( $value, $alldata ) {
2358 # HTMLSelectField forces $value to be one of the options in the select
2359 # field, which is not useful here. But we do want the validation further up
2361 $p = parent
::validate( $value[1], $alldata );
2363 if ( $p !== true ) {
2367 if ( isset( $this->mParams
['required'] ) && $this->mParams
['required'] !== false && $value[1] === '' ) {
2368 return $this->msg( 'htmlform-required' )->parse();
2376 * Radio checkbox fields.
2378 class HTMLRadioField
extends HTMLFormField
{
2380 function validate( $value, $alldata ) {
2381 $p = parent
::validate( $value, $alldata );
2383 if ( $p !== true ) {
2387 if ( !is_string( $value ) && !is_int( $value ) ) {
2391 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
2393 if ( in_array( $value, $validOptions ) ) {
2396 return $this->msg( 'htmlform-select-badoption' )->parse();
2401 * This returns a block of all the radio options, in one cell.
2402 * @see includes/HTMLFormField#getInputHTML()
2403 * @param $value String
2406 function getInputHTML( $value ) {
2407 $html = $this->formatOptions( $this->mParams
['options'], $value );
2412 function formatOptions( $options, $value ) {
2416 if ( !empty( $this->mParams
['disabled'] ) ) {
2417 $attribs['disabled'] = 'disabled';
2420 # TODO: should this produce an unordered list perhaps?
2421 foreach ( $options as $label => $info ) {
2422 if ( is_array( $info ) ) {
2423 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
2424 $html .= $this->formatOptions( $info, $value );
2426 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
2427 $radio = Xml
::radio(
2431 $attribs +
array( 'id' => $id )
2433 $radio .= ' ' .
2434 Html
::rawElement( 'label', array( 'for' => $id ), $label );
2436 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2443 protected function needsLabel() {
2449 * An information field (text blob), not a proper input.
2451 class HTMLInfoField
extends HTMLFormField
{
2452 public function __construct( $info ) {
2453 $info['nodata'] = true;
2455 parent
::__construct( $info );
2458 public function getInputHTML( $value ) {
2459 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
2462 public function getTableRow( $value ) {
2463 if ( !empty( $this->mParams
['rawrow'] ) ) {
2467 return parent
::getTableRow( $value );
2473 public function getDiv( $value ) {
2474 if ( !empty( $this->mParams
['rawrow'] ) ) {
2478 return parent
::getDiv( $value );
2484 public function getRaw( $value ) {
2485 if ( !empty( $this->mParams
['rawrow'] ) ) {
2489 return parent
::getRaw( $value );
2492 protected function needsLabel() {
2497 class HTMLHiddenField
extends HTMLFormField
{
2498 public function __construct( $params ) {
2499 parent
::__construct( $params );
2501 # Per HTML5 spec, hidden fields cannot be 'required'
2502 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2503 unset( $this->mParams
['required'] );
2506 public function getTableRow( $value ) {
2509 $params['id'] = $this->mID
;
2512 $this->mParent
->addHiddenField(
2524 public function getDiv( $value ) {
2525 return $this->getTableRow( $value );
2531 public function getRaw( $value ) {
2532 return $this->getTableRow( $value );
2535 public function getInputHTML( $value ) {
2541 * Add a submit button inline in the form (as opposed to
2542 * HTMLForm::addButton(), which will add it at the end).
2544 class HTMLSubmitField
extends HTMLButtonField
{
2545 protected $buttonType = 'submit';
2549 * Adds a generic button inline to the form. Does not do anything, you must add
2550 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2551 * wish to add a submit button to a form.
2555 class HTMLButtonField
extends HTMLFormField
{
2556 protected $buttonType = 'button';
2558 public function __construct( $info ) {
2559 $info['nodata'] = true;
2560 parent
::__construct( $info );
2563 public function getInputHTML( $value ) {
2565 'class' => 'mw-htmlform-submit ' . $this->mClass
,
2569 if ( !empty( $this->mParams
['disabled'] ) ) {
2570 $attr['disabled'] = 'disabled';
2581 protected function needsLabel() {
2586 * Button cannot be invalid
2587 * @param $value String
2588 * @param $alldata Array
2591 public function validate( $value, $alldata ) {
2596 class HTMLEditTools
extends HTMLFormField
{
2597 public function getInputHTML( $value ) {
2601 public function getTableRow( $value ) {
2602 $msg = $this->formatMsg();
2604 return '<tr><td></td><td class="mw-input">'
2605 . '<div class="mw-editTools">'
2606 . $msg->parseAsBlock()
2607 . "</div></td></tr>\n";
2613 public function getDiv( $value ) {
2614 $msg = $this->formatMsg();
2615 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2621 public function getRaw( $value ) {
2622 return $this->getDiv( $value );
2625 protected function formatMsg() {
2626 if ( empty( $this->mParams
['message'] ) ) {
2627 $msg = $this->msg( 'edittools' );
2629 $msg = $this->msg( $this->mParams
['message'] );
2630 if ( $msg->isDisabled() ) {
2631 $msg = $this->msg( 'edittools' );
2634 $msg->inContentLanguage();
2639 class HTMLApiField
extends HTMLFormField
{
2640 public function getTableRow( $value ) {
2644 public function getDiv( $value ) {
2645 return $this->getTableRow( $value );
2648 public function getRaw( $value ) {
2649 return $this->getTableRow( $value );
2652 public function getInputHTML( $value ) {