RN populateSha1.php renamed (r94291)
[mediawiki.git] / includes / HTMLForm.php
blobe9eacccd4682569ebf3fc0dbd9877d52eb3e0d0a
1 <?php
2 /**
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
30 * the message.
31 * 'label' -- alternatively, a raw text message. Overridden by
32 * label-message
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
35 * the message.
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
56 class HTMLForm {
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;
87 public $mFieldData;
89 protected $mSubmitCallback;
90 protected $mValidationErrorMessage;
92 protected $mPre = '';
93 protected $mHeader = '';
94 protected $mFooter = '';
95 protected $mSectionHeaders = array();
96 protected $mSectionFooters = array();
97 protected $mPost = '';
98 protected $mId;
100 protected $mSubmitID;
101 protected $mSubmitName;
102 protected $mSubmitText;
103 protected $mSubmitTooltip;
105 protected $mContext; // <! RequestContext
106 protected $mTitle;
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.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, /*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;
127 } else {
128 // B/C since 1.18
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'] )
141 ? $info['section']
142 : '';
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;
152 if ( $section ) {
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
175 * done already.
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;
192 } else {
193 $class = null;
196 if ( !$class ) {
197 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
200 $descriptor['fieldname'] = $fieldname;
202 $obj = new $class( $descriptor );
204 return $obj;
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.
217 $this->loadData();
221 * Try submitting, with edit token check first
222 * @return Status|boolean
224 function tryAuthorizedSubmit() {
225 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
227 $result = false;
228 if ( $this->getMethod() != 'post' || $this->getUser()->matchEditToken( $editToken ) ) {
229 $result = $this->trySubmit();
231 return $result;
235 * The here's-one-I-made-earlier option: do the submission if
236 * posted, or display the form with or without funky valiation
237 * errors
238 * @return Bool or Status whether submission was successful.
240 function show() {
241 $this->prepareForm();
243 $result = $this->tryAuthorizedSubmit();
244 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ){
245 return $result;
248 $this->displayForm( $result );
249 return false;
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
257 * display.
259 function trySubmit() {
260 # Check for validation
261 foreach ( $this->mFlatFields as $fieldname => $field ) {
262 if ( !empty( $field->mParams['nodata'] ) ) {
263 continue;
265 if ( $field->validate(
266 $this->mFieldData[$fieldname],
267 $this->mFieldData )
268 !== true
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 );
282 return $res;
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;
326 } else {
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;
342 } else {
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 # For good measure (it is the default)
378 $this->getOutput()->preventClickjacking();
379 $this->getOutput()->addModules( 'mediawiki.htmlform' );
381 $html = ''
382 . $this->getErrors( $submitResult )
383 . $this->mHeader
384 . $this->getBody()
385 . $this->getHiddenFields()
386 . $this->getButtons()
387 . $this->mFooter
390 $html = $this->wrapForm( $html );
392 $this->getOutput()->addHTML( ''
393 . $this->mPre
394 . $html
395 . $this->mPost
400 * Wrap the form innards in an actual <form> element
401 * @param $html String HTML contents to wrap.
402 * @return String wrapped HTML.
404 function wrapForm( $html ) {
406 # Include a <fieldset> wrapper for style, if requested.
407 if ( $this->mWrapperLegend !== false ) {
408 $html = Xml::fieldset( $this->mWrapperLegend, $html );
410 # Use multipart/form-data
411 $encType = $this->mUseMultipart
412 ? 'multipart/form-data'
413 : 'application/x-www-form-urlencoded';
414 # Attributes
415 $attribs = array(
416 'action' => $this->getTitle()->getFullURL(),
417 'method' => $this->mMethod,
418 'class' => 'visualClear',
419 'enctype' => $encType,
421 if ( !empty( $this->mId ) ) {
422 $attribs['id'] = $this->mId;
425 return Html::rawElement( 'form', $attribs, $html );
429 * Get the hidden fields that should go inside the form.
430 * @return String HTML.
432 function getHiddenFields() {
433 $html = '';
434 if( $this->getMethod() == 'post' ){
435 $html .= Html::hidden( 'wpEditToken', $this->getUser()->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
436 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
439 foreach ( $this->mHiddenFields as $data ) {
440 list( $value, $attribs ) = $data;
441 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
444 return $html;
448 * Get the submit and (potentially) reset buttons.
449 * @return String HTML.
451 function getButtons() {
452 $html = '';
453 $attribs = array();
455 if ( isset( $this->mSubmitID ) ) {
456 $attribs['id'] = $this->mSubmitID;
459 if ( isset( $this->mSubmitName ) ) {
460 $attribs['name'] = $this->mSubmitName;
463 if ( isset( $this->mSubmitTooltip ) ) {
464 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
467 $attribs['class'] = 'mw-htmlform-submit';
469 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
471 if ( $this->mShowReset ) {
472 $html .= Html::element(
473 'input',
474 array(
475 'type' => 'reset',
476 'value' => wfMsg( 'htmlform-reset' )
478 ) . "\n";
481 foreach ( $this->mButtons as $button ) {
482 $attrs = array(
483 'type' => 'submit',
484 'name' => $button['name'],
485 'value' => $button['value']
488 if ( $button['attribs'] ) {
489 $attrs += $button['attribs'];
492 if ( isset( $button['id'] ) ) {
493 $attrs['id'] = $button['id'];
496 $html .= Html::element( 'input', $attrs );
499 return $html;
503 * Get the whole body of the form.
505 function getBody() {
506 return $this->displaySection( $this->mFieldTree );
510 * Format and display an error message stack.
511 * @param $errors String|Array|Status
512 * @return String
514 function getErrors( $errors ) {
515 if ( $errors instanceof Status ) {
516 if ( $errors->isOK() ) {
517 $errorstr = '';
518 } else {
519 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
521 } elseif ( is_array( $errors ) ) {
522 $errorstr = $this->formatErrors( $errors );
523 } else {
524 $errorstr = $errors;
527 return $errorstr
528 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
529 : '';
533 * Format a stack of error messages into a single HTML string
534 * @param $errors Array of message keys/values
535 * @return String HTML, a <ul> list of errors
537 public static function formatErrors( $errors ) {
538 $errorstr = '';
540 foreach ( $errors as $error ) {
541 if ( is_array( $error ) ) {
542 $msg = array_shift( $error );
543 } else {
544 $msg = $error;
545 $error = array();
548 $errorstr .= Html::rawElement(
549 'li',
550 array(),
551 wfMsgExt( $msg, array( 'parseinline' ), $error )
555 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
557 return $errorstr;
561 * Set the text for the submit button
562 * @param $t String plaintext.
564 function setSubmitText( $t ) {
565 $this->mSubmitText = $t;
569 * Get the text for the submit button, either customised or a default.
570 * @return unknown_type
572 function getSubmitText() {
573 return $this->mSubmitText
574 ? $this->mSubmitText
575 : wfMsg( 'htmlform-submit' );
578 public function setSubmitName( $name ) {
579 $this->mSubmitName = $name;
582 public function setSubmitTooltip( $name ) {
583 $this->mSubmitTooltip = $name;
587 * Set the id for the submit button.
588 * @param $t String.
589 * @todo FIXME: Integrity of $t is *not* validated
591 function setSubmitID( $t ) {
592 $this->mSubmitID = $t;
595 public function setId( $id ) {
596 $this->mId = $id;
599 * Prompt the whole form to be wrapped in a <fieldset>, with
600 * this text as its <legend> element.
601 * @param $legend String HTML to go inside the <legend> element.
602 * Will be escaped
604 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
607 * Set the prefix for various default messages
608 * TODO: currently only used for the <fieldset> legend on forms
609 * with multiple sections; should be used elsewhre?
610 * @param $p String
612 function setMessagePrefix( $p ) {
613 $this->mMessagePrefix = $p;
617 * Set the title for form submission
618 * @param $t Title of page the form is on/should be posted to
620 function setTitle( $t ) {
621 $this->mTitle = $t;
625 * Get the title
626 * @return Title
628 function getTitle() {
629 return $this->mTitle === false
630 ? $this->getContext()->getTitle()
631 : $this->mTitle;
635 * @return RequestContext
637 public function getContext(){
638 return $this->mContext instanceof RequestContext
639 ? $this->mContext
640 : RequestContext::getMain();
644 * @return OutputPage
646 public function getOutput(){
647 return $this->getContext()->getOutput();
651 * @return WebRequest
653 public function getRequest(){
654 return $this->getContext()->getRequest();
658 * @return User
660 public function getUser(){
661 return $this->getContext()->getUser();
665 * Set the method used to submit the form
666 * @param $method String
668 public function setMethod( $method='post' ){
669 $this->mMethod = $method;
672 public function getMethod(){
673 return $this->mMethod;
677 * TODO: Document
678 * @param $fields
680 function displaySection( $fields, $sectionName = '', $displayTitle = false ) {
681 $tableHtml = '';
682 $subsectionHtml = '';
683 $hasLeftColumn = false;
685 foreach ( $fields as $key => $value ) {
686 if ( is_object( $value ) ) {
687 $v = empty( $value->mParams['nodata'] )
688 ? $this->mFieldData[$key]
689 : $value->getDefault();
690 $tableHtml .= $value->getTableRow( $v );
692 if ( $value->getLabel() != '&#160;' )
693 $hasLeftColumn = true;
694 } elseif ( is_array( $value ) ) {
695 $section = $this->displaySection( $value, $key );
696 $legend = $this->getLegend( $key );
697 if ( isset( $this->mSectionHeaders[$key] ) ) {
698 $section = $this->mSectionHeaders[$key] . $section;
700 if ( isset( $this->mSectionFooters[$key] ) ) {
701 $section .= $this->mSectionFooters[$key];
703 $attributes = array();
704 if ( $displayTitle ) {
705 $attributes["id"] = 'prefsection-' . Sanitizer::escapeId( $key, 'noninitial' );
707 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
711 $classes = array();
713 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
714 $classes[] = 'mw-htmlform-nolabel';
717 $attribs = array(
718 'class' => implode( ' ', $classes ),
721 if ( $sectionName ) {
722 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
725 $tableHtml = Html::rawElement( 'table', $attribs,
726 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
728 return $subsectionHtml . "\n" . $tableHtml;
732 * Construct the form fields from the Descriptor array
734 function loadData() {
735 $fieldData = array();
737 foreach ( $this->mFlatFields as $fieldname => $field ) {
738 if ( !empty( $field->mParams['nodata'] ) ) {
739 continue;
740 } elseif ( !empty( $field->mParams['disabled'] ) ) {
741 $fieldData[$fieldname] = $field->getDefault();
742 } else {
743 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
747 # Filter data.
748 foreach ( $fieldData as $name => &$value ) {
749 $field = $this->mFlatFields[$name];
750 $value = $field->filter( $value, $this->mFlatFields );
753 $this->mFieldData = $fieldData;
757 * Stop a reset button being shown for this form
758 * @param $suppressReset Bool set to false to re-enable the
759 * button again
761 function suppressReset( $suppressReset = true ) {
762 $this->mShowReset = !$suppressReset;
766 * Overload this if you want to apply special filtration routines
767 * to the form as a whole, after it's submitted but before it's
768 * processed.
769 * @param $data
770 * @return unknown_type
772 function filterDataForSubmit( $data ) {
773 return $data;
777 * Get a string to go in the <legend> of a section fieldset. Override this if you
778 * want something more complicated
779 * @param $key String
780 * @return String
782 public function getLegend( $key ) {
783 return wfMsg( "{$this->mMessagePrefix}-$key" );
788 * The parent class to generate form fields. Any field type should
789 * be a subclass of this.
791 abstract class HTMLFormField {
793 protected $mValidationCallback;
794 protected $mFilterCallback;
795 protected $mName;
796 public $mParams;
797 protected $mLabel; # String label. Set on construction
798 protected $mID;
799 protected $mClass = '';
800 protected $mDefault;
803 * @var HTMLForm
805 public $mParent;
808 * This function must be implemented to return the HTML to generate
809 * the input object itself. It should not implement the surrounding
810 * table cells/rows, or labels/help messages.
811 * @param $value String the value to set the input to; eg a default
812 * text for a text input.
813 * @return String valid HTML.
815 abstract function getInputHTML( $value );
818 * Override this function to add specific validation checks on the
819 * field input. Don't forget to call parent::validate() to ensure
820 * that the user-defined callback mValidationCallback is still run
821 * @param $value String the value the field was submitted with
822 * @param $alldata Array the data collected from the form
823 * @return Mixed Bool true on success, or String error to display.
825 function validate( $value, $alldata ) {
826 if ( isset( $this->mValidationCallback ) ) {
827 return call_user_func( $this->mValidationCallback, $value, $alldata );
830 if ( isset( $this->mParams['required'] ) && $value === '' ) {
831 return wfMsgExt( 'htmlform-required', 'parseinline' );
834 return true;
837 function filter( $value, $alldata ) {
838 if ( isset( $this->mFilterCallback ) ) {
839 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
842 return $value;
846 * Should this field have a label, or is there no input element with the
847 * appropriate id for the label to point to?
849 * @return bool True to output a label, false to suppress
851 protected function needsLabel() {
852 return true;
856 * Get the value that this input has been set to from a posted form,
857 * or the input's default value if it has not been set.
858 * @param $request WebRequest
859 * @return String the value
861 function loadDataFromRequest( $request ) {
862 if ( $request->getCheck( $this->mName ) ) {
863 return $request->getText( $this->mName );
864 } else {
865 return $this->getDefault();
870 * Initialise the object
871 * @param $params array Associative Array. See HTMLForm doc for syntax.
873 function __construct( $params ) {
874 $this->mParams = $params;
876 # Generate the label from a message, if possible
877 if ( isset( $params['label-message'] ) ) {
878 $msgInfo = $params['label-message'];
880 if ( is_array( $msgInfo ) ) {
881 $msg = array_shift( $msgInfo );
882 } else {
883 $msg = $msgInfo;
884 $msgInfo = array();
887 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
888 } elseif ( isset( $params['label'] ) ) {
889 $this->mLabel = $params['label'];
892 $this->mName = "wp{$params['fieldname']}";
893 if ( isset( $params['name'] ) ) {
894 $this->mName = $params['name'];
897 $validName = Sanitizer::escapeId( $this->mName );
898 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
899 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
902 $this->mID = "mw-input-{$this->mName}";
904 if ( isset( $params['default'] ) ) {
905 $this->mDefault = $params['default'];
908 if ( isset( $params['id'] ) ) {
909 $id = $params['id'];
910 $validId = Sanitizer::escapeId( $id );
912 if ( $id != $validId ) {
913 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
916 $this->mID = $id;
919 if ( isset( $params['cssclass'] ) ) {
920 $this->mClass = $params['cssclass'];
923 if ( isset( $params['validation-callback'] ) ) {
924 $this->mValidationCallback = $params['validation-callback'];
927 if ( isset( $params['filter-callback'] ) ) {
928 $this->mFilterCallback = $params['filter-callback'];
933 * Get the complete table row for the input, including help text,
934 * labels, and whatever.
935 * @param $value String the value to set the input to.
936 * @return String complete HTML table row.
938 function getTableRow( $value ) {
939 # Check for invalid data.
941 $errors = $this->validate( $value, $this->mParent->mFieldData );
943 $cellAttributes = array();
944 $verticalLabel = false;
946 if ( !empty($this->mParams['vertical-label']) ) {
947 $cellAttributes['colspan'] = 2;
948 $verticalLabel = true;
951 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
952 $errors = '';
953 $errorClass = '';
954 } else {
955 $errors = self::formatErrors( $errors );
956 $errorClass = 'mw-htmlform-invalid-input';
959 $label = $this->getLabelHtml( $cellAttributes );
960 $field = Html::rawElement(
961 'td',
962 array( 'class' => 'mw-input' ) + $cellAttributes,
963 $this->getInputHTML( $value ) . "\n$errors"
966 $fieldType = get_class( $this );
968 if ( $verticalLabel ) {
969 $html = Html::rawElement( 'tr',
970 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
971 $html .= Html::rawElement( 'tr',
972 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
973 $field );
974 } else {
975 $html = Html::rawElement( 'tr',
976 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
977 $label . $field );
980 $helptext = null;
982 if ( isset( $this->mParams['help-message'] ) ) {
983 $msg = wfMessage( $this->mParams['help-message'] );
984 if ( $msg->exists() ) {
985 $helptext = $msg->parse();
987 } elseif ( isset( $this->mParams['help-messages'] ) ) {
988 # help-message can be passed a message key (string) or an array containing
989 # a message key and additional parameters. This makes it impossible to pass
990 # an array of message key
991 foreach( $this->mParams['help-messages'] as $name ) {
992 $msg = wfMessage( $name );
993 if( $msg->exists() ) {
994 $helptext .= $msg->parse(); // append message
997 } elseif ( isset( $this->mParams['help'] ) ) {
998 $helptext = $this->mParams['help'];
1001 if ( !is_null( $helptext ) ) {
1002 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1003 $helptext );
1004 $row = Html::rawElement( 'tr', array(), $row );
1005 $html .= "$row\n";
1008 return $html;
1011 function getLabel() {
1012 return $this->mLabel;
1014 function getLabelHtml( $cellAttributes = array() ) {
1015 # Don't output a for= attribute for labels with no associated input.
1016 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1017 $for = array();
1019 if ( $this->needsLabel() ) {
1020 $for['for'] = $this->mID;
1023 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1024 Html::rawElement( 'label', $for, $this->getLabel() )
1028 function getDefault() {
1029 if ( isset( $this->mDefault ) ) {
1030 return $this->mDefault;
1031 } else {
1032 return null;
1037 * Returns the attributes required for the tooltip and accesskey.
1039 * @return array Attributes
1041 public function getTooltipAndAccessKey() {
1042 if ( empty( $this->mParams['tooltip'] ) ) {
1043 return array();
1045 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1049 * flatten an array of options to a single array, for instance,
1050 * a set of <options> inside <optgroups>.
1051 * @param $options Associative Array with values either Strings
1052 * or Arrays
1053 * @return Array flattened input
1055 public static function flattenOptions( $options ) {
1056 $flatOpts = array();
1058 foreach ( $options as $value ) {
1059 if ( is_array( $value ) ) {
1060 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1061 } else {
1062 $flatOpts[] = $value;
1066 return $flatOpts;
1070 * Formats one or more errors as accepted by field validation-callback.
1071 * @param $errors String|Message|Array of strings or Message instances
1072 * @return String html
1073 * @since 1.18
1075 protected static function formatErrors( $errors ) {
1076 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1077 $errors = array_shift( $errors );
1080 if ( is_array( $errors ) ) {
1081 $lines = array();
1082 foreach ( $errors as $error ) {
1083 if ( $error instanceof Message ) {
1084 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1085 } else {
1086 $lines[] = Html::rawElement( 'li', array(), $error );
1089 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1090 } else {
1091 if ( $errors instanceof Message ) {
1092 $errors = $errors->parse();
1094 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1099 class HTMLTextField extends HTMLFormField {
1100 function getSize() {
1101 return isset( $this->mParams['size'] )
1102 ? $this->mParams['size']
1103 : 45;
1106 function getInputHTML( $value ) {
1107 $attribs = array(
1108 'id' => $this->mID,
1109 'name' => $this->mName,
1110 'size' => $this->getSize(),
1111 'value' => $value,
1112 ) + $this->getTooltipAndAccessKey();
1114 if ( isset( $this->mParams['maxlength'] ) ) {
1115 $attribs['maxlength'] = $this->mParams['maxlength'];
1118 if ( !empty( $this->mParams['disabled'] ) ) {
1119 $attribs['disabled'] = 'disabled';
1122 # TODO: Enforce pattern, step, required, readonly on the server side as
1123 # well
1124 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1125 'placeholder' ) as $param ) {
1126 if ( isset( $this->mParams[$param] ) ) {
1127 $attribs[$param] = $this->mParams[$param];
1131 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1132 if ( isset( $this->mParams[$param] ) ) {
1133 $attribs[$param] = '';
1137 # Implement tiny differences between some field variants
1138 # here, rather than creating a new class for each one which
1139 # is essentially just a clone of this one.
1140 if ( isset( $this->mParams['type'] ) ) {
1141 switch ( $this->mParams['type'] ) {
1142 case 'email':
1143 $attribs['type'] = 'email';
1144 break;
1145 case 'int':
1146 $attribs['type'] = 'number';
1147 break;
1148 case 'float':
1149 $attribs['type'] = 'number';
1150 $attribs['step'] = 'any';
1151 break;
1152 # Pass through
1153 case 'password':
1154 case 'file':
1155 $attribs['type'] = $this->mParams['type'];
1156 break;
1160 return Html::element( 'input', $attribs );
1163 class HTMLTextAreaField extends HTMLFormField {
1164 function getCols() {
1165 return isset( $this->mParams['cols'] )
1166 ? $this->mParams['cols']
1167 : 80;
1170 function getRows() {
1171 return isset( $this->mParams['rows'] )
1172 ? $this->mParams['rows']
1173 : 25;
1176 function getInputHTML( $value ) {
1177 $attribs = array(
1178 'id' => $this->mID,
1179 'name' => $this->mName,
1180 'cols' => $this->getCols(),
1181 'rows' => $this->getRows(),
1182 ) + $this->getTooltipAndAccessKey();
1185 if ( !empty( $this->mParams['disabled'] ) ) {
1186 $attribs['disabled'] = 'disabled';
1189 if ( !empty( $this->mParams['readonly'] ) ) {
1190 $attribs['readonly'] = 'readonly';
1193 foreach ( array( 'required', 'autofocus' ) as $param ) {
1194 if ( isset( $this->mParams[$param] ) ) {
1195 $attribs[$param] = '';
1199 return Html::element( 'textarea', $attribs, $value );
1204 * A field that will contain a numeric value
1206 class HTMLFloatField extends HTMLTextField {
1207 function getSize() {
1208 return isset( $this->mParams['size'] )
1209 ? $this->mParams['size']
1210 : 20;
1213 function validate( $value, $alldata ) {
1214 $p = parent::validate( $value, $alldata );
1216 if ( $p !== true ) {
1217 return $p;
1220 $value = trim( $value );
1222 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1223 # with the addition that a leading '+' sign is ok.
1224 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1225 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1228 # The "int" part of these message names is rather confusing.
1229 # They make equal sense for all numbers.
1230 if ( isset( $this->mParams['min'] ) ) {
1231 $min = $this->mParams['min'];
1233 if ( $min > $value ) {
1234 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1238 if ( isset( $this->mParams['max'] ) ) {
1239 $max = $this->mParams['max'];
1241 if ( $max < $value ) {
1242 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1246 return true;
1251 * A field that must contain a number
1253 class HTMLIntField extends HTMLFloatField {
1254 function validate( $value, $alldata ) {
1255 $p = parent::validate( $value, $alldata );
1257 if ( $p !== true ) {
1258 return $p;
1261 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1262 # with the addition that a leading '+' sign is ok. Note that leading zeros
1263 # are fine, and will be left in the input, which is useful for things like
1264 # phone numbers when you know that they are integers (the HTML5 type=tel
1265 # input does not require its value to be numeric). If you want a tidier
1266 # value to, eg, save in the DB, clean it up with intval().
1267 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1269 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1272 return true;
1277 * A checkbox field
1279 class HTMLCheckField extends HTMLFormField {
1280 function getInputHTML( $value ) {
1281 if ( !empty( $this->mParams['invert'] ) ) {
1282 $value = !$value;
1285 $attr = $this->getTooltipAndAccessKey();
1286 $attr['id'] = $this->mID;
1288 if ( !empty( $this->mParams['disabled'] ) ) {
1289 $attr['disabled'] = 'disabled';
1292 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1293 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1297 * For a checkbox, the label goes on the right hand side, and is
1298 * added in getInputHTML(), rather than HTMLFormField::getRow()
1300 function getLabel() {
1301 return '&#160;';
1305 * @param $request WebRequest
1306 * @return String
1308 function loadDataFromRequest( $request ) {
1309 $invert = false;
1310 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1311 $invert = true;
1314 // GetCheck won't work like we want for checks.
1315 if ( $request->getCheck( 'wpEditToken' ) || $this->mParent->getMethod() != 'post' ) {
1316 // XOR has the following truth table, which is what we want
1317 // INVERT VALUE | OUTPUT
1318 // true true | false
1319 // false true | true
1320 // false false | false
1321 // true false | true
1322 return $request->getBool( $this->mName ) xor $invert;
1323 } else {
1324 return $this->getDefault();
1330 * A select dropdown field. Basically a wrapper for Xmlselect class
1332 class HTMLSelectField extends HTMLFormField {
1333 function validate( $value, $alldata ) {
1334 $p = parent::validate( $value, $alldata );
1336 if ( $p !== true ) {
1337 return $p;
1340 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1342 if ( in_array( $value, $validOptions ) )
1343 return true;
1344 else
1345 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1348 function getInputHTML( $value ) {
1349 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1351 # If one of the options' 'name' is int(0), it is automatically selected.
1352 # because PHP sucks and thinks int(0) == 'some string'.
1353 # Working around this by forcing all of them to strings.
1354 foreach( $this->mParams['options'] as &$opt ){
1355 if( is_int( $opt ) ){
1356 $opt = strval( $opt );
1359 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1361 if ( !empty( $this->mParams['disabled'] ) ) {
1362 $select->setAttribute( 'disabled', 'disabled' );
1365 $select->addOptions( $this->mParams['options'] );
1367 return $select->getHTML();
1372 * Select dropdown field, with an additional "other" textbox.
1374 class HTMLSelectOrOtherField extends HTMLTextField {
1375 static $jsAdded = false;
1377 function __construct( $params ) {
1378 if ( !in_array( 'other', $params['options'], true ) ) {
1379 $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
1380 $params['options'][$msg] = 'other';
1383 parent::__construct( $params );
1386 static function forceToStringRecursive( $array ) {
1387 if ( is_array( $array ) ) {
1388 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1389 } else {
1390 return strval( $array );
1394 function getInputHTML( $value ) {
1395 $valInSelect = false;
1397 if ( $value !== false ) {
1398 $valInSelect = in_array(
1399 $value,
1400 HTMLFormField::flattenOptions( $this->mParams['options'] )
1404 $selected = $valInSelect ? $value : 'other';
1406 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1408 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1409 $select->addOptions( $opts );
1411 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1413 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1415 if ( !empty( $this->mParams['disabled'] ) ) {
1416 $select->setAttribute( 'disabled', 'disabled' );
1417 $tbAttribs['disabled'] = 'disabled';
1420 $select = $select->getHTML();
1422 if ( isset( $this->mParams['maxlength'] ) ) {
1423 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1426 $textbox = Html::input(
1427 $this->mName . '-other',
1428 $valInSelect ? '' : $value,
1429 'text',
1430 $tbAttribs
1433 return "$select<br />\n$textbox";
1437 * @param $request WebRequest
1438 * @return String
1440 function loadDataFromRequest( $request ) {
1441 if ( $request->getCheck( $this->mName ) ) {
1442 $val = $request->getText( $this->mName );
1444 if ( $val == 'other' ) {
1445 $val = $request->getText( $this->mName . '-other' );
1448 return $val;
1449 } else {
1450 return $this->getDefault();
1456 * Multi-select field
1458 class HTMLMultiSelectField extends HTMLFormField {
1460 public function __construct( $params ){
1461 parent::__construct( $params );
1462 if( isset( $params['flatlist'] ) ){
1463 $this->mClass .= ' mw-htmlform-multiselect-flatlist';
1467 function validate( $value, $alldata ) {
1468 $p = parent::validate( $value, $alldata );
1470 if ( $p !== true ) {
1471 return $p;
1474 if ( !is_array( $value ) ) {
1475 return false;
1478 # If all options are valid, array_intersect of the valid options
1479 # and the provided options will return the provided options.
1480 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1482 $validValues = array_intersect( $value, $validOptions );
1483 if ( count( $validValues ) == count( $value ) ) {
1484 return true;
1485 } else {
1486 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1490 function getInputHTML( $value ) {
1491 $html = $this->formatOptions( $this->mParams['options'], $value );
1493 return $html;
1496 function formatOptions( $options, $value ) {
1497 $html = '';
1499 $attribs = array();
1501 if ( !empty( $this->mParams['disabled'] ) ) {
1502 $attribs['disabled'] = 'disabled';
1505 foreach ( $options as $label => $info ) {
1506 if ( is_array( $info ) ) {
1507 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1508 $html .= $this->formatOptions( $info, $value );
1509 } else {
1510 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1512 $checkbox = Xml::check(
1513 $this->mName . '[]',
1514 in_array( $info, $value, true ),
1515 $attribs + $thisAttribs );
1516 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1518 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
1522 return $html;
1526 * @param $request WebRequest
1527 * @return String
1529 function loadDataFromRequest( $request ) {
1530 if ( $this->mParent->getMethod() == 'post' ) {
1531 if( $request->wasPosted() ){
1532 # Checkboxes are just not added to the request arrays if they're not checked,
1533 # so it's perfectly possible for there not to be an entry at all
1534 return $request->getArray( $this->mName, array() );
1535 } else {
1536 # That's ok, the user has not yet submitted the form, so show the defaults
1537 return $this->getDefault();
1539 } else {
1540 # This is the impossible case: if we look at $_GET and see no data for our
1541 # field, is it because the user has not yet submitted the form, or that they
1542 # have submitted it with all the options unchecked? We will have to assume the
1543 # latter, which basically means that you can't specify 'positive' defaults
1544 # for GET forms.
1545 # @todo FIXME...
1546 return $request->getArray( $this->mName, array() );
1550 function getDefault() {
1551 if ( isset( $this->mDefault ) ) {
1552 return $this->mDefault;
1553 } else {
1554 return array();
1558 protected function needsLabel() {
1559 return false;
1564 * Double field with a dropdown list constructed from a system message in the format
1565 * * Optgroup header
1566 * ** <option value>|<option name>
1567 * ** <option value == option name>
1568 * * New Optgroup header
1569 * Plus a text field underneath for an additional reason. The 'value' of the field is
1570 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1571 * select dropdown.
1572 * @todo FIXME: If made 'required', only the text field should be compulsory.
1574 class HTMLSelectAndOtherField extends HTMLSelectField {
1576 function __construct( $params ) {
1577 if ( array_key_exists( 'other', $params ) ) {
1578 } elseif( array_key_exists( 'other-message', $params ) ){
1579 $params['other'] = wfMessage( $params['other-message'] )->escaped();
1580 } else {
1581 $params['other'] = null;
1584 if ( array_key_exists( 'options', $params ) ) {
1585 # Options array already specified
1586 } elseif( array_key_exists( 'options-message', $params ) ){
1587 # Generate options array from a system message
1588 $params['options'] = self::parseMessage(
1589 wfMessage( $params['options-message'] )->inContentLanguage()->escaped(),
1590 $params['other']
1592 } else {
1593 # Sulk
1594 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1596 $this->mFlatOptions = self::flattenOptions( $params['options'] );
1598 parent::__construct( $params );
1602 * Build a drop-down box from a textual list.
1603 * @param $string String message text
1604 * @param $otherName String name of "other reason" option
1605 * @return Array
1606 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1608 public static function parseMessage( $string, $otherName=null ) {
1609 if( $otherName === null ){
1610 $otherName = wfMessage( 'htmlform-selectorother-other' )->escaped();
1613 $optgroup = false;
1614 $options = array( $otherName => 'other' );
1616 foreach ( explode( "\n", $string ) as $option ) {
1617 $value = trim( $option );
1618 if ( $value == '' ) {
1619 continue;
1620 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1621 # A new group is starting...
1622 $value = trim( substr( $value, 1 ) );
1623 $optgroup = $value;
1624 } elseif ( substr( $value, 0, 2) == '**' ) {
1625 # groupmember
1626 $opt = trim( substr( $value, 2 ) );
1627 $parts = array_map( 'trim', explode( '|', $opt, 2 ) );
1628 if( count( $parts ) === 1 ){
1629 $parts[1] = $parts[0];
1631 if( $optgroup === false ){
1632 $options[$parts[1]] = $parts[0];
1633 } else {
1634 $options[$optgroup][$parts[1]] = $parts[0];
1636 } else {
1637 # groupless reason list
1638 $optgroup = false;
1639 $parts = array_map( 'trim', explode( '|', $option, 2 ) );
1640 if( count( $parts ) === 1 ){
1641 $parts[1] = $parts[0];
1643 $options[$parts[1]] = $parts[0];
1647 return $options;
1650 function getInputHTML( $value ) {
1651 $select = parent::getInputHTML( $value[1] );
1653 $textAttribs = array(
1654 'id' => $this->mID . '-other',
1655 'size' => $this->getSize(),
1658 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1659 if ( isset( $this->mParams[$param] ) ) {
1660 $textAttribs[$param] = '';
1664 $textbox = Html::input(
1665 $this->mName . '-other',
1666 $value[2],
1667 'text',
1668 $textAttribs
1671 return "$select<br />\n$textbox";
1675 * @param $request WebRequest
1676 * @return Array( <overall message>, <select value>, <text field value> )
1678 function loadDataFromRequest( $request ) {
1679 if ( $request->getCheck( $this->mName ) ) {
1681 $list = $request->getText( $this->mName );
1682 $text = $request->getText( $this->mName . '-other' );
1684 if ( $list == 'other' ) {
1685 $final = $text;
1686 } elseif( !in_array( $list, $this->mFlatOptions ) ){
1687 # User has spoofed the select form to give an option which wasn't
1688 # in the original offer. Sulk...
1689 $final = $text;
1690 } elseif( $text == '' ) {
1691 $final = $list;
1692 } else {
1693 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1696 } else {
1697 $final = $this->getDefault();
1698 $list = $text = '';
1700 return array( $final, $list, $text );
1703 function getSize() {
1704 return isset( $this->mParams['size'] )
1705 ? $this->mParams['size']
1706 : 45;
1709 function validate( $value, $alldata ) {
1710 # HTMLSelectField forces $value to be one of the options in the select
1711 # field, which is not useful here. But we do want the validation further up
1712 # the chain
1713 $p = parent::validate( $value[1], $alldata );
1715 if ( $p !== true ) {
1716 return $p;
1719 if( isset( $this->mParams['required'] ) && $value[1] === '' ){
1720 return wfMsgExt( 'htmlform-required', 'parseinline' );
1723 return true;
1728 * Radio checkbox fields.
1730 class HTMLRadioField extends HTMLFormField {
1731 function validate( $value, $alldata ) {
1732 $p = parent::validate( $value, $alldata );
1734 if ( $p !== true ) {
1735 return $p;
1738 if ( !is_string( $value ) && !is_int( $value ) ) {
1739 return false;
1742 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1744 if ( in_array( $value, $validOptions ) ) {
1745 return true;
1746 } else {
1747 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1752 * This returns a block of all the radio options, in one cell.
1753 * @see includes/HTMLFormField#getInputHTML()
1755 function getInputHTML( $value ) {
1756 $html = $this->formatOptions( $this->mParams['options'], $value );
1758 return $html;
1761 function formatOptions( $options, $value ) {
1762 $html = '';
1764 $attribs = array();
1765 if ( !empty( $this->mParams['disabled'] ) ) {
1766 $attribs['disabled'] = 'disabled';
1769 # TODO: should this produce an unordered list perhaps?
1770 foreach ( $options as $label => $info ) {
1771 if ( is_array( $info ) ) {
1772 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1773 $html .= $this->formatOptions( $info, $value );
1774 } else {
1775 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1776 $html .= Xml::radio(
1777 $this->mName,
1778 $info,
1779 $info == $value,
1780 $attribs + array( 'id' => $id )
1782 $html .= '&#160;' .
1783 Html::rawElement( 'label', array( 'for' => $id ), $label );
1785 $html .= "<br />\n";
1789 return $html;
1792 protected function needsLabel() {
1793 return false;
1798 * An information field (text blob), not a proper input.
1800 class HTMLInfoField extends HTMLFormField {
1801 function __construct( $info ) {
1802 $info['nodata'] = true;
1804 parent::__construct( $info );
1807 function getInputHTML( $value ) {
1808 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1811 function getTableRow( $value ) {
1812 if ( !empty( $this->mParams['rawrow'] ) ) {
1813 return $value;
1816 return parent::getTableRow( $value );
1819 protected function needsLabel() {
1820 return false;
1824 class HTMLHiddenField extends HTMLFormField {
1825 public function __construct( $params ) {
1826 parent::__construct( $params );
1828 # Per HTML5 spec, hidden fields cannot be 'required'
1829 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1830 unset( $this->mParams['required'] );
1833 public function getTableRow( $value ) {
1834 $params = array();
1835 if ( $this->mID ) {
1836 $params['id'] = $this->mID;
1839 $this->mParent->addHiddenField(
1840 $this->mName,
1841 $this->mDefault,
1842 $params
1845 return '';
1848 public function getInputHTML( $value ) { return ''; }
1852 * Add a submit button inline in the form (as opposed to
1853 * HTMLForm::addButton(), which will add it at the end).
1855 class HTMLSubmitField extends HTMLFormField {
1857 function __construct( $info ) {
1858 $info['nodata'] = true;
1859 parent::__construct( $info );
1862 function getInputHTML( $value ) {
1863 return Xml::submitButton(
1864 $value,
1865 array(
1866 'class' => 'mw-htmlform-submit',
1867 'name' => $this->mName,
1868 'id' => $this->mID,
1873 protected function needsLabel() {
1874 return false;
1878 * Button cannot be invalid
1880 public function validate( $value, $alldata ){
1881 return true;
1885 class HTMLEditTools extends HTMLFormField {
1886 public function getInputHTML( $value ) {
1887 return '';
1890 public function getTableRow( $value ) {
1891 if ( empty( $this->mParams['message'] ) ) {
1892 $msg = wfMessage( 'edittools' );
1893 } else {
1894 $msg = wfMessage( $this->mParams['message'] );
1895 if ( $msg->isDisabled() ) {
1896 $msg = wfMessage( 'edittools' );
1899 $msg->inContentLanguage();
1902 return '<tr><td></td><td class="mw-input">'
1903 . '<div class="mw-editTools">'
1904 . $msg->parseAsBlock()
1905 . "</div></td></tr>\n";