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; // <! RequestContext
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 RequestContext available since 1.18, will become compulsory in 1.19.
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, /*RequestContext*/ $context = null, $messagePrefix = '' ) {
123 if( $context instanceof RequestContext
){
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 $descriptor input Descriptor, as described above
183 * @return HTMLFormField subclass
185 static function loadInputFromParameters( $fieldname, $descriptor ) {
186 if ( isset( $descriptor['class'] ) ) {
187 $class = $descriptor['class'];
188 } elseif ( isset( $descriptor['type'] ) ) {
189 $class = self
::$typeMappings[$descriptor['type']];
190 $descriptor['class'] = $class;
196 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
199 $descriptor['fieldname'] = $fieldname;
201 $obj = new $class( $descriptor );
207 * Prepare form for submission
209 function prepareForm() {
210 # Check if we have the info we need
211 if ( !$this->mTitle
instanceof Title
&& $this->mTitle
!== false ) {
212 throw new MWException( "You must call setTitle() on an HTMLForm" );
215 # Load data from the request.
220 * Try submitting, with edit token check first
221 * @return Status|boolean
223 function tryAuthorizedSubmit() {
224 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
227 if ( $this->getMethod() != 'post' ||
$this->getUser()->matchEditToken( $editToken ) ) {
228 $result = $this->trySubmit();
234 * The here's-one-I-made-earlier option: do the submission if
235 * posted, or display the form with or without funky valiation
237 * @return Bool or Status whether submission was successful.
240 $this->prepareForm();
242 $result = $this->tryAuthorizedSubmit();
243 if ( $result === true ||
( $result instanceof Status
&& $result->isGood() ) ){
247 $this->displayForm( $result );
252 * Validate all the fields, and call the submision callback
253 * function if everything is kosher.
254 * @return Mixed Bool true == Successful submission, Bool false
255 * == No submission attempted, anything else == Error to
258 function trySubmit() {
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 ) {
374 # For good measure (it is the default)
375 $this->getOutput()->preventClickjacking();
376 $this->getOutput()->addModules( 'mediawiki.htmlform' );
379 . $this->getErrors( $submitResult )
382 . $this->getHiddenFields()
383 . $this->getButtons()
387 $html = $this->wrapForm( $html );
389 $this->getOutput()->addHTML( ''
397 * Wrap the form innards in an actual <form> element
398 * @param $html String HTML contents to wrap.
399 * @return String wrapped HTML.
401 function wrapForm( $html ) {
403 # Include a <fieldset> wrapper for style, if requested.
404 if ( $this->mWrapperLegend
!== false ) {
405 $html = Xml
::fieldset( $this->mWrapperLegend
, $html );
407 # Use multipart/form-data
408 $encType = $this->mUseMultipart
409 ?
'multipart/form-data'
410 : 'application/x-www-form-urlencoded';
413 'action' => $this->getTitle()->getFullURL(),
414 'method' => $this->mMethod
,
415 'class' => 'visualClear',
416 'enctype' => $encType,
418 if ( !empty( $this->mId
) ) {
419 $attribs['id'] = $this->mId
;
422 return Html
::rawElement( 'form', $attribs, $html );
426 * Get the hidden fields that should go inside the form.
427 * @return String HTML.
429 function getHiddenFields() {
431 if( $this->getMethod() == 'post' ){
432 $html .= Html
::hidden( 'wpEditToken', $this->getUser()->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
433 $html .= Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
436 foreach ( $this->mHiddenFields
as $data ) {
437 list( $value, $attribs ) = $data;
438 $html .= Html
::hidden( $attribs['name'], $value, $attribs ) . "\n";
445 * Get the submit and (potentially) reset buttons.
446 * @return String HTML.
448 function getButtons() {
452 if ( isset( $this->mSubmitID
) ) {
453 $attribs['id'] = $this->mSubmitID
;
456 if ( isset( $this->mSubmitName
) ) {
457 $attribs['name'] = $this->mSubmitName
;
460 if ( isset( $this->mSubmitTooltip
) ) {
461 $attribs +
= Linker
::tooltipAndAccessKeyAttribs( $this->mSubmitTooltip
);
464 $attribs['class'] = 'mw-htmlform-submit';
466 $html .= Xml
::submitButton( $this->getSubmitText(), $attribs ) . "\n";
468 if ( $this->mShowReset
) {
469 $html .= Html
::element(
473 'value' => wfMsg( 'htmlform-reset' )
478 foreach ( $this->mButtons
as $button ) {
481 'name' => $button['name'],
482 'value' => $button['value']
485 if ( $button['attribs'] ) {
486 $attrs +
= $button['attribs'];
489 if ( isset( $button['id'] ) ) {
490 $attrs['id'] = $button['id'];
493 $html .= Html
::element( 'input', $attrs );
500 * Get the whole body of the form.
503 return $this->displaySection( $this->mFieldTree
);
507 * Format and display an error message stack.
508 * @param $errors String|Array|Status
511 function getErrors( $errors ) {
512 if ( $errors instanceof Status
) {
513 if ( $errors->isOK() ) {
516 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
518 } elseif ( is_array( $errors ) ) {
519 $errorstr = $this->formatErrors( $errors );
525 ? Html
::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
530 * Format a stack of error messages into a single HTML string
531 * @param $errors Array of message keys/values
532 * @return String HTML, a <ul> list of errors
534 public static function formatErrors( $errors ) {
537 foreach ( $errors as $error ) {
538 if ( is_array( $error ) ) {
539 $msg = array_shift( $error );
545 $errorstr .= Html
::rawElement(
548 wfMsgExt( $msg, array( 'parseinline' ), $error )
552 $errorstr = Html
::rawElement( 'ul', array(), $errorstr );
558 * Set the text for the submit button
559 * @param $t String plaintext.
561 function setSubmitText( $t ) {
562 $this->mSubmitText
= $t;
566 * Get the text for the submit button, either customised or a default.
567 * @return unknown_type
569 function getSubmitText() {
570 return $this->mSubmitText
572 : wfMsg( 'htmlform-submit' );
575 public function setSubmitName( $name ) {
576 $this->mSubmitName
= $name;
579 public function setSubmitTooltip( $name ) {
580 $this->mSubmitTooltip
= $name;
584 * Set the id for the submit button.
586 * @todo FIXME: Integrity of $t is *not* validated
588 function setSubmitID( $t ) {
589 $this->mSubmitID
= $t;
592 public function setId( $id ) {
596 * Prompt the whole form to be wrapped in a <fieldset>, with
597 * this text as its <legend> element.
598 * @param $legend String HTML to go inside the <legend> element.
601 public function setWrapperLegend( $legend ) { $this->mWrapperLegend
= $legend; }
604 * Set the prefix for various default messages
605 * TODO: currently only used for the <fieldset> legend on forms
606 * with multiple sections; should be used elsewhre?
609 function setMessagePrefix( $p ) {
610 $this->mMessagePrefix
= $p;
614 * Set the title for form submission
615 * @param $t Title of page the form is on/should be posted to
617 function setTitle( $t ) {
625 function getTitle() {
626 return $this->mTitle
=== false
627 ?
$this->getContext()->title
632 * @return RequestContext
634 public function getContext(){
635 return $this->mContext
instanceof RequestContext
637 : RequestContext
::getMain();
643 public function getOutput(){
644 return $this->getContext()->output
;
650 public function getRequest(){
651 return $this->getContext()->request
;
657 public function getUser(){
658 return $this->getContext()->user
;
662 * Set the method used to submit the form
663 * @param $method String
665 public function setMethod( $method='post' ){
666 $this->mMethod
= $method;
669 public function getMethod(){
670 return $this->mMethod
;
677 function displaySection( $fields, $sectionName = '' ) {
679 $subsectionHtml = '';
680 $hasLeftColumn = false;
682 foreach ( $fields as $key => $value ) {
683 if ( is_object( $value ) ) {
684 $v = empty( $value->mParams
['nodata'] )
685 ?
$this->mFieldData
[$key]
686 : $value->getDefault();
687 $tableHtml .= $value->getTableRow( $v );
689 if ( $value->getLabel() != ' ' )
690 $hasLeftColumn = true;
691 } elseif ( is_array( $value ) ) {
692 $section = $this->displaySection( $value, $key );
693 $legend = $this->getLegend( $key );
694 if ( isset( $this->mSectionHeaders
[$key] ) ) {
695 $section = $this->mSectionHeaders
[$key] . $section;
697 if ( isset( $this->mSectionFooters
[$key] ) ) {
698 $section .= $this->mSectionFooters
[$key];
700 $subsectionHtml .= Xml
::fieldset( $legend, $section ) . "\n";
706 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
707 $classes[] = 'mw-htmlform-nolabel';
711 'class' => implode( ' ', $classes ),
714 if ( $sectionName ) {
715 $attribs['id'] = Sanitizer
::escapeId( "mw-htmlform-$sectionName" );
718 $tableHtml = Html
::rawElement( 'table', $attribs,
719 Html
::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
721 return $subsectionHtml . "\n" . $tableHtml;
725 * Construct the form fields from the Descriptor array
727 function loadData() {
728 $fieldData = array();
730 foreach ( $this->mFlatFields
as $fieldname => $field ) {
731 if ( !empty( $field->mParams
['nodata'] ) ) {
733 } elseif ( !empty( $field->mParams
['disabled'] ) ) {
734 $fieldData[$fieldname] = $field->getDefault();
736 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
741 foreach ( $fieldData as $name => &$value ) {
742 $field = $this->mFlatFields
[$name];
743 $value = $field->filter( $value, $this->mFlatFields
);
746 $this->mFieldData
= $fieldData;
750 * Stop a reset button being shown for this form
751 * @param $suppressReset Bool set to false to re-enable the
754 function suppressReset( $suppressReset = true ) {
755 $this->mShowReset
= !$suppressReset;
759 * Overload this if you want to apply special filtration routines
760 * to the form as a whole, after it's submitted but before it's
763 * @return unknown_type
765 function filterDataForSubmit( $data ) {
770 * Get a string to go in the <legend> of a section fieldset. Override this if you
771 * want something more complicated
775 public function getLegend( $key ) {
776 return wfMsg( "{$this->mMessagePrefix}-$key" );
781 * The parent class to generate form fields. Any field type should
782 * be a subclass of this.
784 abstract class HTMLFormField
{
786 protected $mValidationCallback;
787 protected $mFilterCallback;
790 protected $mLabel; # String label. Set on construction
792 protected $mClass = '';
801 * This function must be implemented to return the HTML to generate
802 * the input object itself. It should not implement the surrounding
803 * table cells/rows, or labels/help messages.
804 * @param $value String the value to set the input to; eg a default
805 * text for a text input.
806 * @return String valid HTML.
808 abstract function getInputHTML( $value );
811 * Override this function to add specific validation checks on the
812 * field input. Don't forget to call parent::validate() to ensure
813 * that the user-defined callback mValidationCallback is still run
814 * @param $value String the value the field was submitted with
815 * @param $alldata Array the data collected from the form
816 * @return Mixed Bool true on success, or String error to display.
818 function validate( $value, $alldata ) {
819 if ( isset( $this->mValidationCallback
) ) {
820 return call_user_func( $this->mValidationCallback
, $value, $alldata );
823 if ( isset( $this->mParams
['required'] ) && $value === '' ) {
824 return wfMsgExt( 'htmlform-required', 'parseinline' );
830 function filter( $value, $alldata ) {
831 if ( isset( $this->mFilterCallback
) ) {
832 $value = call_user_func( $this->mFilterCallback
, $value, $alldata );
839 * Should this field have a label, or is there no input element with the
840 * appropriate id for the label to point to?
842 * @return bool True to output a label, false to suppress
844 protected function needsLabel() {
849 * Get the value that this input has been set to from a posted form,
850 * or the input's default value if it has not been set.
851 * @param $request WebRequest
852 * @return String the value
854 function loadDataFromRequest( $request ) {
855 if ( $request->getCheck( $this->mName
) ) {
856 return $request->getText( $this->mName
);
858 return $this->getDefault();
863 * Initialise the object
864 * @param $params array Associative Array. See HTMLForm doc for syntax.
866 function __construct( $params ) {
867 $this->mParams
= $params;
869 # Generate the label from a message, if possible
870 if ( isset( $params['label-message'] ) ) {
871 $msgInfo = $params['label-message'];
873 if ( is_array( $msgInfo ) ) {
874 $msg = array_shift( $msgInfo );
880 $this->mLabel
= wfMsgExt( $msg, 'parseinline', $msgInfo );
881 } elseif ( isset( $params['label'] ) ) {
882 $this->mLabel
= $params['label'];
885 $this->mName
= "wp{$params['fieldname']}";
886 if ( isset( $params['name'] ) ) {
887 $this->mName
= $params['name'];
890 $validName = Sanitizer
::escapeId( $this->mName
);
891 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
892 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
895 $this->mID
= "mw-input-{$this->mName}";
897 if ( isset( $params['default'] ) ) {
898 $this->mDefault
= $params['default'];
901 if ( isset( $params['id'] ) ) {
903 $validId = Sanitizer
::escapeId( $id );
905 if ( $id != $validId ) {
906 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
912 if ( isset( $params['cssclass'] ) ) {
913 $this->mClass
= $params['cssclass'];
916 if ( isset( $params['validation-callback'] ) ) {
917 $this->mValidationCallback
= $params['validation-callback'];
920 if ( isset( $params['filter-callback'] ) ) {
921 $this->mFilterCallback
= $params['filter-callback'];
926 * Get the complete table row for the input, including help text,
927 * labels, and whatever.
928 * @param $value String the value to set the input to.
929 * @return String complete HTML table row.
931 function getTableRow( $value ) {
932 # Check for invalid data.
934 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
936 $cellAttributes = array();
937 $verticalLabel = false;
939 if ( !empty($this->mParams
['vertical-label']) ) {
940 $cellAttributes['colspan'] = 2;
941 $verticalLabel = true;
944 if ( $errors === true ||
( !$this->mParent
->getRequest()->wasPosted() && ( $this->mParent
->getMethod() == 'post' ) ) ) {
948 $errors = self
::formatErrors( $errors );
949 $errorClass = 'mw-htmlform-invalid-input';
952 $label = $this->getLabelHtml( $cellAttributes );
953 $field = Html
::rawElement(
955 array( 'class' => 'mw-input' ) +
$cellAttributes,
956 $this->getInputHTML( $value ) . "\n$errors"
959 $fieldType = get_class( $this );
961 if ( $verticalLabel ) {
962 $html = Html
::rawElement( 'tr',
963 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
964 $html .= Html
::rawElement( 'tr',
965 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
968 $html = Html
::rawElement( 'tr',
969 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
975 if ( isset( $this->mParams
['help-message'] ) ) {
976 $msg = wfMessage( $this->mParams
['help-message'] );
977 if ( $msg->exists() ) {
978 $helptext = $msg->parse();
980 } elseif ( isset( $this->mParams
['help-messages'] ) ) {
981 # help-message can be passed a message key (string) or an array containing
982 # a message key and additional parameters. This makes it impossible to pass
983 # an array of message key
984 foreach( $this->mParams
['help-messages'] as $name ) {
985 $msg = wfMessage( $name );
986 if( $msg->exists() ) {
987 $helptext .= $msg->parse(); // append message
990 } elseif ( isset( $this->mParams
['help'] ) ) {
991 $helptext = $this->mParams
['help'];
994 if ( !is_null( $helptext ) ) {
995 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
997 $row = Html
::rawElement( 'tr', array(), $row );
1004 function getLabel() {
1005 return $this->mLabel
;
1007 function getLabelHtml( $cellAttributes = array() ) {
1008 # Don't output a for= attribute for labels with no associated input.
1009 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1012 if ( $this->needsLabel() ) {
1013 $for['for'] = $this->mID
;
1016 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes,
1017 Html
::rawElement( 'label', $for, $this->getLabel() )
1021 function getDefault() {
1022 if ( isset( $this->mDefault
) ) {
1023 return $this->mDefault
;
1030 * Returns the attributes required for the tooltip and accesskey.
1032 * @return array Attributes
1034 public function getTooltipAndAccessKey() {
1035 if ( empty( $this->mParams
['tooltip'] ) ) {
1038 return Linker
::tooltipAndAccessKeyAttribs( $this->mParams
['tooltip'] );
1042 * flatten an array of options to a single array, for instance,
1043 * a set of <options> inside <optgroups>.
1044 * @param $options Associative Array with values either Strings
1046 * @return Array flattened input
1048 public static function flattenOptions( $options ) {
1049 $flatOpts = array();
1051 foreach ( $options as $value ) {
1052 if ( is_array( $value ) ) {
1053 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1055 $flatOpts[] = $value;
1063 * Formats one or more errors as accepted by field validation-callback.
1064 * @param $errors String|Message|Array of strings or Message instances
1065 * @return String html
1068 protected static function formatErrors( $errors ) {
1069 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1070 $errors = array_shift( $errors );
1073 if ( is_array( $errors ) ) {
1075 foreach ( $errors as $error ) {
1076 if ( $error instanceof Message
) {
1077 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
1079 $lines[] = Html
::rawElement( 'li', array(), $error );
1082 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1084 if ( $errors instanceof Message
) {
1085 $errors = $errors->parse();
1087 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );
1092 class HTMLTextField
extends HTMLFormField
{
1093 function getSize() {
1094 return isset( $this->mParams
['size'] )
1095 ?
$this->mParams
['size']
1099 function getInputHTML( $value ) {
1102 'name' => $this->mName
,
1103 'size' => $this->getSize(),
1105 ) +
$this->getTooltipAndAccessKey();
1107 if ( isset( $this->mParams
['maxlength'] ) ) {
1108 $attribs['maxlength'] = $this->mParams
['maxlength'];
1111 if ( !empty( $this->mParams
['disabled'] ) ) {
1112 $attribs['disabled'] = 'disabled';
1115 # TODO: Enforce pattern, step, required, readonly on the server side as
1117 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1118 'placeholder' ) as $param ) {
1119 if ( isset( $this->mParams
[$param] ) ) {
1120 $attribs[$param] = $this->mParams
[$param];
1124 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1125 if ( isset( $this->mParams
[$param] ) ) {
1126 $attribs[$param] = '';
1130 # Implement tiny differences between some field variants
1131 # here, rather than creating a new class for each one which
1132 # is essentially just a clone of this one.
1133 if ( isset( $this->mParams
['type'] ) ) {
1134 switch ( $this->mParams
['type'] ) {
1136 $attribs['type'] = 'email';
1139 $attribs['type'] = 'number';
1142 $attribs['type'] = 'number';
1143 $attribs['step'] = 'any';
1148 $attribs['type'] = $this->mParams
['type'];
1153 return Html
::element( 'input', $attribs );
1156 class HTMLTextAreaField
extends HTMLFormField
{
1157 function getCols() {
1158 return isset( $this->mParams
['cols'] )
1159 ?
$this->mParams
['cols']
1163 function getRows() {
1164 return isset( $this->mParams
['rows'] )
1165 ?
$this->mParams
['rows']
1169 function getInputHTML( $value ) {
1172 'name' => $this->mName
,
1173 'cols' => $this->getCols(),
1174 'rows' => $this->getRows(),
1175 ) +
$this->getTooltipAndAccessKey();
1178 if ( !empty( $this->mParams
['disabled'] ) ) {
1179 $attribs['disabled'] = 'disabled';
1182 if ( !empty( $this->mParams
['readonly'] ) ) {
1183 $attribs['readonly'] = 'readonly';
1186 foreach ( array( 'required', 'autofocus' ) as $param ) {
1187 if ( isset( $this->mParams
[$param] ) ) {
1188 $attribs[$param] = '';
1192 return Html
::element( 'textarea', $attribs, $value );
1197 * A field that will contain a numeric value
1199 class HTMLFloatField
extends HTMLTextField
{
1200 function getSize() {
1201 return isset( $this->mParams
['size'] )
1202 ?
$this->mParams
['size']
1206 function validate( $value, $alldata ) {
1207 $p = parent
::validate( $value, $alldata );
1209 if ( $p !== true ) {
1213 $value = trim( $value );
1215 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1216 # with the addition that a leading '+' sign is ok.
1217 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1218 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1221 # The "int" part of these message names is rather confusing.
1222 # They make equal sense for all numbers.
1223 if ( isset( $this->mParams
['min'] ) ) {
1224 $min = $this->mParams
['min'];
1226 if ( $min > $value ) {
1227 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1231 if ( isset( $this->mParams
['max'] ) ) {
1232 $max = $this->mParams
['max'];
1234 if ( $max < $value ) {
1235 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1244 * A field that must contain a number
1246 class HTMLIntField
extends HTMLFloatField
{
1247 function validate( $value, $alldata ) {
1248 $p = parent
::validate( $value, $alldata );
1250 if ( $p !== true ) {
1254 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1255 # with the addition that a leading '+' sign is ok. Note that leading zeros
1256 # are fine, and will be left in the input, which is useful for things like
1257 # phone numbers when you know that they are integers (the HTML5 type=tel
1258 # input does not require its value to be numeric). If you want a tidier
1259 # value to, eg, save in the DB, clean it up with intval().
1260 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1262 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1272 class HTMLCheckField
extends HTMLFormField
{
1273 function getInputHTML( $value ) {
1274 if ( !empty( $this->mParams
['invert'] ) ) {
1278 $attr = $this->getTooltipAndAccessKey();
1279 $attr['id'] = $this->mID
;
1281 if ( !empty( $this->mParams
['disabled'] ) ) {
1282 $attr['disabled'] = 'disabled';
1285 return Xml
::check( $this->mName
, $value, $attr ) . ' ' .
1286 Html
::rawElement( 'label', array( 'for' => $this->mID
), $this->mLabel
);
1290 * For a checkbox, the label goes on the right hand side, and is
1291 * added in getInputHTML(), rather than HTMLFormField::getRow()
1293 function getLabel() {
1298 * @param $request WebRequest
1301 function loadDataFromRequest( $request ) {
1303 if ( isset( $this->mParams
['invert'] ) && $this->mParams
['invert'] ) {
1307 // GetCheck won't work like we want for checks.
1308 if ( $request->getCheck( 'wpEditToken' ) ||
$this->mParent
->getMethod() != 'post' ) {
1309 // XOR has the following truth table, which is what we want
1310 // INVERT VALUE | OUTPUT
1311 // true true | false
1312 // false true | true
1313 // false false | false
1314 // true false | true
1315 return $request->getBool( $this->mName
) xor $invert;
1317 return $this->getDefault();
1323 * A select dropdown field. Basically a wrapper for Xmlselect class
1325 class HTMLSelectField
extends HTMLFormField
{
1326 function validate( $value, $alldata ) {
1327 $p = parent
::validate( $value, $alldata );
1329 if ( $p !== true ) {
1333 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1335 if ( in_array( $value, $validOptions ) )
1338 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1341 function getInputHTML( $value ) {
1342 $select = new XmlSelect( $this->mName
, $this->mID
, strval( $value ) );
1344 # If one of the options' 'name' is int(0), it is automatically selected.
1345 # because PHP sucks and thinks int(0) == 'some string'.
1346 # Working around this by forcing all of them to strings.
1347 foreach( $this->mParams
['options'] as &$opt ){
1348 if( is_int( $opt ) ){
1349 $opt = strval( $opt );
1352 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1354 if ( !empty( $this->mParams
['disabled'] ) ) {
1355 $select->setAttribute( 'disabled', 'disabled' );
1358 $select->addOptions( $this->mParams
['options'] );
1360 return $select->getHTML();
1365 * Select dropdown field, with an additional "other" textbox.
1367 class HTMLSelectOrOtherField
extends HTMLTextField
{
1368 static $jsAdded = false;
1370 function __construct( $params ) {
1371 if ( !in_array( 'other', $params['options'], true ) ) {
1372 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1375 parent
::__construct( $params );
1378 static function forceToStringRecursive( $array ) {
1379 if ( is_array( $array ) ) {
1380 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
1382 return strval( $array );
1386 function getInputHTML( $value ) {
1387 $valInSelect = false;
1389 if ( $value !== false ) {
1390 $valInSelect = in_array(
1392 HTMLFormField
::flattenOptions( $this->mParams
['options'] )
1396 $selected = $valInSelect ?
$value : 'other';
1398 $opts = self
::forceToStringRecursive( $this->mParams
['options'] );
1400 $select = new XmlSelect( $this->mName
, $this->mID
, $selected );
1401 $select->addOptions( $opts );
1403 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1405 $tbAttribs = array( 'id' => $this->mID
. '-other', 'size' => $this->getSize() );
1407 if ( !empty( $this->mParams
['disabled'] ) ) {
1408 $select->setAttribute( 'disabled', 'disabled' );
1409 $tbAttribs['disabled'] = 'disabled';
1412 $select = $select->getHTML();
1414 if ( isset( $this->mParams
['maxlength'] ) ) {
1415 $tbAttribs['maxlength'] = $this->mParams
['maxlength'];
1418 $textbox = Html
::input(
1419 $this->mName
. '-other',
1420 $valInSelect ?
'' : $value,
1425 return "$select<br />\n$textbox";
1429 * @param $request WebRequest
1432 function loadDataFromRequest( $request ) {
1433 if ( $request->getCheck( $this->mName
) ) {
1434 $val = $request->getText( $this->mName
);
1436 if ( $val == 'other' ) {
1437 $val = $request->getText( $this->mName
. '-other' );
1442 return $this->getDefault();
1448 * Multi-select field
1450 class HTMLMultiSelectField
extends HTMLFormField
{
1452 public function __construct( $params ){
1453 parent
::__construct( $params );
1454 if( isset( $params['flatlist'] ) ){
1455 $this->mClass
.= ' mw-htmlform-multiselect-flatlist';
1459 function validate( $value, $alldata ) {
1460 $p = parent
::validate( $value, $alldata );
1462 if ( $p !== true ) {
1466 if ( !is_array( $value ) ) {
1470 # If all options are valid, array_intersect of the valid options
1471 # and the provided options will return the provided options.
1472 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1474 $validValues = array_intersect( $value, $validOptions );
1475 if ( count( $validValues ) == count( $value ) ) {
1478 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1482 function getInputHTML( $value ) {
1483 $html = $this->formatOptions( $this->mParams
['options'], $value );
1488 function formatOptions( $options, $value ) {
1493 if ( !empty( $this->mParams
['disabled'] ) ) {
1494 $attribs['disabled'] = 'disabled';
1497 foreach ( $options as $label => $info ) {
1498 if ( is_array( $info ) ) {
1499 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1500 $html .= $this->formatOptions( $info, $value );
1502 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1504 $checkbox = Xml
::check(
1505 $this->mName
. '[]',
1506 in_array( $info, $value, true ),
1507 $attribs +
$thisAttribs );
1508 $checkbox .= ' ' . Html
::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1510 $html .= ' ' . Html
::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
1518 * @param $request WebRequest
1521 function loadDataFromRequest( $request ) {
1522 if ( $this->mParent
->getMethod() == 'post' ) {
1523 if( $request->wasPosted() ){
1524 # Checkboxes are just not added to the request arrays if they're not checked,
1525 # so it's perfectly possible for there not to be an entry at all
1526 return $request->getArray( $this->mName
, array() );
1528 # That's ok, the user has not yet submitted the form, so show the defaults
1529 return $this->getDefault();
1532 # This is the impossible case: if we look at $_GET and see no data for our
1533 # field, is it because the user has not yet submitted the form, or that they
1534 # have submitted it with all the options unchecked? We will have to assume the
1535 # latter, which basically means that you can't specify 'positive' defaults
1538 return $request->getArray( $this->mName
, array() );
1542 function getDefault() {
1543 if ( isset( $this->mDefault
) ) {
1544 return $this->mDefault
;
1550 protected function needsLabel() {
1556 * Double field with a dropdown list constructed from a system message in the format
1558 * ** <option value>|<option name>
1559 * ** <option value == option name>
1560 * * New Optgroup header
1561 * Plus a text field underneath for an additional reason. The 'value' of the field is
1562 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1564 * @todo FIXME: If made 'required', only the text field should be compulsory.
1566 class HTMLSelectAndOtherField
extends HTMLSelectField
{
1568 function __construct( $params ) {
1569 if ( array_key_exists( 'other', $params ) ) {
1570 } elseif( array_key_exists( 'other-message', $params ) ){
1571 $params['other'] = wfMsg( $params['other-message'] );
1573 $params['other'] = wfMsg( 'htmlform-selectorother-other' );
1576 if ( array_key_exists( 'options', $params ) ) {
1577 # Options array already specified
1578 } elseif( array_key_exists( 'options-message', $params ) ){
1579 # Generate options array from a system message
1580 $params['options'] = self
::parseMessage( wfMsg( $params['options-message'], $params['other'] ) );
1583 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1585 $this->mFlatOptions
= self
::flattenOptions( $params['options'] );
1587 parent
::__construct( $params );
1591 * Build a drop-down box from a textual list.
1592 * @param $string String message text
1593 * @param $otherName String name of "other reason" option
1595 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1597 public static function parseMessage( $string, $otherName=null ) {
1598 if( $otherName === null ){
1599 $otherName = wfMsg( 'htmlform-selectorother-other' );
1603 $options = array( $otherName => 'other' );
1605 foreach ( explode( "\n", $string ) as $option ) {
1606 $value = trim( $option );
1607 if ( $value == '' ) {
1609 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1610 # A new group is starting...
1611 $value = trim( substr( $value, 1 ) );
1613 } elseif ( substr( $value, 0, 2) == '**' ) {
1615 $opt = trim( substr( $value, 2 ) );
1616 $parts = array_map( 'trim', explode( '|', $opt, 2 ) );
1617 if( count( $parts ) === 1 ){
1618 $parts[1] = $parts[0];
1620 if( $optgroup === false ){
1621 $options[$parts[1]] = $parts[0];
1623 $options[$optgroup][$parts[1]] = $parts[0];
1626 # groupless reason list
1628 $parts = array_map( 'trim', explode( '|', $option, 2 ) );
1629 if( count( $parts ) === 1 ){
1630 $parts[1] = $parts[0];
1632 $options[$parts[1]] = $parts[0];
1639 function getInputHTML( $value ) {
1640 $select = parent
::getInputHTML( $value[1] );
1642 $textAttribs = array(
1643 'id' => $this->mID
. '-other',
1644 'size' => $this->getSize(),
1647 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1648 if ( isset( $this->mParams
[$param] ) ) {
1649 $textAttribs[$param] = '';
1653 $textbox = Html
::input(
1654 $this->mName
. '-other',
1660 return "$select<br />\n$textbox";
1664 * @param $request WebRequest
1665 * @return Array( <overall message>, <select value>, <text field value> )
1667 function loadDataFromRequest( $request ) {
1668 if ( $request->getCheck( $this->mName
) ) {
1670 $list = $request->getText( $this->mName
);
1671 $text = $request->getText( $this->mName
. '-other' );
1673 if ( $list == 'other' ) {
1675 } elseif( !in_array( $list, $this->mFlatOptions
) ){
1676 # User has spoofed the select form to give an option which wasn't
1677 # in the original offer. Sulk...
1679 } elseif( $text == '' ) {
1682 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1686 $final = $this->getDefault();
1689 return array( $final, $list, $text );
1692 function getSize() {
1693 return isset( $this->mParams
['size'] )
1694 ?
$this->mParams
['size']
1698 function validate( $value, $alldata ) {
1699 # HTMLSelectField forces $value to be one of the options in the select
1700 # field, which is not useful here. But we do want the validation further up
1702 $p = parent
::validate( $value[1], $alldata );
1704 if ( $p !== true ) {
1708 if( isset( $this->mParams
['required'] ) && $value[1] === '' ){
1709 return wfMsgExt( 'htmlform-required', 'parseinline' );
1717 * Radio checkbox fields.
1719 class HTMLRadioField
extends HTMLFormField
{
1720 function validate( $value, $alldata ) {
1721 $p = parent
::validate( $value, $alldata );
1723 if ( $p !== true ) {
1727 if ( !is_string( $value ) && !is_int( $value ) ) {
1731 $validOptions = HTMLFormField
::flattenOptions( $this->mParams
['options'] );
1733 if ( in_array( $value, $validOptions ) ) {
1736 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1741 * This returns a block of all the radio options, in one cell.
1742 * @see includes/HTMLFormField#getInputHTML()
1744 function getInputHTML( $value ) {
1745 $html = $this->formatOptions( $this->mParams
['options'], $value );
1750 function formatOptions( $options, $value ) {
1754 if ( !empty( $this->mParams
['disabled'] ) ) {
1755 $attribs['disabled'] = 'disabled';
1758 # TODO: should this produce an unordered list perhaps?
1759 foreach ( $options as $label => $info ) {
1760 if ( is_array( $info ) ) {
1761 $html .= Html
::rawElement( 'h1', array(), $label ) . "\n";
1762 $html .= $this->formatOptions( $info, $value );
1764 $id = Sanitizer
::escapeId( $this->mID
. "-$info" );
1765 $html .= Xml
::radio(
1769 $attribs +
array( 'id' => $id )
1772 Html
::rawElement( 'label', array( 'for' => $id ), $label );
1774 $html .= "<br />\n";
1781 protected function needsLabel() {
1787 * An information field (text blob), not a proper input.
1789 class HTMLInfoField
extends HTMLFormField
{
1790 function __construct( $info ) {
1791 $info['nodata'] = true;
1793 parent
::__construct( $info );
1796 function getInputHTML( $value ) {
1797 return !empty( $this->mParams
['raw'] ) ?
$value : htmlspecialchars( $value );
1800 function getTableRow( $value ) {
1801 if ( !empty( $this->mParams
['rawrow'] ) ) {
1805 return parent
::getTableRow( $value );
1808 protected function needsLabel() {
1813 class HTMLHiddenField
extends HTMLFormField
{
1814 public function __construct( $params ) {
1815 parent
::__construct( $params );
1817 # Per HTML5 spec, hidden fields cannot be 'required'
1818 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1819 unset( $this->mParams
['required'] );
1822 public function getTableRow( $value ) {
1825 $params['id'] = $this->mID
;
1828 $this->mParent
->addHiddenField(
1837 public function getInputHTML( $value ) { return ''; }
1841 * Add a submit button inline in the form (as opposed to
1842 * HTMLForm::addButton(), which will add it at the end).
1844 class HTMLSubmitField
extends HTMLFormField
{
1846 function __construct( $info ) {
1847 $info['nodata'] = true;
1848 parent
::__construct( $info );
1851 function getInputHTML( $value ) {
1852 return Xml
::submitButton(
1855 'class' => 'mw-htmlform-submit',
1856 'name' => $this->mName
,
1862 protected function needsLabel() {
1867 * Button cannot be invalid
1869 public function validate( $value, $alldata ){
1874 class HTMLEditTools
extends HTMLFormField
{
1875 public function getInputHTML( $value ) {
1879 public function getTableRow( $value ) {
1880 if ( empty( $this->mParams
['message'] ) ) {
1881 $msg = wfMessage( 'edittools' );
1883 $msg = wfMessage( $this->mParams
['message'] );
1884 if ( $msg->isDisabled() ) {
1885 $msg = wfMessage( 'edittools' );
1888 $msg->inContentLanguage();
1891 return '<tr><td></td><td class="mw-input">'
1892 . '<div class="mw-editTools">'
1893 . $msg->parseAsBlock()
1894 . "</div></td></tr>\n";