3 * Object handling generic submission, CSRF protection, layout and
4 * other logic for UI forms. in a reusable manner.
6 * In order to generate the form, the HTMLForm object takes an array
7 * structure detailing the form fields available. Each element of the
8 * array is a basic property-list, including the type of field, the
9 * label it is to be given in the form, callbacks for validation and
10 * 'filtering', and other pertinent information.
12 * Field types are implemented as subclasses of the generic HTMLFormField
13 * object, and typically implement at least getInputHTML, which generates
14 * the HTML for the input field to be placed in the table.
16 * The constructor input is an associative array of $fieldname => $info,
17 * where $info is an Associative Array with any of the following:
19 * 'class' -- the subclass of HTMLFormField that will be used
20 * to create the object. *NOT* the CSS class!
21 * 'type' -- roughly translates into the <select> type attribute.
22 * if 'class' is not specified, this is used as a map
23 * through HTMLForm::$typeMappings to get the class name.
24 * 'default' -- default value when the form is displayed
25 * 'id' -- HTML id attribute
26 * 'cssclass' -- CSS class
27 * 'options' -- varies according to the specific object.
28 * 'label-message' -- message key for a message to use as the label.
29 * can be an array of msg key and then parameters to
31 * 'label' -- alternatively, a raw text message. Overridden by
33 * 'help-message' -- message key for a message to use as a help text.
34 * can be an array of msg key and then parameters to
36 * Overwrites 'help-messages'.
37 * 'help-messages' -- array of message key. As above, each item can
38 * be an array of msg key and then parameters.
39 * Overwrites 'help-message'.
40 * 'required' -- passed through to the object, indicating that it
41 * is a required field.
42 * 'size' -- the length of text fields
43 * 'filter-callback -- a function name to give you the chance to
44 * massage the inputted value before it's processed.
45 * @see HTMLForm::filter()
46 * 'validation-callback' -- a function name to give you the chance
47 * to impose extra validation on the field input.
48 * @see HTMLForm::validate()
49 * 'name' -- By default, the 'name' attribute of the input field
50 * is "wp{$fieldname}". If you want a different name
51 * (eg one without the "wp" prefix), specify it here and
52 * it will be used without modification.
54 * TODO: Document 'section' / 'subsection' stuff
58 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
59 static $typeMappings = array(
60 'text' => 'HTMLTextField',
61 'textarea' => 'HTMLTextAreaField',
62 'select' => 'HTMLSelectField',
63 'radio' => 'HTMLRadioField',
64 'multiselect' => 'HTMLMultiSelectField',
65 'check' => 'HTMLCheckField',
66 'toggle' => 'HTMLCheckField',
67 'int' => 'HTMLIntField',
68 'float' => 'HTMLFloatField',
69 'info' => 'HTMLInfoField',
70 'selectorother' => 'HTMLSelectOrOtherField',
71 'selectandother' => 'HTMLSelectAndOtherField',
72 'submit' => 'HTMLSubmitField',
73 'hidden' => 'HTMLHiddenField',
74 'edittools' => 'HTMLEditTools',
76 # HTMLTextField will output the correct type="" attribute automagically.
77 # There are about four zillion other HTML5 input types, like url, but
78 # we don't use those at the moment, so no point in adding all of them.
79 'email' => 'HTMLTextField',
80 'password' => 'HTMLTextField',
83 protected $mMessagePrefix;
84 protected $mFlatFields;
85 protected $mFieldTree;
86 protected $mShowReset = false;
89 protected $mSubmitCallback;
90 protected $mValidationErrorMessage;
93 protected $mHeader = '';
94 protected $mFooter = '';
95 protected $mSectionHeaders = array();
96 protected $mSectionFooters = array();
97 protected $mPost = '';
100 protected $mSubmitID;
101 protected $mSubmitName;
102 protected $mSubmitText;
103 protected $mSubmitTooltip;
105 protected $mContext; // <! IContextSource
107 protected $mMethod = 'post';
109 protected $mUseMultipart = false;
110 protected $mHiddenFields = array();
111 protected $mButtons = array();
113 protected $mWrapperLegend = false;
116 * Build a new HTMLForm from an array of field attributes
117 * @param $descriptor Array of Field constructs, as described above
118 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
119 * Obviates the need to call $form->setTitle()
120 * @param $messagePrefix String a prefix to go in front of default messages
122 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
123 if( $context instanceof IContextSource
){
124 $this->mContext
= $context;
125 $this->mTitle
= false; // We don't need them to set a title
126 $this->mMessagePrefix
= $messagePrefix;
129 if( is_string( $context ) && $messagePrefix === '' ){
130 // it's actually $messagePrefix
131 $this->mMessagePrefix
= $context;
135 // Expand out into a tree.
136 $loadedDescriptor = array();
137 $this->mFlatFields
= array();
139 foreach ( $descriptor as $fieldname => $info ) {
140 $section = isset( $info['section'] )
144 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
145 $this->mUseMultipart
= true;
148 $field = self
::loadInputFromParameters( $fieldname, $info );
149 $field->mParent
= $this;
151 $setSection =& $loadedDescriptor;
153 $sectionParts = explode( '/', $section );
155 while ( count( $sectionParts ) ) {
156 $newName = array_shift( $sectionParts );
158 if ( !isset( $setSection[$newName] ) ) {
159 $setSection[$newName] = array();
162 $setSection =& $setSection[$newName];
166 $setSection[$fieldname] = $field;
167 $this->mFlatFields
[$fieldname] = $field;
170 $this->mFieldTree
= $loadedDescriptor;
174 * Add the HTMLForm-specific JavaScript, if it hasn't been
176 * @deprecated since 1.18 load modules with ResourceLoader instead
178 static function addJS() { }
181 * Initialise a new Object for the field
182 * @param $fieldname string
183 * @param $descriptor string input Descriptor, as described above
184 * @return HTMLFormField subclass
186 static function loadInputFromParameters( $fieldname, $descriptor ) {
187 if ( isset( $descriptor['class'] ) ) {
188 $class = $descriptor['class'];
189 } elseif ( isset( $descriptor['type'] ) ) {
190 $class = self
::$typeMappings[$descriptor['type']];
191 $descriptor['class'] = $class;
197 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
200 $descriptor['fieldname'] = $fieldname;
202 $obj = new $class( $descriptor );
208 * Prepare form for submission
210 function prepareForm() {
211 # Check if we have the info we need
212 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
213 throw new MWException( "You must call setTitle() on an HTMLForm" );
216 # Load data from the request.
221 * Try submitting, with edit token check first
222 * @return Status|boolean
224 function tryAuthorizedSubmit() {
225 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
228 if ( $this->getMethod() != 'post' ||
$this->getUser()->matchEditToken( $editToken ) ) {
229 $result = $this->trySubmit();
235 * The here's-one-I-made-earlier option: do the submission if
236 * posted, or display the form with or without funky valiation
238 * @return Bool or Status whether submission was successful.
241 $this->prepareForm();
243 $result = $this->tryAuthorizedSubmit();
244 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
248 $this->displayForm( $result );
253 * Validate all the fields, and call the submision callback
254 * function if everything is kosher.
255 * @return Mixed Bool true == Successful submission, Bool false
256 * == No submission attempted, anything else == Error to
259 function trySubmit() {
260 # Check for validation
261 foreach ( $this->mFlatFields
as $fieldname => $field ) {
262 if ( !empty( $field->mParams
['nodata'] ) ) {
265 if ( $field->validate(
266 $this->mFieldData
[$fieldname],
270 return isset( $this->mValidationErrorMessage
)
271 ?
$this->mValidationErrorMessage
272 : array( 'htmlform-invalid-input' );
276 $callback = $this->mSubmitCallback
;
278 $data = $this->filterDataForSubmit( $this->mFieldData
);
280 $res = call_user_func( $callback, $data, $this );
286 * Set a callback to a function to do something with the form
287 * once it's been successfully validated.
288 * @param $cb String function name. The function will be passed
289 * the output from HTMLForm::filterDataForSubmit, and must
290 * return Bool true on success, Bool false if no submission
291 * was attempted, or String HTML output to display on error.
293 function setSubmitCallback( $cb ) {
294 $this->mSubmitCallback
= $cb;
298 * Set a message to display on a validation error.
299 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
300 * (so each entry can be either a String or Array)
302 function setValidationErrorMessage( $msg ) {
303 $this->mValidationErrorMessage
= $msg;
307 * Set the introductory message, overwriting any existing message.
308 * @param $msg String complete text of message to display
310 function setIntro( $msg ) { $this->mPre
= $msg; }
313 * Add introductory text.
314 * @param $msg String complete text of message to display
316 function addPreText( $msg ) { $this->mPre
.= $msg; }
319 * Add header text, inside the form.
320 * @param $msg String complete text of message to display
321 * @param $section The section to add the header to
323 function addHeaderText( $msg, $section = null ) {
324 if ( is_null( $section ) ) {
325 $this->mHeader
.= $msg;
327 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
328 $this->mSectionHeaders
[$section] = '';
330 $this->mSectionHeaders
[$section] .= $msg;
335 * Add footer text, inside the form.
336 * @param $msg String complete text of message to display
337 * @param $section string The section to add the footer text to
339 function addFooterText( $msg, $section = null ) {
340 if ( is_null( $section ) ) {
341 $this->mFooter
.= $msg;
343 if ( !isset( $this->mSectionFooters
[$section] ) ) {
344 $this->mSectionFooters
[$section] = '';
346 $this->mSectionFooters
[$section] .= $msg;
351 * Add text to the end of the display.
352 * @param $msg String complete text of message to display
354 function addPostText( $msg ) { $this->mPost
.= $msg; }
357 * Add a hidden field to the output
358 * @param $name String field name. This will be used exactly as entered
359 * @param $value String field value
360 * @param $attribs Array
362 public function addHiddenField( $name, $value, $attribs = array() ) {
363 $attribs +
= array( 'name' => $name );
364 $this->mHiddenFields
[] = array( $value, $attribs );
367 public function addButton( $name, $value, $id = null, $attribs = null ) {
368 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
372 * Display the form (sending to wgOut), with an appropriate error
373 * message or stack of messages, and any validation errors, etc.
374 * @param $submitResult Mixed output from HTMLForm::trySubmit()
376 function displayForm( $submitResult ) {
377 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
381 * Returns the raw HTML generated by the form
382 * @param $submitResult Mixed output from HTMLForm::trySubmit()
385 function getHTML( $submitResult ) {
386 # For good measure (it is the default)
387 $this->getOutput()->preventClickjacking();
388 $this->getOutput()->addModules( 'mediawiki.htmlform' );
391 . $this->getErrors( $submitResult )
394 . $this->getHiddenFields()
395 . $this->getButtons()
399 $html = $this->wrapForm( $html );
401 return '' . $this->mPre
. $html . $this->mPost
;
405 * Wrap the form innards in an actual <form> element
406 * @param $html String HTML contents to wrap.
407 * @return String wrapped HTML.
409 function wrapForm( $html ) {
411 # Include a <fieldset> wrapper for style, if requested.
412 if ( $this->mWrapperLegend
!== false ) {
413 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
415 # Use multipart/form-data
416 $encType = $this->mUseMultipart
417 ?
'multipart/form-data'
418 : 'application/x-www-form-urlencoded';
421 'action' => $this->getTitle()->getFullURL(),
422 'method' => $this->mMethod
,
423 'class' => 'visualClear',
424 'enctype' => $encType,
426 if ( !empty( $this->mId
) ) {
427 $attribs['id'] = $this->mId
;
430 return Html
::rawElement( 'form', $attribs, $html );
434 * Get the hidden fields that should go inside the form.
435 * @return String HTML.
437 function getHiddenFields() {
438 global $wgUsePathInfo;
441 if( $this->getMethod() == 'post' ){
442 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
443 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
446 if ( !$wgUsePathInfo && $this->getMethod() == 'get' ) {
447 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
450 foreach ( $this->mHiddenFields
as $data ) {
451 list( $value, $attribs ) = $data;
452 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
459 * Get the submit and (potentially) reset buttons.
460 * @return String HTML.
462 function getButtons() {
466 if ( isset( $this->mSubmitID
) ) {
467 $attribs['id'] = $this->mSubmitID
;
470 if ( isset( $this->mSubmitName
) ) {
471 $attribs['name'] = $this->mSubmitName
;
474 if ( isset( $this->mSubmitTooltip
) ) {
475 $attribs +
= Linker
::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip
);
478 $attribs['class'] = 'mw-htmlform-submit';
480 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
482 if ( $this->mShowReset
) {
483 $html .= Html
::element(
487 'value' => wfMsg( 'htmlform-reset' )
492 foreach ( $this->mButtons
as $button ) {
495 'name' => $button['name'],
496 'value' => $button['value']
499 if ( $button['attribs'] ) {
500 $attrs +
= $button['attribs'];
503 if ( isset( $button['id'] ) ) {
504 $attrs['id'] = $button['id'];
507 $html .= Html
::element( 'input', $attrs );
514 * Get the whole body of the form.
517 return $this->displaySection( $this->mFieldTree
);
521 * Format and display an error message stack.
522 * @param $errors String|Array|Status
525 function getErrors( $errors ) {
526 if ( $errors instanceof Status
) {
527 if ( $errors->isOK() ) {
530 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
532 } elseif ( is_array( $errors ) ) {
533 $errorstr = $this->formatErrors( $errors );
539 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
544 * Format a stack of error messages into a single HTML string
545 * @param $errors Array of message keys/values
546 * @return String HTML, a <ul> list of errors
548 public static function formatErrors( $errors ) {
551 foreach ( $errors as $error ) {
552 if ( is_array( $error ) ) {
553 $msg = array_shift( $error );
559 $errorstr .= Html
::rawElement(
562 wfMsgExt( $msg, array( 'parseinline' ), $error )
566 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
572 * Set the text for the submit button
573 * @param $t String plaintext.
575 function setSubmitText( $t ) {
576 $this->mSubmitText
= $t;
580 * Get the text for the submit button, either customised or a default.
581 * @return unknown_type
583 function getSubmitText() {
584 return $this->mSubmitText
586 : wfMsg( 'htmlform-submit' );
589 public function setSubmitName( $name ) {
590 $this->mSubmitName
= $name;
593 public function setSubmitTooltip( $name ) {
594 $this->mSubmitTooltip
= $name;
598 * Set the id for the submit button.
600 * @todo FIXME: Integrity of $t is *not* validated
602 function setSubmitID( $t ) {
603 $this->mSubmitID
= $t;
606 public function setId( $id ) {
610 * Prompt the whole form to be wrapped in a <fieldset>, with
611 * this text as its <legend> element.
612 * @param $legend String HTML to go inside the <legend> element.
615 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
618 * Set the prefix for various default messages
619 * TODO: currently only used for the <fieldset> legend on forms
620 * with multiple sections; should be used elsewhre?
623 function setMessagePrefix( $p ) {
624 $this->mMessagePrefix
= $p;
628 * Set the title for form submission
629 * @param $t Title of page the form is on/should be posted to
631 function setTitle( $t ) {
639 function getTitle() {
640 return $this->mTitle
=== false
641 ?
$this->getContext()->getTitle()
646 * @return IContextSource
648 public function getContext(){
649 return $this->mContext
instanceof IContextSource
651 : RequestContext
::getMain();
657 public function getOutput(){
658 return $this->getContext()->getOutput();
664 public function getRequest(){
665 return $this->getContext()->getRequest();
671 public function getUser(){
672 return $this->getContext()->getUser();
676 * Set the method used to submit the form
677 * @param $method String
679 public function setMethod( $method='post' ){
680 $this->mMethod
= $method;
683 public function getMethod(){
684 return $this->mMethod
;
689 * @param $fields array of fields (either arrays or objects)
690 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
691 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
693 function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
695 $subsectionHtml = '';
696 $hasLeftColumn = false;
698 foreach ( $fields as $key => $value ) {
699 if ( is_object( $value ) ) {
700 $v = empty( $value->mParams
['nodata'] )
701 ?
$this->mFieldData
[$key]
702 : $value->getDefault();
703 $tableHtml .= $value->getTableRow( $v );
705 if ( $value->getLabel() != ' ' ) {
706 $hasLeftColumn = true;
708 } elseif ( is_array( $value ) ) {
709 $section = $this->displaySection( $value, $key );
710 $legend = $this->getLegend( $key );
711 if ( isset( $this->mSectionHeaders
[$key] ) ) {
712 $section = $this->mSectionHeaders
[$key] . $section;
714 if ( isset( $this->mSectionFooters
[$key] ) ) {
715 $section .= $this->mSectionFooters
[$key];
717 $attributes = array();
718 if ( $fieldsetIDPrefix ) {
719 $attributes['id'] = Sanitizer
::escapeId( "$fieldsetIDPrefix$key" );
721 $subsectionHtml .= Xml
::fieldset( $legend, $section, $attributes ) . "\n";
727 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
728 $classes[] = 'mw-htmlform-nolabel';
732 'class' => implode( ' ', $classes ),
735 if ( $sectionName ) {
736 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
739 $tableHtml = Html
::rawElement( 'table', $attribs,
740 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
742 return $subsectionHtml . "\n" . $tableHtml;
746 * Construct the form fields from the Descriptor array
748 function loadData() {
749 $fieldData = array();
751 foreach ( $this->mFlatFields
as $fieldname => $field ) {
752 if ( !empty( $field->mParams
['nodata'] ) ) {
754 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
755 $fieldData[$fieldname] = $field->getDefault();
757 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
762 foreach ( $fieldData as $name => &$value ) {
763 $field = $this->mFlatFields
[$name];
764 $value = $field->filter( $value, $this->mFlatFields
);
767 $this->mFieldData
= $fieldData;
771 * Stop a reset button being shown for this form
772 * @param $suppressReset Bool set to false to re-enable the
775 function suppressReset( $suppressReset = true ) {
776 $this->mShowReset
= !$suppressReset;
780 * Overload this if you want to apply special filtration routines
781 * to the form as a whole, after it's submitted but before it's
784 * @return unknown_type
786 function filterDataForSubmit( $data ) {
791 * Get a string to go in the <legend> of a section fieldset. Override this if you
792 * want something more complicated
796 public function getLegend( $key ) {
797 return wfMsg( "{$this->mMessagePrefix}-$key" );
802 * The parent class to generate form fields. Any field type should
803 * be a subclass of this.
805 abstract class HTMLFormField
{
807 protected $mValidationCallback;
808 protected $mFilterCallback;
811 protected $mLabel; # String label. Set on construction
813 protected $mClass = '';
822 * This function must be implemented to return the HTML to generate
823 * the input object itself. It should not implement the surrounding
824 * table cells/rows, or labels/help messages.
825 * @param $value String the value to set the input to; eg a default
826 * text for a text input.
827 * @return String valid HTML.
829 abstract function getInputHTML( $value );
832 * Override this function to add specific validation checks on the
833 * field input. Don't forget to call parent::validate() to ensure
834 * that the user-defined callback mValidationCallback is still run
835 * @param $value String the value the field was submitted with
836 * @param $alldata Array the data collected from the form
837 * @return Mixed Bool true on success, or String error to display.
839 function validate( $value, $alldata ) {
840 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
841 return wfMsgExt( 'htmlform-required', 'parseinline' );
844 if ( isset( $this->mValidationCallback
) ) {
845 return call_user_func( $this->mValidationCallback
, $value, $alldata );
851 function filter( $value, $alldata ) {
852 if ( isset( $this->mFilterCallback
) ) {
853 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
860 * Should this field have a label, or is there no input element with the
861 * appropriate id for the label to point to?
863 * @return bool True to output a label, false to suppress
865 protected function needsLabel() {
870 * Get the value that this input has been set to from a posted form,
871 * or the input's default value if it has not been set.
872 * @param $request WebRequest
873 * @return String the value
875 function loadDataFromRequest( $request ) {
876 if ( $request->getCheck( $this->mName
) ) {
877 return $request->getText( $this->mName
);
879 return $this->getDefault();
884 * Initialise the object
885 * @param $params array Associative Array. See HTMLForm doc for syntax.
887 function __construct( $params ) {
888 $this->mParams
= $params;
890 # Generate the label from a message, if possible
891 if ( isset( $params['label-message'] ) ) {
892 $msgInfo = $params['label-message'];
894 if ( is_array( $msgInfo ) ) {
895 $msg = array_shift( $msgInfo );
901 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
902 } elseif ( isset( $params['label'] ) ) {
903 $this->mLabel
= $params['label'];
906 $this->mName
= "wp{$params['fieldname']}";
907 if ( isset( $params['name'] ) ) {
908 $this->mName
= $params['name'];
911 $validName = Sanitizer
::escapeId( $this->mName
);
912 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
913 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
916 $this->mID
= "mw-input-{$this->mName}";
918 if ( isset( $params['default'] ) ) {
919 $this->mDefault
= $params['default'];
922 if ( isset( $params['id'] ) ) {
924 $validId = Sanitizer
::escapeId( $id );
926 if ( $id != $validId ) {
927 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
933 if ( isset( $params['cssclass'] ) ) {
934 $this->mClass
= $params['cssclass'];
937 if ( isset( $params['validation-callback'] ) ) {
938 $this->mValidationCallback
= $params['validation-callback'];
941 if ( isset( $params['filter-callback'] ) ) {
942 $this->mFilterCallback
= $params['filter-callback'];
947 * Get the complete table row for the input, including help text,
948 * labels, and whatever.
949 * @param $value String the value to set the input to.
950 * @return String complete HTML table row.
952 function getTableRow( $value ) {
953 # Check for invalid data.
955 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
957 $cellAttributes = array();
958 $verticalLabel = false;
960 if ( !empty($this->mParams
['vertical-label']) ) {
961 $cellAttributes['colspan'] = 2;
962 $verticalLabel = true;
965 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
969 $errors = self
::formatErrors( $errors );
970 $errorClass = 'mw-htmlform-invalid-input';
973 $label = $this->getLabelHtml( $cellAttributes );
974 $field = Html
::rawElement(
976 array( 'class' => 'mw-input' ) +
$cellAttributes,
977 $this->getInputHTML( $value ) . "\n$errors"
980 $fieldType = get_class( $this );
982 if ( $verticalLabel ) {
983 $html = Html
::rawElement( 'tr',
984 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
985 $html .= Html
::rawElement( 'tr',
986 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
989 $html = Html
::rawElement( 'tr',
990 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
996 if ( isset( $this->mParams
['help-message'] ) ) {
997 $msg = wfMessage( $this->mParams
['help-message'] );
998 if ( $msg->exists() ) {
999 $helptext = $msg->parse();
1001 } elseif ( isset( $this->mParams
['help-messages'] ) ) {
1002 # help-message can be passed a message key (string) or an array containing
1003 # a message key and additional parameters. This makes it impossible to pass
1004 # an array of message key
1005 foreach( $this->mParams
['help-messages'] as $name ) {
1006 $msg = wfMessage( $name );
1007 if( $msg->exists() ) {
1008 $helptext .= $msg->parse(); // append message
1011 } elseif ( isset( $this->mParams
['help'] ) ) {
1012 $helptext = $this->mParams
['help'];
1015 if ( !is_null( $helptext ) ) {
1016 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1018 $row = Html
::rawElement( 'tr', array(), $row );
1025 function getLabel() {
1026 return $this->mLabel
;
1028 function getLabelHtml( $cellAttributes = array() ) {
1029 # Don't output a for= attribute for labels with no associated input.
1030 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1033 if ( $this->needsLabel() ) {
1034 $for['for'] = $this->mID
;
1037 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1038 Html
::rawElement( 'label', $for, $this->getLabel() )
1042 function getDefault() {
1043 if ( isset( $this->mDefault
) ) {
1044 return $this->mDefault
;
1051 * Returns the attributes required for the tooltip and accesskey.
1053 * @return array Attributes
1055 public function getTooltipAndAccessKey() {
1056 if ( empty( $this->mParams
['tooltip'] ) ) {
1059 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
1063 * flatten an array of options to a single array, for instance,
1064 * a set of <options> inside <optgroups>.
1065 * @param $options Associative Array with values either Strings
1067 * @return Array flattened input
1069 public static function flattenOptions( $options ) {
1070 $flatOpts = array();
1072 foreach ( $options as $value ) {
1073 if ( is_array( $value ) ) {
1074 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1076 $flatOpts[] = $value;
1084 * Formats one or more errors as accepted by field validation-callback.
1085 * @param $errors String|Message|Array of strings or Message instances
1086 * @return String html
1089 protected static function formatErrors( $errors ) {
1090 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1091 $errors = array_shift( $errors );
1094 if ( is_array( $errors ) ) {
1096 foreach ( $errors as $error ) {
1097 if ( $error instanceof Message
) {
1098 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1100 $lines[] = Html
::rawElement( 'li', array(), $error );
1103 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1105 if ( $errors instanceof Message
) {
1106 $errors = $errors->parse();
1108 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1113 class HTMLTextField
extends HTMLFormField
{
1114 function getSize() {
1115 return isset( $this->mParams
['size'] )
1116 ?
$this->mParams
['size']
1120 function getInputHTML( $value ) {
1123 'name' => $this->mName
,
1124 'size' => $this->getSize(),
1126 ) +
$this->getTooltipAndAccessKey();
1128 if ( isset( $this->mParams
['maxlength'] ) ) {
1129 $attribs['maxlength'] = $this->mParams
['maxlength'];
1132 if ( !empty( $this->mParams
['disabled'] ) ) {
1133 $attribs['disabled'] = 'disabled';
1136 # TODO: Enforce pattern, step, required, readonly on the server side as
1138 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1139 'placeholder' ) as $param ) {
1140 if ( isset( $this->mParams
[$param] ) ) {
1141 $attribs[$param] = $this->mParams
[$param];
1145 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1146 if ( isset( $this->mParams
[$param] ) ) {
1147 $attribs[$param] = '';
1151 # Implement tiny differences between some field variants
1152 # here, rather than creating a new class for each one which
1153 # is essentially just a clone of this one.
1154 if ( isset( $this->mParams
['type'] ) ) {
1155 switch ( $this->mParams
['type'] ) {
1157 $attribs['type'] = 'email';
1160 $attribs['type'] = 'number';
1163 $attribs['type'] = 'number';
1164 $attribs['step'] = 'any';
1169 $attribs['type'] = $this->mParams
['type'];
1174 return Html
::element( 'input', $attribs );
1177 class HTMLTextAreaField
extends HTMLFormField
{
1178 function getCols() {
1179 return isset( $this->mParams
['cols'] )
1180 ?
$this->mParams
['cols']
1184 function getRows() {
1185 return isset( $this->mParams
['rows'] )
1186 ?
$this->mParams
['rows']
1190 function getInputHTML( $value ) {
1193 'name' => $this->mName
,
1194 'cols' => $this->getCols(),
1195 'rows' => $this->getRows(),
1196 ) +
$this->getTooltipAndAccessKey();
1199 if ( !empty( $this->mParams
['disabled'] ) ) {
1200 $attribs['disabled'] = 'disabled';
1203 if ( !empty( $this->mParams
['readonly'] ) ) {
1204 $attribs['readonly'] = 'readonly';
1207 foreach ( array( 'required', 'autofocus' ) as $param ) {
1208 if ( isset( $this->mParams
[$param] ) ) {
1209 $attribs[$param] = '';
1213 return Html
::element( 'textarea', $attribs, $value );
1218 * A field that will contain a numeric value
1220 class HTMLFloatField
extends HTMLTextField
{
1221 function getSize() {
1222 return isset( $this->mParams
['size'] )
1223 ?
$this->mParams
['size']
1227 function validate( $value, $alldata ) {
1228 $p = parent
::validate( $value, $alldata );
1230 if ( $p !== true ) {
1234 $value = trim( $value );
1236 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1237 # with the addition that a leading '+' sign is ok.
1238 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1239 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1242 # The "int" part of these message names is rather confusing.
1243 # They make equal sense for all numbers.
1244 if ( isset( $this->mParams
['min'] ) ) {
1245 $min = $this->mParams
['min'];
1247 if ( $min > $value ) {
1248 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1252 if ( isset( $this->mParams
['max'] ) ) {
1253 $max = $this->mParams
['max'];
1255 if ( $max < $value ) {
1256 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1265 * A field that must contain a number
1267 class HTMLIntField
extends HTMLFloatField
{
1268 function validate( $value, $alldata ) {
1269 $p = parent
::validate( $value, $alldata );
1271 if ( $p !== true ) {
1275 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1276 # with the addition that a leading '+' sign is ok. Note that leading zeros
1277 # are fine, and will be left in the input, which is useful for things like
1278 # phone numbers when you know that they are integers (the HTML5 type=tel
1279 # input does not require its value to be numeric). If you want a tidier
1280 # value to, eg, save in the DB, clean it up with intval().
1281 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1283 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1293 class HTMLCheckField
extends HTMLFormField
{
1294 function getInputHTML( $value ) {
1295 if ( !empty( $this->mParams
['invert'] ) ) {
1299 $attr = $this->getTooltipAndAccessKey();
1300 $attr['id'] = $this->mID
;
1302 if ( !empty( $this->mParams
['disabled'] ) ) {
1303 $attr['disabled'] = 'disabled';
1306 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1307 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1311 * For a checkbox, the label goes on the right hand side, and is
1312 * added in getInputHTML(), rather than HTMLFormField::getRow()
1314 function getLabel() {
1319 * @param $request WebRequest
1322 function loadDataFromRequest( $request ) {
1324 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1328 // GetCheck won't work like we want for checks.
1329 if ( $request->getCheck( 'wpEditToken' ) ||
$this->mParent
->getMethod() != 'post' ) {
1330 // XOR has the following truth table, which is what we want
1331 // INVERT VALUE | OUTPUT
1332 // true true | false
1333 // false true | true
1334 // false false | false
1335 // true false | true
1336 return $request->getBool( $this->mName
) xor $invert;
1338 return $this->getDefault();
1344 * A select dropdown field. Basically a wrapper for Xmlselect class
1346 class HTMLSelectField
extends HTMLFormField
{
1347 function validate( $value, $alldata ) {
1348 $p = parent
::validate( $value, $alldata );
1350 if ( $p !== true ) {
1354 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1356 if ( in_array( $value, $validOptions ) )
1359 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1362 function getInputHTML( $value ) {
1363 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1365 # If one of the options' 'name' is int(0), it is automatically selected.
1366 # because PHP sucks and thinks int(0) == 'some string'.
1367 # Working around this by forcing all of them to strings.
1368 foreach( $this->mParams
['options'] as &$opt ){
1369 if( is_int( $opt ) ){
1370 $opt = strval( $opt );
1373 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1375 if ( !empty( $this->mParams
['disabled'] ) ) {
1376 $select->setAttribute( 'disabled', 'disabled' );
1379 $select->addOptions( $this->mParams
['options'] );
1381 return $select->getHTML();
1386 * Select dropdown field, with an additional "other" textbox.
1388 class HTMLSelectOrOtherField
extends HTMLTextField
{
1389 static $jsAdded = false;
1391 function __construct( $params ) {
1392 if ( !in_array( 'other', $params['options'], true ) ) {
1393 $msg = isset( $params['other'] ) ?
$params['other'] : wfMsg( 'htmlform-selectorother-other' );
1394 $params['options'][$msg] = 'other';
1397 parent
::__construct( $params );
1400 static function forceToStringRecursive( $array ) {
1401 if ( is_array( $array ) ) {
1402 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1404 return strval( $array );
1408 function getInputHTML( $value ) {
1409 $valInSelect = false;
1411 if ( $value !== false ) {
1412 $valInSelect = in_array(
1414 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1418 $selected = $valInSelect ?
$value : 'other';
1420 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1422 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1423 $select->addOptions( $opts );
1425 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1427 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1429 if ( !empty( $this->mParams
['disabled'] ) ) {
1430 $select->setAttribute( 'disabled', 'disabled' );
1431 $tbAttribs['disabled'] = 'disabled';
1434 $select = $select->getHTML();
1436 if ( isset( $this->mParams
['maxlength'] ) ) {
1437 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1440 $textbox = Html
::input(
1441 $this->mName
. '-other',
1442 $valInSelect ?
'' : $value,
1447 return "$select<br />\n$textbox";
1451 * @param $request WebRequest
1454 function loadDataFromRequest( $request ) {
1455 if ( $request->getCheck( $this->mName
) ) {
1456 $val = $request->getText( $this->mName
);
1458 if ( $val == 'other' ) {
1459 $val = $request->getText( $this->mName
. '-other' );
1464 return $this->getDefault();
1470 * Multi-select field
1472 class HTMLMultiSelectField
extends HTMLFormField
{
1474 public function __construct( $params ){
1475 parent
::__construct( $params );
1476 if( isset( $params['flatlist'] ) ){
1477 $this->mClass
.= ' mw-htmlform-multiselect-flatlist';
1481 function validate( $value, $alldata ) {
1482 $p = parent
::validate( $value, $alldata );
1484 if ( $p !== true ) {
1488 if ( !is_array( $value ) ) {
1492 # If all options are valid, array_intersect of the valid options
1493 # and the provided options will return the provided options.
1494 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1496 $validValues = array_intersect( $value, $validOptions );
1497 if ( count( $validValues ) == count( $value ) ) {
1500 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1504 function getInputHTML( $value ) {
1505 $html = $this->formatOptions( $this->mParams
['options'], $value );
1510 function formatOptions( $options, $value ) {
1515 if ( !empty( $this->mParams
['disabled'] ) ) {
1516 $attribs['disabled'] = 'disabled';
1519 foreach ( $options as $label => $info ) {
1520 if ( is_array( $info ) ) {
1521 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1522 $html .= $this->formatOptions( $info, $value );
1524 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1526 $checkbox = Xml
::check(
1527 $this->mName
. '[]',
1528 in_array( $info, $value, true ),
1529 $attribs +
$thisAttribs );
1530 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1532 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
1540 * @param $request WebRequest
1543 function loadDataFromRequest( $request ) {
1544 if ( $this->mParent
->getMethod() == 'post' ) {
1545 if( $request->wasPosted() ){
1546 # Checkboxes are just not added to the request arrays if they're not checked,
1547 # so it's perfectly possible for there not to be an entry at all
1548 return $request->getArray( $this->mName
, array() );
1550 # That's ok, the user has not yet submitted the form, so show the defaults
1551 return $this->getDefault();
1554 # This is the impossible case: if we look at $_GET and see no data for our
1555 # field, is it because the user has not yet submitted the form, or that they
1556 # have submitted it with all the options unchecked? We will have to assume the
1557 # latter, which basically means that you can't specify 'positive' defaults
1560 return $request->getArray( $this->mName
, array() );
1564 function getDefault() {
1565 if ( isset( $this->mDefault
) ) {
1566 return $this->mDefault
;
1572 protected function needsLabel() {
1578 * Double field with a dropdown list constructed from a system message in the format
1581 * * New Optgroup header
1582 * Plus a text field underneath for an additional reason. The 'value' of the field is
1583 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1585 * @todo FIXME: If made 'required', only the text field should be compulsory.
1587 class HTMLSelectAndOtherField
extends HTMLSelectField
{
1589 function __construct( $params ) {
1590 if ( array_key_exists( 'other', $params ) ) {
1591 } elseif( array_key_exists( 'other-message', $params ) ){
1592 $params['other'] = wfMessage( $params['other-message'] )->plain();
1594 $params['other'] = null;
1597 if ( array_key_exists( 'options', $params ) ) {
1598 # Options array already specified
1599 } elseif( array_key_exists( 'options-message', $params ) ){
1600 # Generate options array from a system message
1601 $params['options'] = self
::parseMessage(
1602 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1607 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1609 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
1611 parent
::__construct( $params );
1615 * Build a drop-down box from a textual list.
1616 * @param $string String message text
1617 * @param $otherName String name of "other reason" option
1619 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1621 public static function parseMessage( $string, $otherName=null ) {
1622 if( $otherName === null ){
1623 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1627 $options = array( $otherName => 'other' );
1629 foreach ( explode( "\n", $string ) as $option ) {
1630 $value = trim( $option );
1631 if ( $value == '' ) {
1633 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1634 # A new group is starting...
1635 $value = trim( substr( $value, 1 ) );
1637 } elseif ( substr( $value, 0, 2) == '**' ) {
1639 $opt = trim( substr( $value, 2 ) );
1640 if( $optgroup === false ){
1641 $options[$opt] = $opt;
1643 $options[$optgroup][$opt] = $opt;
1646 # groupless reason list
1648 $options[$option] = $option;
1655 function getInputHTML( $value ) {
1656 $select = parent
::getInputHTML( $value[1] );
1658 $textAttribs = array(
1659 'id' => $this->mID
. '-other',
1660 'size' => $this->getSize(),
1663 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1664 if ( isset( $this->mParams
[$param] ) ) {
1665 $textAttribs[$param] = '';
1669 $textbox = Html
::input(
1670 $this->mName
. '-other',
1676 return "$select<br />\n$textbox";
1680 * @param $request WebRequest
1681 * @return Array( <overall message>, <select value>, <text field value> )
1683 function loadDataFromRequest( $request ) {
1684 if ( $request->getCheck( $this->mName
) ) {
1686 $list = $request->getText( $this->mName
);
1687 $text = $request->getText( $this->mName
. '-other' );
1689 if ( $list == 'other' ) {
1691 } elseif( !in_array( $list, $this->mFlatOptions
) ){
1692 # User has spoofed the select form to give an option which wasn't
1693 # in the original offer. Sulk...
1695 } elseif( $text == '' ) {
1698 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1702 $final = $this->getDefault();
1705 return array( $final, $list, $text );
1708 function getSize() {
1709 return isset( $this->mParams
['size'] )
1710 ?
$this->mParams
['size']
1714 function validate( $value, $alldata ) {
1715 # HTMLSelectField forces $value to be one of the options in the select
1716 # field, which is not useful here. But we do want the validation further up
1718 $p = parent
::validate( $value[1], $alldata );
1720 if ( $p !== true ) {
1724 if( isset( $this->mParams
['required'] ) && $value[1] === '' ){
1725 return wfMsgExt( 'htmlform-required', 'parseinline' );
1733 * Radio checkbox fields.
1735 class HTMLRadioField
extends HTMLFormField
{
1736 function validate( $value, $alldata ) {
1737 $p = parent
::validate( $value, $alldata );
1739 if ( $p !== true ) {
1743 if ( !is_string( $value ) && !is_int( $value ) ) {
1747 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1749 if ( in_array( $value, $validOptions ) ) {
1752 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1757 * This returns a block of all the radio options, in one cell.
1758 * @see includes/HTMLFormField#getInputHTML()
1760 function getInputHTML( $value ) {
1761 $html = $this->formatOptions( $this->mParams
['options'], $value );
1766 function formatOptions( $options, $value ) {
1770 if ( !empty( $this->mParams
['disabled'] ) ) {
1771 $attribs['disabled'] = 'disabled';
1774 # TODO: should this produce an unordered list perhaps?
1775 foreach ( $options as $label => $info ) {
1776 if ( is_array( $info ) ) {
1777 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1778 $html .= $this->formatOptions( $info, $value );
1780 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1781 $html .= Xml
::radio(
1785 $attribs +
array( 'id' => $id )
1788 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1790 $html .= "<br />\n";
1797 protected function needsLabel() {
1803 * An information field (text blob), not a proper input.
1805 class HTMLInfoField
extends HTMLFormField
{
1806 function __construct( $info ) {
1807 $info['nodata'] = true;
1809 parent
::__construct( $info );
1812 function getInputHTML( $value ) {
1813 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1816 function getTableRow( $value ) {
1817 if ( !empty( $this->mParams
['rawrow'] ) ) {
1821 return parent
::getTableRow( $value );
1824 protected function needsLabel() {
1829 class HTMLHiddenField
extends HTMLFormField
{
1830 public function __construct( $params ) {
1831 parent
::__construct( $params );
1833 # Per HTML5 spec, hidden fields cannot be 'required'
1834 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1835 unset( $this->mParams
['required'] );
1838 public function getTableRow( $value ) {
1841 $params['id'] = $this->mID
;
1844 $this->mParent
->addHiddenField(
1853 public function getInputHTML( $value ) { return ''; }
1857 * Add a submit button inline in the form (as opposed to
1858 * HTMLForm::addButton(), which will add it at the end).
1860 class HTMLSubmitField
extends HTMLFormField
{
1862 function __construct( $info ) {
1863 $info['nodata'] = true;
1864 parent
::__construct( $info );
1867 function getInputHTML( $value ) {
1868 return Xml
::submitButton(
1871 'class' => 'mw-htmlform-submit',
1872 'name' => $this->mName
,
1878 protected function needsLabel() {
1883 * Button cannot be invalid
1885 public function validate( $value, $alldata ){
1890 class HTMLEditTools
extends HTMLFormField
{
1891 public function getInputHTML( $value ) {
1895 public function getTableRow( $value ) {
1896 if ( empty( $this->mParams
['message'] ) ) {
1897 $msg = wfMessage( 'edittools' );
1899 $msg = wfMessage( $this->mParams
['message'] );
1900 if ( $msg->isDisabled() ) {
1901 $msg = wfMessage( 'edittools' );
1904 $msg->inContentLanguage();
1907 return '<tr><td></td><td class="mw-input">'
1908 . '<div class="mw-editTools">'
1909 . $msg->parseAsBlock()
1910 . "</div></td></tr>\n";