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
57 static $jsAdded = false;
59 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
60 static $typeMappings = array(
61 'text' => 'HTMLTextField',
62 'textarea' => 'HTMLTextAreaField',
63 'select' => 'HTMLSelectField',
64 'radio' => 'HTMLRadioField',
65 'multiselect' => 'HTMLMultiSelectField',
66 'check' => 'HTMLCheckField',
67 'toggle' => 'HTMLCheckField',
68 'int' => 'HTMLIntField',
69 'float' => 'HTMLFloatField',
70 'info' => 'HTMLInfoField',
71 'selectorother' => 'HTMLSelectOrOtherField',
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 $mMethod = 'post';
107 protected $mUseMultipart = false;
108 protected $mHiddenFields = array();
109 protected $mButtons = array();
111 protected $mWrapperLegend = false;
112 protected $mTokenAction = 'Edit';
115 * Build a new HTMLForm from an array of field attributes
116 * @param $descriptor Array of Field constructs, as described above
117 * @param $messagePrefix String a prefix to go in front of default messages
119 public function __construct( $descriptor, $messagePrefix = '' ) {
120 $this->mMessagePrefix
= $messagePrefix;
122 // Expand out into a tree.
123 $loadedDescriptor = array();
124 $this->mFlatFields
= array();
126 foreach ( $descriptor as $fieldname => $info ) {
127 $section = isset( $info['section'] )
131 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
132 $this->mUseMultipart
= true;
135 $field = self
::loadInputFromParameters( $fieldname, $info );
136 $field->mParent
= $this;
138 $setSection =& $loadedDescriptor;
140 $sectionParts = explode( '/', $section );
142 while ( count( $sectionParts ) ) {
143 $newName = array_shift( $sectionParts );
145 if ( !isset( $setSection[$newName] ) ) {
146 $setSection[$newName] = array();
149 $setSection =& $setSection[$newName];
153 $setSection[$fieldname] = $field;
154 $this->mFlatFields
[$fieldname] = $field;
157 $this->mFieldTree
= $loadedDescriptor;
161 * Add the HTMLForm-specific JavaScript, if it hasn't been
164 static function addJS() {
165 if ( self
::$jsAdded ) return;
169 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
173 * Initialise a new Object for the field
174 * @param $descriptor input Descriptor, as described above
175 * @return HTMLFormField subclass
177 static function loadInputFromParameters( $fieldname, $descriptor ) {
178 if ( isset( $descriptor['class'] ) ) {
179 $class = $descriptor['class'];
180 } elseif ( isset( $descriptor['type'] ) ) {
181 $class = self
::$typeMappings[$descriptor['type']];
182 $descriptor['class'] = $class;
186 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
189 $descriptor['fieldname'] = $fieldname;
191 $obj = new $class( $descriptor );
197 * Prepare form for submission
199 function prepareForm() {
200 # Check if we have the info we need
201 if ( ! $this->mTitle
) {
202 throw new MWException( "You must call setTitle() on an HTMLForm" );
205 // FIXME shouldn't this be closer to displayForm() ?
208 # Load data from the request.
213 * Try submitting, with edit token check first
214 * @return Status|boolean
216 function tryAuthorizedSubmit() {
217 global $wgUser, $wgRequest;
218 $editToken = $wgRequest->getVal( 'wpEditToken' );
222 if ( $wgRequest->wasPosted() ){#&& $this->getMethod() != 'post' || $wgUser->matchEditToken( $editToken ) ) {
223 $result = $this->trySubmit();
229 * The here's-one-I-made-earlier option: do the submission if
230 * posted, or display the form with or without funky valiation
232 * @return Bool or Status whether submission was successful.
235 $this->prepareForm();
237 $result = $this->tryAuthorizedSubmit();
238 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
242 $this->displayForm( $result );
247 * Validate all the fields, and call the submision callback
248 * function if everything is kosher.
249 * @return Mixed Bool true == Successful submission, Bool false
250 * == No submission attempted, anything else == Error to
253 function trySubmit() {
254 # Check the session tokens
256 if ( false && !Token
::match( null, $this->mTokenAction
) ) {
257 return array( 'sessionfailure' );
259 # Check for validation
260 foreach ( $this->mFlatFields
as $fieldname => $field ) {
261 if ( !empty( $field->mParams
['nodata'] ) ) {
264 if ( $field->validate(
265 $this->mFieldData
[$fieldname],
269 return isset( $this->mValidationErrorMessage
)
270 ?
$this->mValidationErrorMessage
271 : array( 'htmlform-invalid-input' );
275 $callback = $this->mSubmitCallback
;
277 $data = $this->filterDataForSubmit( $this->mFieldData
);
279 $res = call_user_func( $callback, $data );
285 * Set a callback to a function to do something with the form
286 * once it's been successfully validated.
287 * @param $cb String function name. The function will be passed
288 * the output from HTMLForm::filterDataForSubmit, and must
289 * return Bool true on success, Bool false if no submission
290 * was attempted, or String HTML output to display on error.
292 function setSubmitCallback( $cb ) {
293 $this->mSubmitCallback
= $cb;
297 * Set a message to display on a validation error.
298 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
299 * (so each entry can be either a String or Array)
301 function setValidationErrorMessage( $msg ) {
302 $this->mValidationErrorMessage
= $msg;
306 * Set the introductory message, overwriting any existing message.
307 * @param $msg String complete text of message to display
309 function setIntro( $msg ) { $this->mPre
= $msg; }
312 * Add introductory text.
313 * @param $msg String complete text of message to display
315 function addPreText( $msg ) { $this->mPre
.= $msg; }
318 * Add header text, inside the form.
319 * @param $msg String complete text of message to display
321 function addHeaderText( $msg, $section = null ) {
322 if ( is_null( $section ) ) {
323 $this->mHeader
.= $msg;
325 if ( !isset( $this->mSectionHeaders
[$section] ) ) {
326 $this->mSectionHeaders
[$section] = '';
328 $this->mSectionHeaders
[$section] .= $msg;
333 * Add footer text, inside the form.
334 * @param $msg String complete text of message to display
336 function addFooterText( $msg, $section = null ) {
337 if ( is_null( $section ) ) {
338 $this->mFooter
.= $msg;
340 if ( !isset( $this->mSectionFooters
[$section] ) ) {
341 $this->mSectionFooters
[$section] = '';
343 $this->mSectionFooters
[$section] .= $msg;
348 * Add text to the end of the display.
349 * @param $msg String complete text of message to display
351 function addPostText( $msg ) { $this->mPost
.= $msg; }
354 * Add a hidden field to the output
355 * @param $name String field name. This will be used exactly as entered
356 * @param $value String field value
357 * @param $attribs Array
359 public function addHiddenField( $name, $value, $attribs = array() ) {
360 $attribs +
= array( 'name' => $name );
361 $this->mHiddenFields
[] = array( $value, $attribs );
364 public function addButton( $name, $value, $id = null, $attribs = null ) {
365 $this->mButtons
[] = compact( 'name', 'value', 'id', 'attribs' );
369 * Display the form (sending to wgOut), with an appropriate error
370 * message or stack of messages, and any validation errors, etc.
371 * @param $submitResult Mixed output from HTMLForm::trySubmit()
373 function displayForm( $submitResult ) {
376 # For good measure (it is the default)
377 $wgOut->preventClickjacking();
380 . $this->getErrors( $submitResult )
383 . $this->getHiddenFields()
384 . $this->getButtons()
388 $html = $this->wrapForm( $html );
398 * Wrap the form innards in an actual <form> element
399 * @param $html String HTML contents to wrap.
400 * @return String wrapped HTML.
402 function wrapForm( $html ) {
404 # Include a <fieldset> wrapper for style, if requested.
405 if ( $this->mWrapperLegend
!== false ) {
406 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
408 # Use multipart/form-data
409 $encType = $this->mUseMultipart
410 ?
'multipart/form-data'
411 : 'application/x-www-form-urlencoded';
414 'action' => $this->getTitle()->getFullURL(),
415 'method' => $this->mMethod
,
416 'class' => 'visualClear',
417 'enctype' => $encType,
419 if ( !empty( $this->mId
) ) {
420 $attribs['id'] = $this->mId
;
423 return Html
::rawElement( 'form', $attribs, $html );
427 * Get the hidden fields that should go inside the form.
428 * @return String HTML.
430 function getHiddenFields() {
434 if( $this->getMethod() == 'post' ){
436 $token = new Token( $this->mTokenAction
);
437 $html .= Html
::hidden(
438 "wp{$this->mTokenAction}Token",
440 array( 'id' => 'wpEditToken' )
442 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
445 foreach ( $this->mHiddenFields
as $data ) {
446 list( $value, $attribs ) = $data;
447 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
454 * Get the submit and (potentially) reset buttons.
455 * @return String HTML.
457 function getButtons() {
461 if ( isset( $this->mSubmitID
) ) {
462 $attribs['id'] = $this->mSubmitID
;
465 if ( isset( $this->mSubmitName
) ) {
466 $attribs['name'] = $this->mSubmitName
;
469 if ( isset( $this->mSubmitTooltip
) ) {
471 $attribs +
= $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
474 $attribs['class'] = 'mw-htmlform-submit';
476 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
478 if ( $this->mShowReset
) {
479 $html .= Html
::element(
483 'value' => wfMsg( 'htmlform-reset' )
488 foreach ( $this->mButtons
as $button ) {
491 'name' => $button['name'],
492 'value' => $button['value']
495 if ( $button['attribs'] ) {
496 $attrs +
= $button['attribs'];
499 if ( isset( $button['id'] ) ) {
500 $attrs['id'] = $button['id'];
503 $html .= Html
::element( 'input', $attrs );
510 * Get the whole body of the form.
513 return $this->displaySection( $this->mFieldTree
);
517 * Format and display an error message stack.
518 * @param $errors Mixed String or Array of message keys
521 function getErrors( $errors ) {
522 if ( $errors instanceof Status
) {
524 if ( $errors->isOK() ) {
527 $errorstr = $wgOut->parse( $errors->getWikiText() );
529 } elseif ( is_array( $errors ) ) {
530 $errorstr = $this->formatErrors( $errors );
536 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
541 * Format a stack of error messages into a single HTML string
542 * @param $errors Array of message keys/values
543 * @return String HTML, a <ul> list of errors
545 static function formatErrors( $errors ) {
548 foreach ( $errors as $error ) {
549 if ( is_array( $error ) ) {
550 $msg = array_shift( $error );
556 $errorstr .= Html
::rawElement(
559 wfMsgExt( $msg, array( 'parseinline' ), $error )
563 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
569 * Set the text for the submit button
570 * @param $t String plaintext.
572 function setSubmitText( $t ) {
573 $this->mSubmitText
= $t;
577 * Get the text for the submit button, either customised or a default.
578 * @return unknown_type
580 function getSubmitText() {
581 return $this->mSubmitText
583 : wfMsg( 'htmlform-submit' );
586 public function setSubmitName( $name ) {
587 $this->mSubmitName
= $name;
590 public function setSubmitTooltip( $name ) {
591 $this->mSubmitTooltip
= $name;
596 * Set the id for the submit button.
597 * @param $t String. FIXME: Integrity is *not* validated
599 function setSubmitID( $t ) {
600 $this->mSubmitID
= $t;
603 public function setId( $id ) {
607 * Prompt the whole form to be wrapped in a <fieldset>, with
608 * this text as its <legend> element.
609 * @param $legend String HTML to go inside the <legend> element.
612 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
615 * Set the prefix for various default messages
616 * TODO: currently only used for the <fieldset> legend on forms
617 * with multiple sections; should be used elsewhre?
620 function setMessagePrefix( $p ) {
621 $this->mMessagePrefix
= $p;
624 * If you want to protect the form from CSRF by a token other than
625 * the usual wsEditToken, set something here.
629 function setTokenAction( $a ){
630 $this->mTokenAction
= ucfirst( $a );
634 * Set the title for form submission
635 * @param $t Title of page the form is on/should be posted to
637 function setTitle( $t ) {
645 function getTitle() {
646 return $this->mTitle
;
650 * Set the method used to submit the form
651 * @param $method String
653 public function setMethod( $method='post' ){
654 $this->mMethod
= $method;
657 public function getMethod(){
658 return $this->mMethod
;
665 function displaySection( $fields, $sectionName = '' ) {
667 $subsectionHtml = '';
668 $hasLeftColumn = false;
670 foreach ( $fields as $key => $value ) {
671 if ( is_object( $value ) ) {
672 $v = empty( $value->mParams
['nodata'] )
673 ?
$this->mFieldData
[$key]
674 : $value->getDefault();
675 $tableHtml .= $value->getTableRow( $v );
677 if ( $value->getLabel() != ' ' )
678 $hasLeftColumn = true;
679 } elseif ( is_array( $value ) ) {
680 $section = $this->displaySection( $value, $key );
681 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
682 if ( isset( $this->mSectionHeaders
[$key] ) ) {
683 $section = $this->mSectionHeaders
[$key] . $section;
685 if ( isset( $this->mSectionFooters
[$key] ) ) {
686 $section .= $this->mSectionFooters
[$key];
688 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
694 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
695 $classes[] = 'mw-htmlform-nolabel';
699 'class' => implode( ' ', $classes ),
702 if ( $sectionName ) {
703 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
706 $tableHtml = Html
::rawElement( 'table', $attribs,
707 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
709 return $subsectionHtml . "\n" . $tableHtml;
713 * Construct the form fields from the Descriptor array
715 function loadData() {
718 $fieldData = array();
720 foreach ( $this->mFlatFields
as $fieldname => $field ) {
721 if ( !empty( $field->mParams
['nodata'] ) ) {
723 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
724 $fieldData[$fieldname] = $field->getDefault();
726 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
731 foreach ( $fieldData as $name => &$value ) {
732 $field = $this->mFlatFields
[$name];
733 $value = $field->filter( $value, $this->mFlatFields
);
736 $this->mFieldData
= $fieldData;
740 * Stop a reset button being shown for this form
741 * @param $suppressReset Bool set to false to re-enable the
744 function suppressReset( $suppressReset = true ) {
745 $this->mShowReset
= !$suppressReset;
749 * Overload this if you want to apply special filtration routines
750 * to the form as a whole, after it's submitted but before it's
753 * @return unknown_type
755 function filterDataForSubmit( $data ) {
761 * The parent class to generate form fields. Any field type should
762 * be a subclass of this.
764 abstract class HTMLFormField
{
766 protected $mValidationCallback;
767 protected $mFilterCallback;
770 protected $mLabel; # String label. Set on construction
772 protected $mClass = '';
777 * This function must be implemented to return the HTML to generate
778 * the input object itself. It should not implement the surrounding
779 * table cells/rows, or labels/help messages.
780 * @param $value String the value to set the input to; eg a default
781 * text for a text input.
782 * @return String valid HTML.
784 abstract function getInputHTML( $value );
787 * Override this function to add specific validation checks on the
788 * field input. Don't forget to call parent::validate() to ensure
789 * that the user-defined callback mValidationCallback is still run
790 * @param $value String the value the field was submitted with
791 * @param $alldata Array the data collected from the form
792 * @return Mixed Bool true on success, or String error to display.
794 function validate( $value, $alldata ) {
795 if ( isset( $this->mValidationCallback
) ) {
796 return call_user_func( $this->mValidationCallback
, $value, $alldata );
799 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
800 return wfMsgExt( 'htmlform-required', 'parseinline' );
806 function filter( $value, $alldata ) {
807 if ( isset( $this->mFilterCallback
) ) {
808 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
815 * Should this field have a label, or is there no input element with the
816 * appropriate id for the label to point to?
818 * @return bool True to output a label, false to suppress
820 protected function needsLabel() {
825 * Get the value that this input has been set to from a posted form,
826 * or the input's default value if it has not been set.
827 * @param $request WebRequest
828 * @return String the value
830 function loadDataFromRequest( $request ) {
831 if ( $request->getCheck( $this->mName
) ) {
832 return $request->getText( $this->mName
);
834 return $this->getDefault();
839 * Initialise the object
840 * @param $params Associative Array. See HTMLForm doc for syntax.
842 function __construct( $params ) {
843 $this->mParams
= $params;
845 # Generate the label from a message, if possible
846 if ( isset( $params['label-message'] ) ) {
847 $msgInfo = $params['label-message'];
849 if ( is_array( $msgInfo ) ) {
850 $msg = array_shift( $msgInfo );
856 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
857 } elseif ( isset( $params['label'] ) ) {
858 $this->mLabel
= $params['label'];
861 $this->mName
= "wp{$params['fieldname']}";
862 if ( isset( $params['name'] ) ) {
863 $this->mName
= $params['name'];
866 $validName = Sanitizer
::escapeId( $this->mName
);
867 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
868 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
871 $this->mID
= "mw-input-{$this->mName}";
873 if ( isset( $params['default'] ) ) {
874 $this->mDefault
= $params['default'];
877 if ( isset( $params['id'] ) ) {
879 $validId = Sanitizer
::escapeId( $id );
881 if ( $id != $validId ) {
882 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
888 if ( isset( $params['cssclass'] ) ) {
889 $this->mClass
= $params['cssclass'];
892 if ( isset( $params['validation-callback'] ) ) {
893 $this->mValidationCallback
= $params['validation-callback'];
896 if ( isset( $params['filter-callback'] ) ) {
897 $this->mFilterCallback
= $params['filter-callback'];
902 * Get the complete table row for the input, including help text,
903 * labels, and whatever.
904 * @param $value String the value to set the input to.
905 * @return String complete HTML table row.
907 function getTableRow( $value ) {
908 # Check for invalid data.
911 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
913 $cellAttributes = array();
914 $verticalLabel = false;
916 if ( !empty($this->mParams
['vertical-label']) ) {
917 $cellAttributes['colspan'] = 2;
918 $verticalLabel = true;
921 if ( $errors === true ||
( !$wgRequest->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
924 $errors = Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
927 $label = $this->getLabelHtml( $cellAttributes );
928 $field = Html
::rawElement(
930 array( 'class' => 'mw-input' ) +
$cellAttributes,
931 $this->getInputHTML( $value ) . "\n$errors"
934 $fieldType = get_class( $this );
936 if ($verticalLabel) {
937 $html = Html
::rawElement( 'tr',
938 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
939 $html .= Html
::rawElement( 'tr',
940 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
943 $html = Html
::rawElement( 'tr',
944 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
950 if ( isset( $this->mParams
['help-message'] ) ) {
951 $msg = $this->mParams
['help-message'];
952 $helptext = wfMsgExt( $msg, 'parseinline' );
953 if ( wfEmptyMsg( $msg, $helptext ) ) {
957 } elseif ( isset( $this->mParams
['help-messages'] ) ) {
958 # help-message can be passed a message key (string) or an array containing
959 # a message key and additional parameters. This makes it impossible to pass
960 # an array of message key
961 foreach( $this->mParams
['help-messages'] as $msg ) {
962 $candidate = wfMsgExt( $msg, 'parseinline' );
963 if( wfEmptyMsg( $msg ) ) {
966 $helptext .= $candidate; // append message
968 } elseif ( isset( $this->mParams
['help'] ) ) {
969 $helptext = $this->mParams
['help'];
972 if ( !is_null( $helptext ) ) {
973 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
975 $row = Html
::rawElement( 'tr', array(), $row );
982 function getLabel() {
983 return $this->mLabel
;
985 function getLabelHtml( $cellAttributes = array() ) {
986 # Don't output a for= attribute for labels with no associated input.
987 # Kind of hacky here, possibly we don't want these to be <label>s at all.
990 if ( $this->needsLabel() ) {
991 $for['for'] = $this->mID
;
994 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
995 Html
::rawElement( 'label', $for, $this->getLabel() )
999 function getDefault() {
1000 if ( isset( $this->mDefault
) ) {
1001 return $this->mDefault
;
1008 * Returns the attributes required for the tooltip and accesskey.
1010 * @return array Attributes
1012 public function getTooltipAndAccessKey() {
1013 if ( empty( $this->mParams
['tooltip'] ) ) {
1019 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
1023 * flatten an array of options to a single array, for instance,
1024 * a set of <options> inside <optgroups>.
1025 * @param $options Associative Array with values either Strings
1027 * @return Array flattened input
1029 public static function flattenOptions( $options ) {
1030 $flatOpts = array();
1032 foreach ( $options as $value ) {
1033 if ( is_array( $value ) ) {
1034 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1036 $flatOpts[] = $value;
1044 class HTMLTextField
extends HTMLFormField
{
1045 function getSize() {
1046 return isset( $this->mParams
['size'] )
1047 ?
$this->mParams
['size']
1051 function getInputHTML( $value ) {
1054 'name' => $this->mName
,
1055 'size' => $this->getSize(),
1057 ) +
$this->getTooltipAndAccessKey();
1059 if ( isset( $this->mParams
['maxlength'] ) ) {
1060 $attribs['maxlength'] = $this->mParams
['maxlength'];
1063 if ( !empty( $this->mParams
['disabled'] ) ) {
1064 $attribs['disabled'] = 'disabled';
1067 # TODO: Enforce pattern, step, required, readonly on the server side as
1069 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1070 'placeholder' ) as $param ) {
1071 if ( isset( $this->mParams
[$param] ) ) {
1072 $attribs[$param] = $this->mParams
[$param];
1076 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1077 if ( isset( $this->mParams
[$param] ) ) {
1078 $attribs[$param] = '';
1082 # Implement tiny differences between some field variants
1083 # here, rather than creating a new class for each one which
1084 # is essentially just a clone of this one.
1085 if ( isset( $this->mParams
['type'] ) ) {
1086 switch ( $this->mParams
['type'] ) {
1088 $attribs['type'] = 'email';
1091 $attribs['type'] = 'number';
1094 $attribs['type'] = 'number';
1095 $attribs['step'] = 'any';
1100 $attribs['type'] = $this->mParams
['type'];
1105 return Html
::element( 'input', $attribs );
1108 class HTMLTextAreaField
extends HTMLFormField
{
1109 function getCols() {
1110 return isset( $this->mParams
['cols'] )
1111 ?
$this->mParams
['cols']
1115 function getRows() {
1116 return isset( $this->mParams
['rows'] )
1117 ?
$this->mParams
['rows']
1121 function getInputHTML( $value ) {
1124 'name' => $this->mName
,
1125 'cols' => $this->getCols(),
1126 'rows' => $this->getRows(),
1127 ) +
$this->getTooltipAndAccessKey();
1130 if ( !empty( $this->mParams
['disabled'] ) ) {
1131 $attribs['disabled'] = 'disabled';
1134 if ( !empty( $this->mParams
['readonly'] ) ) {
1135 $attribs['readonly'] = 'readonly';
1138 foreach ( array( 'required', 'autofocus' ) as $param ) {
1139 if ( isset( $this->mParams
[$param] ) ) {
1140 $attribs[$param] = '';
1144 return Html
::element( 'textarea', $attribs, $value );
1149 * A field that will contain a numeric value
1151 class HTMLFloatField
extends HTMLTextField
{
1152 function getSize() {
1153 return isset( $this->mParams
['size'] )
1154 ?
$this->mParams
['size']
1158 function validate( $value, $alldata ) {
1159 $p = parent
::validate( $value, $alldata );
1161 if ( $p !== true ) {
1165 $value = trim( $value );
1167 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1168 # with the addition that a leading '+' sign is ok.
1169 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1170 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1173 # The "int" part of these message names is rather confusing.
1174 # They make equal sense for all numbers.
1175 if ( isset( $this->mParams
['min'] ) ) {
1176 $min = $this->mParams
['min'];
1178 if ( $min > $value ) {
1179 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1183 if ( isset( $this->mParams
['max'] ) ) {
1184 $max = $this->mParams
['max'];
1186 if ( $max < $value ) {
1187 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1196 * A field that must contain a number
1198 class HTMLIntField
extends HTMLFloatField
{
1199 function validate( $value, $alldata ) {
1200 $p = parent
::validate( $value, $alldata );
1202 if ( $p !== true ) {
1206 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1207 # with the addition that a leading '+' sign is ok. Note that leading zeros
1208 # are fine, and will be left in the input, which is useful for things like
1209 # phone numbers when you know that they are integers (the HTML5 type=tel
1210 # input does not require its value to be numeric). If you want a tidier
1211 # value to, eg, save in the DB, clean it up with intval().
1212 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1214 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1224 class HTMLCheckField
extends HTMLFormField
{
1225 function getInputHTML( $value ) {
1226 if ( !empty( $this->mParams
['invert'] ) ) {
1230 $attr = $this->getTooltipAndAccessKey();
1231 $attr['id'] = $this->mID
;
1233 if ( !empty( $this->mParams
['disabled'] ) ) {
1234 $attr['disabled'] = 'disabled';
1237 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1238 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1242 * For a checkbox, the label goes on the right hand side, and is
1243 * added in getInputHTML(), rather than HTMLFormField::getRow()
1245 function getLabel() {
1249 function loadDataFromRequest( $request ) {
1251 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1255 // GetCheck won't work like we want for checks.
1256 if ( $request->getCheck( 'wpEditToken' ) ) {
1257 // XOR has the following truth table, which is what we want
1258 // INVERT VALUE | OUTPUT
1259 // true true | false
1260 // false true | true
1261 // false false | false
1262 // true false | true
1263 return $request->getBool( $this->mName
) xor $invert;
1265 return $this->getDefault();
1271 * A select dropdown field. Basically a wrapper for Xmlselect class
1273 class HTMLSelectField
extends HTMLFormField
{
1274 function validate( $value, $alldata ) {
1275 $p = parent
::validate( $value, $alldata );
1277 if ( $p !== true ) {
1281 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1283 if ( in_array( $value, $validOptions ) )
1286 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1289 function getInputHTML( $value ) {
1290 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1292 # If one of the options' 'name' is int(0), it is automatically selected.
1293 # because PHP sucks and things int(0) == 'some string'.
1294 # Working around this by forcing all of them to strings.
1295 foreach( $this->mParams
['options'] as $key => &$opt ){
1296 if( is_int( $opt ) ){
1297 $opt = strval( $opt );
1300 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1302 if ( !empty( $this->mParams
['disabled'] ) ) {
1303 $select->setAttribute( 'disabled', 'disabled' );
1306 $select->addOptions( $this->mParams
['options'] );
1308 return $select->getHTML();
1313 * Select dropdown field, with an additional "other" textbox.
1315 class HTMLSelectOrOtherField
extends HTMLTextField
{
1316 static $jsAdded = false;
1318 function __construct( $params ) {
1319 if ( !in_array( 'other', $params['options'], true ) ) {
1320 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1323 parent
::__construct( $params );
1326 static function forceToStringRecursive( $array ) {
1327 if ( is_array( $array ) ) {
1328 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1330 return strval( $array );
1334 function getInputHTML( $value ) {
1335 $valInSelect = false;
1337 if ( $value !== false ) {
1338 $valInSelect = in_array(
1340 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1344 $selected = $valInSelect ?
$value : 'other';
1346 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1348 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1349 $select->addOptions( $opts );
1351 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1353 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1355 if ( !empty( $this->mParams
['disabled'] ) ) {
1356 $select->setAttribute( 'disabled', 'disabled' );
1357 $tbAttribs['disabled'] = 'disabled';
1360 $select = $select->getHTML();
1362 if ( isset( $this->mParams
['maxlength'] ) ) {
1363 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1366 $textbox = Html
::input(
1367 $this->mName
. '-other',
1368 $valInSelect ?
'' : $value,
1373 return "$select<br />\n$textbox";
1376 function loadDataFromRequest( $request ) {
1377 if ( $request->getCheck( $this->mName
) ) {
1378 $val = $request->getText( $this->mName
);
1380 if ( $val == 'other' ) {
1381 $val = $request->getText( $this->mName
. '-other' );
1386 return $this->getDefault();
1392 * Multi-select field
1394 class HTMLMultiSelectField
extends HTMLFormField
{
1395 function validate( $value, $alldata ) {
1396 $p = parent
::validate( $value, $alldata );
1398 if ( $p !== true ) {
1402 if ( !is_array( $value ) ) {
1406 # If all options are valid, array_intersect of the valid options
1407 # and the provided options will return the provided options.
1408 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1410 $validValues = array_intersect( $value, $validOptions );
1411 if ( count( $validValues ) == count( $value ) ) {
1414 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1418 function getInputHTML( $value ) {
1419 $html = $this->formatOptions( $this->mParams
['options'], $value );
1424 function formatOptions( $options, $value ) {
1429 if ( !empty( $this->mParams
['disabled'] ) ) {
1430 $attribs['disabled'] = 'disabled';
1433 foreach ( $options as $label => $info ) {
1434 if ( is_array( $info ) ) {
1435 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1436 $html .= $this->formatOptions( $info, $value );
1438 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1440 $checkbox = Xml
::check(
1441 $this->mName
. '[]',
1442 in_array( $info, $value, true ),
1443 $attribs +
$thisAttribs );
1444 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1446 $html .= $checkbox . '<br />';
1453 function loadDataFromRequest( $request ) {
1454 # won't work with getCheck
1455 if ( $request->getCheck( 'wpEditToken' ) ) {
1456 $arr = $request->getArray( $this->mName
);
1464 return $this->getDefault();
1468 function getDefault() {
1469 if ( isset( $this->mDefault
) ) {
1470 return $this->mDefault
;
1476 protected function needsLabel() {
1482 * Radio checkbox fields.
1484 class HTMLRadioField
extends HTMLFormField
{
1485 function validate( $value, $alldata ) {
1486 $p = parent
::validate( $value, $alldata );
1488 if ( $p !== true ) {
1492 if ( !is_string( $value ) && !is_int( $value ) ) {
1496 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1498 if ( in_array( $value, $validOptions ) ) {
1501 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1506 * This returns a block of all the radio options, in one cell.
1507 * @see includes/HTMLFormField#getInputHTML()
1509 function getInputHTML( $value ) {
1510 $html = $this->formatOptions( $this->mParams
['options'], $value );
1515 function formatOptions( $options, $value ) {
1519 if ( !empty( $this->mParams
['disabled'] ) ) {
1520 $attribs['disabled'] = 'disabled';
1523 # TODO: should this produce an unordered list perhaps?
1524 foreach ( $options as $label => $info ) {
1525 if ( is_array( $info ) ) {
1526 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1527 $html .= $this->formatOptions( $info, $value );
1529 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1530 $html .= Xml
::radio(
1534 $attribs +
array( 'id' => $id )
1537 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1539 $html .= "<br />\n";
1546 protected function needsLabel() {
1552 * An information field (text blob), not a proper input.
1554 class HTMLInfoField
extends HTMLFormField
{
1555 function __construct( $info ) {
1556 $info['nodata'] = true;
1558 parent
::__construct( $info );
1561 function getInputHTML( $value ) {
1562 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1565 function getTableRow( $value ) {
1566 if ( !empty( $this->mParams
['rawrow'] ) ) {
1570 return parent
::getTableRow( $value );
1573 protected function needsLabel() {
1578 class HTMLHiddenField
extends HTMLFormField
{
1579 public function __construct( $params ) {
1580 parent
::__construct( $params );
1582 # Per HTML5 spec, hidden fields cannot be 'required'
1583 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1584 unset( $this->mParams
['required'] );
1587 public function getTableRow( $value ) {
1590 $params['id'] = $this->mID
;
1593 $this->mParent
->addHiddenField(
1602 public function getInputHTML( $value ) { return ''; }
1606 * Add a submit button inline in the form (as opposed to
1607 * HTMLForm::addButton(), which will add it at the end).
1609 class HTMLSubmitField
extends HTMLFormField
{
1611 function __construct( $info ) {
1612 $info['nodata'] = true;
1613 parent
::__construct( $info );
1616 function getInputHTML( $value ) {
1617 return Xml
::submitButton(
1620 'class' => 'mw-htmlform-submit',
1621 'name' => $this->mName
,
1627 protected function needsLabel() {
1632 * Button cannot be invalid
1634 public function validate( $value, $alldata ){
1639 class HTMLEditTools
extends HTMLFormField
{
1640 public function getInputHTML( $value ) {
1644 public function getTableRow( $value ) {
1645 if ( empty( $this->mParams
['message'] ) ) {
1646 $msg = wfMessage( 'edittools' );
1648 $msg = wfMessage( $this->mParams
['message'] );
1649 if ( $msg->isDisabled() ) {
1650 $msg = wfMessage( 'edittools' );
1653 $msg->inContentLanguage();
1656 return '<tr><td></td><td class="mw-input">'
1657 . '<div class="mw-editTools">'
1658 . $msg->parseAsBlock()
1659 . "</div></td></tr>\n";