(bug 26895) in /include/db/LoadBalancer.php function "closeConnecton" should be calle...
[mediawiki.git] / includes / HTMLForm.php
blob2e7e3999bdce441fe8c76eeb415bdf855cea4d87
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 {
57 static $jsAdded = false;
59 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
60 static $typeMappings = array(
61 'text' => 'HTMLTextField',
62 'textarea' => 'HTMLTextAreaField',
63 'select' => 'HTMLSelectField',
64 'radio' => 'HTMLRadioField',
65 'multiselect' => 'HTMLMultiSelectField',
66 'check' => 'HTMLCheckField',
67 'toggle' => 'HTMLCheckField',
68 'int' => 'HTMLIntField',
69 'float' => 'HTMLFloatField',
70 'info' => 'HTMLInfoField',
71 'selectorother' => 'HTMLSelectOrOtherField',
72 'submit' => 'HTMLSubmitField',
73 'hidden' => 'HTMLHiddenField',
74 'edittools' => 'HTMLEditTools',
76 # HTMLTextField will output the correct type="" attribute automagically.
77 # There are about four zillion other HTML5 input types, like url, but
78 # we don't use those at the moment, so no point in adding all of them.
79 'email' => 'HTMLTextField',
80 'password' => 'HTMLTextField',
83 protected $mMessagePrefix;
84 protected $mFlatFields;
85 protected $mFieldTree;
86 protected $mShowReset = false;
87 public $mFieldData;
89 protected $mSubmitCallback;
90 protected $mValidationErrorMessage;
92 protected $mPre = '';
93 protected $mHeader = '';
94 protected $mFooter = '';
95 protected $mPost = '';
96 protected $mId;
98 protected $mSubmitID;
99 protected $mSubmitName;
100 protected $mSubmitText;
101 protected $mSubmitTooltip;
102 protected $mTitle;
103 protected $mMethod = 'post';
105 protected $mUseMultipart = false;
106 protected $mHiddenFields = array();
107 protected $mButtons = array();
109 protected $mWrapperLegend = false;
112 * Build a new HTMLForm from an array of field attributes
113 * @param $descriptor Array of Field constructs, as described above
114 * @param $messagePrefix String a prefix to go in front of default messages
116 public function __construct( $descriptor, $messagePrefix = '' ) {
117 $this->mMessagePrefix = $messagePrefix;
119 // Expand out into a tree.
120 $loadedDescriptor = array();
121 $this->mFlatFields = array();
123 foreach ( $descriptor as $fieldname => $info ) {
124 $section = isset( $info['section'] )
125 ? $info['section']
126 : '';
128 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
129 $this->mUseMultipart = true;
132 $field = self::loadInputFromParameters( $fieldname, $info );
133 $field->mParent = $this;
135 $setSection =& $loadedDescriptor;
136 if ( $section ) {
137 $sectionParts = explode( '/', $section );
139 while ( count( $sectionParts ) ) {
140 $newName = array_shift( $sectionParts );
142 if ( !isset( $setSection[$newName] ) ) {
143 $setSection[$newName] = array();
146 $setSection =& $setSection[$newName];
150 $setSection[$fieldname] = $field;
151 $this->mFlatFields[$fieldname] = $field;
154 $this->mFieldTree = $loadedDescriptor;
158 * Add the HTMLForm-specific JavaScript, if it hasn't been
159 * done already.
161 static function addJS() {
162 if ( self::$jsAdded ) return;
164 global $wgOut;
166 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
170 * Initialise a new Object for the field
171 * @param $descriptor input Descriptor, as described above
172 * @return HTMLFormField subclass
174 static function loadInputFromParameters( $fieldname, $descriptor ) {
175 if ( isset( $descriptor['class'] ) ) {
176 $class = $descriptor['class'];
177 } elseif ( isset( $descriptor['type'] ) ) {
178 $class = self::$typeMappings[$descriptor['type']];
179 $descriptor['class'] = $class;
182 if ( !$class ) {
183 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
186 $descriptor['fieldname'] = $fieldname;
188 $obj = new $class( $descriptor );
190 return $obj;
194 * Prepare form for submission
196 function prepareForm() {
197 # Check if we have the info we need
198 if ( ! $this->mTitle ) {
199 throw new MWException( "You must call setTitle() on an HTMLForm" );
202 // FIXME shouldn't this be closer to displayForm() ?
203 self::addJS();
205 # Load data from the request.
206 $this->loadData();
210 * Try submitting, with edit token check first
211 * @return Status|boolean
213 function tryAuthorizedSubmit() {
214 global $wgUser, $wgRequest;
215 $editToken = $wgRequest->getVal( 'wpEditToken' );
217 $result = false;
218 if ( $this->getMethod() != 'post' || $wgUser->matchEditToken( $editToken ) ) {
219 $result = $this->trySubmit();
221 return $result;
225 * The here's-one-I-made-earlier option: do the submission if
226 * posted, or display the form with or without funky valiation
227 * errors
228 * @return Bool or Status whether submission was successful.
230 function show() {
231 $this->prepareForm();
233 $result = $this->tryAuthorizedSubmit();
234 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ){
235 return $result;
238 $this->displayForm( $result );
239 return false;
243 * Validate all the fields, and call the submision callback
244 * function if everything is kosher.
245 * @return Mixed Bool true == Successful submission, Bool false
246 * == No submission attempted, anything else == Error to
247 * display.
249 function trySubmit() {
250 # Check for validation
251 foreach ( $this->mFlatFields as $fieldname => $field ) {
252 if ( !empty( $field->mParams['nodata'] ) ) {
253 continue;
255 if ( $field->validate(
256 $this->mFieldData[$fieldname],
257 $this->mFieldData )
258 !== true
260 return isset( $this->mValidationErrorMessage )
261 ? $this->mValidationErrorMessage
262 : array( 'htmlform-invalid-input' );
266 $callback = $this->mSubmitCallback;
268 $data = $this->filterDataForSubmit( $this->mFieldData );
270 $res = call_user_func( $callback, $data );
272 return $res;
276 * Set a callback to a function to do something with the form
277 * once it's been successfully validated.
278 * @param $cb String function name. The function will be passed
279 * the output from HTMLForm::filterDataForSubmit, and must
280 * return Bool true on success, Bool false if no submission
281 * was attempted, or String HTML output to display on error.
283 function setSubmitCallback( $cb ) {
284 $this->mSubmitCallback = $cb;
288 * Set a message to display on a validation error.
289 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
290 * (so each entry can be either a String or Array)
292 function setValidationErrorMessage( $msg ) {
293 $this->mValidationErrorMessage = $msg;
297 * Set the introductory message, overwriting any existing message.
298 * @param $msg String complete text of message to display
300 function setIntro( $msg ) { $this->mPre = $msg; }
303 * Add introductory text.
304 * @param $msg String complete text of message to display
306 function addPreText( $msg ) { $this->mPre .= $msg; }
309 * Add header text, inside the form.
310 * @param $msg String complete text of message to display
312 function addHeaderText( $msg ) { $this->mHeader .= $msg; }
315 * Add footer text, inside the form.
316 * @param $msg String complete text of message to display
318 function addFooterText( $msg ) { $this->mFooter .= $msg; }
321 * Add text to the end of the display.
322 * @param $msg String complete text of message to display
324 function addPostText( $msg ) { $this->mPost .= $msg; }
327 * Add a hidden field to the output
328 * @param $name String field name. This will be used exactly as entered
329 * @param $value String field value
330 * @param $attribs Array
332 public function addHiddenField( $name, $value, $attribs = array() ) {
333 $attribs += array( 'name' => $name );
334 $this->mHiddenFields[] = array( $value, $attribs );
337 public function addButton( $name, $value, $id = null, $attribs = null ) {
338 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
342 * Display the form (sending to wgOut), with an appropriate error
343 * message or stack of messages, and any validation errors, etc.
344 * @param $submitResult Mixed output from HTMLForm::trySubmit()
346 function displayForm( $submitResult ) {
347 global $wgOut;
349 # For good measure (it is the default)
350 $wgOut->preventClickjacking();
352 $html = ''
353 . $this->getErrors( $submitResult )
354 . $this->mHeader
355 . $this->getBody()
356 . $this->getHiddenFields()
357 . $this->getButtons()
358 . $this->mFooter
361 $html = $this->wrapForm( $html );
363 $wgOut->addHTML( ''
364 . $this->mPre
365 . $html
366 . $this->mPost
371 * Wrap the form innards in an actual <form> element
372 * @param $html String HTML contents to wrap.
373 * @return String wrapped HTML.
375 function wrapForm( $html ) {
377 # Include a <fieldset> wrapper for style, if requested.
378 if ( $this->mWrapperLegend !== false ) {
379 $html = Xml::fieldset( $this->mWrapperLegend, $html );
381 # Use multipart/form-data
382 $encType = $this->mUseMultipart
383 ? 'multipart/form-data'
384 : 'application/x-www-form-urlencoded';
385 # Attributes
386 $attribs = array(
387 'action' => $this->getTitle()->getFullURL(),
388 'method' => $this->mMethod,
389 'class' => 'visualClear',
390 'enctype' => $encType,
392 if ( !empty( $this->mId ) ) {
393 $attribs['id'] = $this->mId;
396 return Html::rawElement( 'form', $attribs, $html );
400 * Get the hidden fields that should go inside the form.
401 * @return String HTML.
403 function getHiddenFields() {
404 global $wgUser;
406 $html = '';
408 if( $this->getMethod() == 'post' ){
409 $html .= Html::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
410 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
413 foreach ( $this->mHiddenFields as $data ) {
414 list( $value, $attribs ) = $data;
415 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
418 return $html;
422 * Get the submit and (potentially) reset buttons.
423 * @return String HTML.
425 function getButtons() {
426 $html = '';
427 $attribs = array();
429 if ( isset( $this->mSubmitID ) ) {
430 $attribs['id'] = $this->mSubmitID;
433 if ( isset( $this->mSubmitName ) ) {
434 $attribs['name'] = $this->mSubmitName;
437 if ( isset( $this->mSubmitTooltip ) ) {
438 global $wgUser;
439 $attribs += $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip );
442 $attribs['class'] = 'mw-htmlform-submit';
444 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
446 if ( $this->mShowReset ) {
447 $html .= Html::element(
448 'input',
449 array(
450 'type' => 'reset',
451 'value' => wfMsg( 'htmlform-reset' )
453 ) . "\n";
456 foreach ( $this->mButtons as $button ) {
457 $attrs = array(
458 'type' => 'submit',
459 'name' => $button['name'],
460 'value' => $button['value']
463 if ( $button['attribs'] ) {
464 $attrs += $button['attribs'];
467 if ( isset( $button['id'] ) ) {
468 $attrs['id'] = $button['id'];
471 $html .= Html::element( 'input', $attrs );
474 return $html;
478 * Get the whole body of the form.
480 function getBody() {
481 return $this->displaySection( $this->mFieldTree );
485 * Format and display an error message stack.
486 * @param $errors Mixed String or Array of message keys
487 * @return String
489 function getErrors( $errors ) {
490 if ( $errors instanceof Status ) {
491 global $wgOut;
492 $errorstr = $wgOut->parse( $errors->getWikiText() );
493 } elseif ( is_array( $errors ) ) {
494 $errorstr = $this->formatErrors( $errors );
495 } else {
496 $errorstr = $errors;
499 return $errorstr
500 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
501 : '';
505 * Format a stack of error messages into a single HTML string
506 * @param $errors Array of message keys/values
507 * @return String HTML, a <ul> list of errors
509 static function formatErrors( $errors ) {
510 $errorstr = '';
512 foreach ( $errors as $error ) {
513 if ( is_array( $error ) ) {
514 $msg = array_shift( $error );
515 } else {
516 $msg = $error;
517 $error = array();
520 $errorstr .= Html::rawElement(
521 'li',
522 null,
523 wfMsgExt( $msg, array( 'parseinline' ), $error )
527 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
529 return $errorstr;
533 * Set the text for the submit button
534 * @param $t String plaintext.
536 function setSubmitText( $t ) {
537 $this->mSubmitText = $t;
541 * Get the text for the submit button, either customised or a default.
542 * @return unknown_type
544 function getSubmitText() {
545 return $this->mSubmitText
546 ? $this->mSubmitText
547 : wfMsg( 'htmlform-submit' );
550 public function setSubmitName( $name ) {
551 $this->mSubmitName = $name;
554 public function setSubmitTooltip( $name ) {
555 $this->mSubmitTooltip = $name;
559 * Set the id for the submit button.
560 * @param $t String. FIXME: Integrity is *not* validated
562 function setSubmitID( $t ) {
563 $this->mSubmitID = $t;
566 public function setId( $id ) {
567 $this->mId = $id;
570 * Prompt the whole form to be wrapped in a <fieldset>, with
571 * this text as its <legend> element.
572 * @param $legend String HTML to go inside the <legend> element.
573 * Will be escaped
575 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
578 * Set the prefix for various default messages
579 * TODO: currently only used for the <fieldset> legend on forms
580 * with multiple sections; should be used elsewhre?
581 * @param $p String
583 function setMessagePrefix( $p ) {
584 $this->mMessagePrefix = $p;
588 * Set the title for form submission
589 * @param $t Title of page the form is on/should be posted to
591 function setTitle( $t ) {
592 $this->mTitle = $t;
596 * Get the title
597 * @return Title
599 function getTitle() {
600 return $this->mTitle;
604 * Set the method used to submit the form
605 * @param $method String
607 public function setMethod( $method='post' ){
608 $this->mMethod = $method;
611 public function getMethod(){
612 return $this->mMethod;
616 * TODO: Document
617 * @param $fields
619 function displaySection( $fields, $sectionName = '' ) {
620 $tableHtml = '';
621 $subsectionHtml = '';
622 $hasLeftColumn = false;
624 foreach ( $fields as $key => $value ) {
625 if ( is_object( $value ) ) {
626 $v = empty( $value->mParams['nodata'] )
627 ? $this->mFieldData[$key]
628 : $value->getDefault();
629 $tableHtml .= $value->getTableRow( $v );
631 if ( $value->getLabel() != '&#160;' )
632 $hasLeftColumn = true;
633 } elseif ( is_array( $value ) ) {
634 $section = $this->displaySection( $value, $key );
635 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
636 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
640 $classes = array();
642 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
643 $classes[] = 'mw-htmlform-nolabel';
646 $attribs = array(
647 'class' => implode( ' ', $classes ),
650 if ( $sectionName ) {
651 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
654 $tableHtml = Html::rawElement( 'table', $attribs,
655 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
657 return $subsectionHtml . "\n" . $tableHtml;
661 * Construct the form fields from the Descriptor array
663 function loadData() {
664 global $wgRequest;
666 $fieldData = array();
668 foreach ( $this->mFlatFields as $fieldname => $field ) {
669 if ( !empty( $field->mParams['nodata'] ) ) {
670 continue;
671 } elseif ( !empty( $field->mParams['disabled'] ) ) {
672 $fieldData[$fieldname] = $field->getDefault();
673 } else {
674 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
678 # Filter data.
679 foreach ( $fieldData as $name => &$value ) {
680 $field = $this->mFlatFields[$name];
681 $value = $field->filter( $value, $this->mFlatFields );
684 $this->mFieldData = $fieldData;
688 * Stop a reset button being shown for this form
689 * @param $suppressReset Bool set to false to re-enable the
690 * button again
692 function suppressReset( $suppressReset = true ) {
693 $this->mShowReset = !$suppressReset;
697 * Overload this if you want to apply special filtration routines
698 * to the form as a whole, after it's submitted but before it's
699 * processed.
700 * @param $data
701 * @return unknown_type
703 function filterDataForSubmit( $data ) {
704 return $data;
709 * The parent class to generate form fields. Any field type should
710 * be a subclass of this.
712 abstract class HTMLFormField {
714 protected $mValidationCallback;
715 protected $mFilterCallback;
716 protected $mName;
717 public $mParams;
718 protected $mLabel; # String label. Set on construction
719 protected $mID;
720 protected $mClass = '';
721 protected $mDefault;
722 public $mParent;
725 * This function must be implemented to return the HTML to generate
726 * the input object itself. It should not implement the surrounding
727 * table cells/rows, or labels/help messages.
728 * @param $value String the value to set the input to; eg a default
729 * text for a text input.
730 * @return String valid HTML.
732 abstract function getInputHTML( $value );
735 * Override this function to add specific validation checks on the
736 * field input. Don't forget to call parent::validate() to ensure
737 * that the user-defined callback mValidationCallback is still run
738 * @param $value String the value the field was submitted with
739 * @param $alldata Array the data collected from the form
740 * @return Mixed Bool true on success, or String error to display.
742 function validate( $value, $alldata ) {
743 if ( isset( $this->mValidationCallback ) ) {
744 return call_user_func( $this->mValidationCallback, $value, $alldata );
747 if ( isset( $this->mParams['required'] ) && $value === '' ) {
748 return wfMsgExt( 'htmlform-required', 'parseinline' );
751 return true;
754 function filter( $value, $alldata ) {
755 if ( isset( $this->mFilterCallback ) ) {
756 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
759 return $value;
763 * Should this field have a label, or is there no input element with the
764 * appropriate id for the label to point to?
766 * @return bool True to output a label, false to suppress
768 protected function needsLabel() {
769 return true;
773 * Get the value that this input has been set to from a posted form,
774 * or the input's default value if it has not been set.
775 * @param $request WebRequest
776 * @return String the value
778 function loadDataFromRequest( $request ) {
779 if ( $request->getCheck( $this->mName ) ) {
780 return $request->getText( $this->mName );
781 } else {
782 return $this->getDefault();
787 * Initialise the object
788 * @param $params Associative Array. See HTMLForm doc for syntax.
790 function __construct( $params ) {
791 $this->mParams = $params;
793 # Generate the label from a message, if possible
794 if ( isset( $params['label-message'] ) ) {
795 $msgInfo = $params['label-message'];
797 if ( is_array( $msgInfo ) ) {
798 $msg = array_shift( $msgInfo );
799 } else {
800 $msg = $msgInfo;
801 $msgInfo = array();
804 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
805 } elseif ( isset( $params['label'] ) ) {
806 $this->mLabel = $params['label'];
809 $this->mName = "wp{$params['fieldname']}";
810 if ( isset( $params['name'] ) ) {
811 $this->mName = $params['name'];
814 $validName = Sanitizer::escapeId( $this->mName );
815 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
816 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
819 $this->mID = "mw-input-{$this->mName}";
821 if ( isset( $params['default'] ) ) {
822 $this->mDefault = $params['default'];
825 if ( isset( $params['id'] ) ) {
826 $id = $params['id'];
827 $validId = Sanitizer::escapeId( $id );
829 if ( $id != $validId ) {
830 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
833 $this->mID = $id;
836 if ( isset( $params['cssclass'] ) ) {
837 $this->mClass = $params['cssclass'];
840 if ( isset( $params['validation-callback'] ) ) {
841 $this->mValidationCallback = $params['validation-callback'];
844 if ( isset( $params['filter-callback'] ) ) {
845 $this->mFilterCallback = $params['filter-callback'];
850 * Get the complete table row for the input, including help text,
851 * labels, and whatever.
852 * @param $value String the value to set the input to.
853 * @return String complete HTML table row.
855 function getTableRow( $value ) {
856 # Check for invalid data.
857 global $wgRequest;
859 $errors = $this->validate( $value, $this->mParent->mFieldData );
861 $cellAttributes = array();
862 $verticalLabel = false;
864 if ( !empty($this->mParams['vertical-label']) ) {
865 $cellAttributes['colspan'] = 2;
866 $verticalLabel = true;
869 if ( $errors === true || ( !$wgRequest->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
870 $errors = '';
871 } else {
872 $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
875 $label = $this->getLabelHtml( $cellAttributes );
876 $field = Html::rawElement(
877 'td',
878 array( 'class' => 'mw-input' ) + $cellAttributes,
879 $this->getInputHTML( $value ) . "\n$errors"
882 $fieldType = get_class( $this );
884 if ($verticalLabel) {
885 $html = Html::rawElement( 'tr',
886 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
887 $html .= Html::rawElement( 'tr',
888 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
889 $field );
890 } else {
891 $html = Html::rawElement( 'tr',
892 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
893 $label . $field );
896 $helptext = null;
898 if ( isset( $this->mParams['help-message'] ) ) {
899 $msg = $this->mParams['help-message'];
900 $helptext = wfMsgExt( $msg, 'parseinline' );
901 if ( wfEmptyMsg( $msg, $helptext ) ) {
902 # Never mind
903 $helptext = null;
905 } elseif ( isset( $this->mParams['help-messages'] ) ) {
906 # help-message can be passed a message key (string) or an array containing
907 # a message key and additional parameters. This makes it impossible to pass
908 # an array of message key
909 foreach( $this->mParams['help-messages'] as $msg ) {
910 $candidate = wfMsgExt( $msg, 'parseinline' );
911 if( wfEmptyMsg( $msg ) ) {
912 $candidate = null;
914 $helptext .= $candidate; // append message
916 } elseif ( isset( $this->mParams['help'] ) ) {
917 $helptext = $this->mParams['help'];
920 if ( !is_null( $helptext ) ) {
921 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
922 $helptext );
923 $row = Html::rawElement( 'tr', array(), $row );
924 $html .= "$row\n";
927 return $html;
930 function getLabel() {
931 return $this->mLabel;
933 function getLabelHtml( $cellAttributes = array() ) {
934 # Don't output a for= attribute for labels with no associated input.
935 # Kind of hacky here, possibly we don't want these to be <label>s at all.
936 $for = array();
938 if ( $this->needsLabel() ) {
939 $for['for'] = $this->mID;
942 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
943 Html::rawElement( 'label', $for, $this->getLabel() )
947 function getDefault() {
948 if ( isset( $this->mDefault ) ) {
949 return $this->mDefault;
950 } else {
951 return null;
956 * Returns the attributes required for the tooltip and accesskey.
958 * @return array Attributes
960 public function getTooltipAndAccessKey() {
961 if ( empty( $this->mParams['tooltip'] ) ) {
962 return array();
965 global $wgUser;
967 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
971 * flatten an array of options to a single array, for instance,
972 * a set of <options> inside <optgroups>.
973 * @param $options Associative Array with values either Strings
974 * or Arrays
975 * @return Array flattened input
977 public static function flattenOptions( $options ) {
978 $flatOpts = array();
980 foreach ( $options as $value ) {
981 if ( is_array( $value ) ) {
982 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
983 } else {
984 $flatOpts[] = $value;
988 return $flatOpts;
992 class HTMLTextField extends HTMLFormField {
993 function getSize() {
994 return isset( $this->mParams['size'] )
995 ? $this->mParams['size']
996 : 45;
999 function getInputHTML( $value ) {
1000 $attribs = array(
1001 'id' => $this->mID,
1002 'name' => $this->mName,
1003 'size' => $this->getSize(),
1004 'value' => $value,
1005 ) + $this->getTooltipAndAccessKey();
1007 if ( isset( $this->mParams['maxlength'] ) ) {
1008 $attribs['maxlength'] = $this->mParams['maxlength'];
1011 if ( !empty( $this->mParams['disabled'] ) ) {
1012 $attribs['disabled'] = 'disabled';
1015 # TODO: Enforce pattern, step, required, readonly on the server side as
1016 # well
1017 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1018 'placeholder' ) as $param ) {
1019 if ( isset( $this->mParams[$param] ) ) {
1020 $attribs[$param] = $this->mParams[$param];
1024 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1025 if ( isset( $this->mParams[$param] ) ) {
1026 $attribs[$param] = '';
1030 # Implement tiny differences between some field variants
1031 # here, rather than creating a new class for each one which
1032 # is essentially just a clone of this one.
1033 if ( isset( $this->mParams['type'] ) ) {
1034 switch ( $this->mParams['type'] ) {
1035 case 'email':
1036 $attribs['type'] = 'email';
1037 break;
1038 case 'int':
1039 $attribs['type'] = 'number';
1040 break;
1041 case 'float':
1042 $attribs['type'] = 'number';
1043 $attribs['step'] = 'any';
1044 break;
1045 # Pass through
1046 case 'password':
1047 case 'file':
1048 $attribs['type'] = $this->mParams['type'];
1049 break;
1053 return Html::element( 'input', $attribs );
1056 class HTMLTextAreaField extends HTMLFormField {
1057 function getCols() {
1058 return isset( $this->mParams['cols'] )
1059 ? $this->mParams['cols']
1060 : 80;
1063 function getRows() {
1064 return isset( $this->mParams['rows'] )
1065 ? $this->mParams['rows']
1066 : 25;
1069 function getInputHTML( $value ) {
1070 $attribs = array(
1071 'id' => $this->mID,
1072 'name' => $this->mName,
1073 'cols' => $this->getCols(),
1074 'rows' => $this->getRows(),
1075 ) + $this->getTooltipAndAccessKey();
1078 if ( !empty( $this->mParams['disabled'] ) ) {
1079 $attribs['disabled'] = 'disabled';
1082 if ( !empty( $this->mParams['readonly'] ) ) {
1083 $attribs['readonly'] = 'readonly';
1086 foreach ( array( 'required', 'autofocus' ) as $param ) {
1087 if ( isset( $this->mParams[$param] ) ) {
1088 $attribs[$param] = '';
1092 return Html::element( 'textarea', $attribs, $value );
1097 * A field that will contain a numeric value
1099 class HTMLFloatField extends HTMLTextField {
1100 function getSize() {
1101 return isset( $this->mParams['size'] )
1102 ? $this->mParams['size']
1103 : 20;
1106 function validate( $value, $alldata ) {
1107 $p = parent::validate( $value, $alldata );
1109 if ( $p !== true ) {
1110 return $p;
1113 $value = trim( $value );
1115 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1116 # with the addition that a leading '+' sign is ok.
1117 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1118 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1121 # The "int" part of these message names is rather confusing.
1122 # They make equal sense for all numbers.
1123 if ( isset( $this->mParams['min'] ) ) {
1124 $min = $this->mParams['min'];
1126 if ( $min > $value ) {
1127 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1131 if ( isset( $this->mParams['max'] ) ) {
1132 $max = $this->mParams['max'];
1134 if ( $max < $value ) {
1135 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1139 return true;
1144 * A field that must contain a number
1146 class HTMLIntField extends HTMLFloatField {
1147 function validate( $value, $alldata ) {
1148 $p = parent::validate( $value, $alldata );
1150 if ( $p !== true ) {
1151 return $p;
1154 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1155 # with the addition that a leading '+' sign is ok. Note that leading zeros
1156 # are fine, and will be left in the input, which is useful for things like
1157 # phone numbers when you know that they are integers (the HTML5 type=tel
1158 # input does not require its value to be numeric). If you want a tidier
1159 # value to, eg, save in the DB, clean it up with intval().
1160 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1162 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1165 return true;
1170 * A checkbox field
1172 class HTMLCheckField extends HTMLFormField {
1173 function getInputHTML( $value ) {
1174 if ( !empty( $this->mParams['invert'] ) ) {
1175 $value = !$value;
1178 $attr = $this->getTooltipAndAccessKey();
1179 $attr['id'] = $this->mID;
1181 if ( !empty( $this->mParams['disabled'] ) ) {
1182 $attr['disabled'] = 'disabled';
1185 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1186 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1190 * For a checkbox, the label goes on the right hand side, and is
1191 * added in getInputHTML(), rather than HTMLFormField::getRow()
1193 function getLabel() {
1194 return '&#160;';
1197 function loadDataFromRequest( $request ) {
1198 $invert = false;
1199 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1200 $invert = true;
1203 // GetCheck won't work like we want for checks.
1204 if ( $request->getCheck( 'wpEditToken' ) ) {
1205 // XOR has the following truth table, which is what we want
1206 // INVERT VALUE | OUTPUT
1207 // true true | false
1208 // false true | true
1209 // false false | false
1210 // true false | true
1211 return $request->getBool( $this->mName ) xor $invert;
1212 } else {
1213 return $this->getDefault();
1219 * A select dropdown field. Basically a wrapper for Xmlselect class
1221 class HTMLSelectField extends HTMLFormField {
1222 function validate( $value, $alldata ) {
1223 $p = parent::validate( $value, $alldata );
1225 if ( $p !== true ) {
1226 return $p;
1229 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1231 if ( in_array( $value, $validOptions ) )
1232 return true;
1233 else
1234 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1237 function getInputHTML( $value ) {
1238 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1240 # If one of the options' 'name' is int(0), it is automatically selected.
1241 # because PHP sucks and things int(0) == 'some string'.
1242 # Working around this by forcing all of them to strings.
1243 foreach( $this->mParams['options'] as $key => &$opt ){
1244 if( is_int( $opt ) ){
1245 $opt = strval( $opt );
1248 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1250 if ( !empty( $this->mParams['disabled'] ) ) {
1251 $select->setAttribute( 'disabled', 'disabled' );
1254 $select->addOptions( $this->mParams['options'] );
1256 return $select->getHTML();
1261 * Select dropdown field, with an additional "other" textbox.
1263 class HTMLSelectOrOtherField extends HTMLTextField {
1264 static $jsAdded = false;
1266 function __construct( $params ) {
1267 if ( !in_array( 'other', $params['options'], true ) ) {
1268 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1271 parent::__construct( $params );
1274 static function forceToStringRecursive( $array ) {
1275 if ( is_array( $array ) ) {
1276 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1277 } else {
1278 return strval( $array );
1282 function getInputHTML( $value ) {
1283 $valInSelect = false;
1285 if ( $value !== false ) {
1286 $valInSelect = in_array(
1287 $value,
1288 HTMLFormField::flattenOptions( $this->mParams['options'] )
1292 $selected = $valInSelect ? $value : 'other';
1294 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1296 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1297 $select->addOptions( $opts );
1299 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1301 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1303 if ( !empty( $this->mParams['disabled'] ) ) {
1304 $select->setAttribute( 'disabled', 'disabled' );
1305 $tbAttribs['disabled'] = 'disabled';
1308 $select = $select->getHTML();
1310 if ( isset( $this->mParams['maxlength'] ) ) {
1311 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1314 $textbox = Html::input(
1315 $this->mName . '-other',
1316 $valInSelect ? '' : $value,
1317 'text',
1318 $tbAttribs
1321 return "$select<br />\n$textbox";
1324 function loadDataFromRequest( $request ) {
1325 if ( $request->getCheck( $this->mName ) ) {
1326 $val = $request->getText( $this->mName );
1328 if ( $val == 'other' ) {
1329 $val = $request->getText( $this->mName . '-other' );
1332 return $val;
1333 } else {
1334 return $this->getDefault();
1340 * Multi-select field
1342 class HTMLMultiSelectField extends HTMLFormField {
1343 function validate( $value, $alldata ) {
1344 $p = parent::validate( $value, $alldata );
1346 if ( $p !== true ) {
1347 return $p;
1350 if ( !is_array( $value ) ) {
1351 return false;
1354 # If all options are valid, array_intersect of the valid options
1355 # and the provided options will return the provided options.
1356 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1358 $validValues = array_intersect( $value, $validOptions );
1359 if ( count( $validValues ) == count( $value ) ) {
1360 return true;
1361 } else {
1362 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1366 function getInputHTML( $value ) {
1367 $html = $this->formatOptions( $this->mParams['options'], $value );
1369 return $html;
1372 function formatOptions( $options, $value ) {
1373 $html = '';
1375 $attribs = array();
1377 if ( !empty( $this->mParams['disabled'] ) ) {
1378 $attribs['disabled'] = 'disabled';
1381 foreach ( $options as $label => $info ) {
1382 if ( is_array( $info ) ) {
1383 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1384 $html .= $this->formatOptions( $info, $value );
1385 } else {
1386 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1388 $checkbox = Xml::check(
1389 $this->mName . '[]',
1390 in_array( $info, $value, true ),
1391 $attribs + $thisAttribs );
1392 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1394 $html .= $checkbox . '<br />';
1398 return $html;
1401 function loadDataFromRequest( $request ) {
1402 # won't work with getCheck
1403 if ( $request->getCheck( 'wpEditToken' ) ) {
1404 $arr = $request->getArray( $this->mName );
1406 if ( !$arr ) {
1407 $arr = array();
1410 return $arr;
1411 } else {
1412 return $this->getDefault();
1416 function getDefault() {
1417 if ( isset( $this->mDefault ) ) {
1418 return $this->mDefault;
1419 } else {
1420 return array();
1424 protected function needsLabel() {
1425 return false;
1430 * Radio checkbox fields.
1432 class HTMLRadioField extends HTMLFormField {
1433 function validate( $value, $alldata ) {
1434 $p = parent::validate( $value, $alldata );
1436 if ( $p !== true ) {
1437 return $p;
1440 if ( !is_string( $value ) && !is_int( $value ) ) {
1441 return false;
1444 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1446 if ( in_array( $value, $validOptions ) ) {
1447 return true;
1448 } else {
1449 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1454 * This returns a block of all the radio options, in one cell.
1455 * @see includes/HTMLFormField#getInputHTML()
1457 function getInputHTML( $value ) {
1458 $html = $this->formatOptions( $this->mParams['options'], $value );
1460 return $html;
1463 function formatOptions( $options, $value ) {
1464 $html = '';
1466 $attribs = array();
1467 if ( !empty( $this->mParams['disabled'] ) ) {
1468 $attribs['disabled'] = 'disabled';
1471 # TODO: should this produce an unordered list perhaps?
1472 foreach ( $options as $label => $info ) {
1473 if ( is_array( $info ) ) {
1474 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1475 $html .= $this->formatOptions( $info, $value );
1476 } else {
1477 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1478 $html .= Xml::radio(
1479 $this->mName,
1480 $info,
1481 $info == $value,
1482 $attribs + array( 'id' => $id )
1484 $html .= '&#160;' .
1485 Html::rawElement( 'label', array( 'for' => $id ), $label );
1487 $html .= "<br />\n";
1491 return $html;
1494 protected function needsLabel() {
1495 return false;
1500 * An information field (text blob), not a proper input.
1502 class HTMLInfoField extends HTMLFormField {
1503 function __construct( $info ) {
1504 $info['nodata'] = true;
1506 parent::__construct( $info );
1509 function getInputHTML( $value ) {
1510 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1513 function getTableRow( $value ) {
1514 if ( !empty( $this->mParams['rawrow'] ) ) {
1515 return $value;
1518 return parent::getTableRow( $value );
1521 protected function needsLabel() {
1522 return false;
1526 class HTMLHiddenField extends HTMLFormField {
1527 public function __construct( $params ) {
1528 parent::__construct( $params );
1530 # Per HTML5 spec, hidden fields cannot be 'required'
1531 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1532 unset( $this->mParams['required'] );
1535 public function getTableRow( $value ) {
1536 $params = array();
1537 if ( $this->mID ) {
1538 $params['id'] = $this->mID;
1541 $this->mParent->addHiddenField(
1542 $this->mName,
1543 $this->mDefault,
1544 $params
1547 return '';
1550 public function getInputHTML( $value ) { return ''; }
1554 * Add a submit button inline in the form (as opposed to
1555 * HTMLForm::addButton(), which will add it at the end).
1557 class HTMLSubmitField extends HTMLFormField {
1559 function __construct( $info ) {
1560 $info['nodata'] = true;
1561 parent::__construct( $info );
1564 function getInputHTML( $value ) {
1565 return Xml::submitButton(
1566 $value,
1567 array(
1568 'class' => 'mw-htmlform-submit',
1569 'name' => $this->mName,
1570 'id' => $this->mID,
1575 protected function needsLabel() {
1576 return false;
1580 * Button cannot be invalid
1582 public function validate( $value, $alldata ){
1583 return true;
1587 class HTMLEditTools extends HTMLFormField {
1588 public function getInputHTML( $value ) {
1589 return '';
1592 public function getTableRow( $value ) {
1593 return "<tr><td></td><td class=\"mw-input\">"
1594 . '<div class="mw-editTools">'
1595 . wfMsgExt( empty( $this->mParams['message'] )
1596 ? 'edittools' : $this->mParams['message'],
1597 array( 'parse', 'content' ) )
1598 . "</div></td></tr>\n";