Add a way for packagers to override some installation details
[mediawiki.git] / includes / HTMLForm.php
blob4f696382e49add8d18eb58b1b14342ff43fe0fdb
1 <?php
2 /**
3 * HTML form generation and submission handling.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Object handling generic submission, CSRF protection, layout and
25 * other logic for UI forms. in a reusable manner.
27 * In order to generate the form, the HTMLForm object takes an array
28 * structure detailing the form fields available. Each element of the
29 * array is a basic property-list, including the type of field, the
30 * label it is to be given in the form, callbacks for validation and
31 * 'filtering', and other pertinent information.
33 * Field types are implemented as subclasses of the generic HTMLFormField
34 * object, and typically implement at least getInputHTML, which generates
35 * the HTML for the input field to be placed in the table.
37 * The constructor input is an associative array of $fieldname => $info,
38 * where $info is an Associative Array with any of the following:
40 * 'class' -- the subclass of HTMLFormField that will be used
41 * to create the object. *NOT* the CSS class!
42 * 'type' -- roughly translates into the <select> type attribute.
43 * if 'class' is not specified, this is used as a map
44 * through HTMLForm::$typeMappings to get the class name.
45 * 'default' -- default value when the form is displayed
46 * 'id' -- HTML id attribute
47 * 'cssclass' -- CSS class
48 * 'options' -- varies according to the specific object.
49 * 'label-message' -- message key for a message to use as the label.
50 * can be an array of msg key and then parameters to
51 * the message.
52 * 'label' -- alternatively, a raw text message. Overridden by
53 * label-message
54 * 'help' -- message text for a message to use as a help text.
55 * 'help-message' -- message key for a message to use as a help text.
56 * can be an array of msg key and then parameters to
57 * the message.
58 * Overwrites 'help-messages' and 'help'.
59 * 'help-messages' -- array of message key. As above, each item can
60 * be an array of msg key and then parameters.
61 * Overwrites 'help'.
62 * 'required' -- passed through to the object, indicating that it
63 * is a required field.
64 * 'size' -- the length of text fields
65 * 'filter-callback -- a function name to give you the chance to
66 * massage the inputted value before it's processed.
67 * @see HTMLForm::filter()
68 * 'validation-callback' -- a function name to give you the chance
69 * to impose extra validation on the field input.
70 * @see HTMLForm::validate()
71 * 'name' -- By default, the 'name' attribute of the input field
72 * is "wp{$fieldname}". If you want a different name
73 * (eg one without the "wp" prefix), specify it here and
74 * it will be used without modification.
76 * TODO: Document 'section' / 'subsection' stuff
78 class HTMLForm extends ContextSource {
80 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
81 static $typeMappings = array(
82 'text' => 'HTMLTextField',
83 'textarea' => 'HTMLTextAreaField',
84 'select' => 'HTMLSelectField',
85 'radio' => 'HTMLRadioField',
86 'multiselect' => 'HTMLMultiSelectField',
87 'check' => 'HTMLCheckField',
88 'toggle' => 'HTMLCheckField',
89 'int' => 'HTMLIntField',
90 'float' => 'HTMLFloatField',
91 'info' => 'HTMLInfoField',
92 'selectorother' => 'HTMLSelectOrOtherField',
93 'selectandother' => 'HTMLSelectAndOtherField',
94 'submit' => 'HTMLSubmitField',
95 'hidden' => 'HTMLHiddenField',
96 'edittools' => 'HTMLEditTools',
98 // HTMLTextField will output the correct type="" attribute automagically.
99 // There are about four zillion other HTML5 input types, like url, but
100 // we don't use those at the moment, so no point in adding all of them.
101 'email' => 'HTMLTextField',
102 'password' => 'HTMLTextField',
105 protected $mMessagePrefix;
107 /** @var HTMLFormField[] */
108 protected $mFlatFields;
110 protected $mFieldTree;
111 protected $mShowReset = false;
112 public $mFieldData;
114 protected $mSubmitCallback;
115 protected $mValidationErrorMessage;
117 protected $mPre = '';
118 protected $mHeader = '';
119 protected $mFooter = '';
120 protected $mSectionHeaders = array();
121 protected $mSectionFooters = array();
122 protected $mPost = '';
123 protected $mId;
125 protected $mSubmitID;
126 protected $mSubmitName;
127 protected $mSubmitText;
128 protected $mSubmitTooltip;
130 protected $mTitle;
131 protected $mMethod = 'post';
134 * Form action URL. false means we will use the URL to set Title
135 * @since 1.19
136 * @var bool|string
138 protected $mAction = false;
140 protected $mUseMultipart = false;
141 protected $mHiddenFields = array();
142 protected $mButtons = array();
144 protected $mWrapperLegend = false;
147 * If true, sections that contain both fields and subsections will
148 * render their subsections before their fields.
150 * Subclasses may set this to false to render subsections after fields
151 * instead.
153 protected $mSubSectionBeforeFields = true;
156 * Format in which to display form. For viable options,
157 * @see $availableDisplayFormats
158 * @var String
160 protected $displayFormat = 'table';
163 * Available formats in which to display the form
164 * @var Array
166 protected $availableDisplayFormats = array(
167 'table',
168 'div',
169 'raw',
173 * Build a new HTMLForm from an array of field attributes
174 * @param $descriptor Array of Field constructs, as described above
175 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
176 * Obviates the need to call $form->setTitle()
177 * @param $messagePrefix String a prefix to go in front of default messages
179 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
180 if ( $context instanceof IContextSource ) {
181 $this->setContext( $context );
182 $this->mTitle = false; // We don't need them to set a title
183 $this->mMessagePrefix = $messagePrefix;
184 } else {
185 // B/C since 1.18
186 if ( is_string( $context ) && $messagePrefix === '' ) {
187 // it's actually $messagePrefix
188 $this->mMessagePrefix = $context;
192 // Expand out into a tree.
193 $loadedDescriptor = array();
194 $this->mFlatFields = array();
196 foreach ( $descriptor as $fieldname => $info ) {
197 $section = isset( $info['section'] )
198 ? $info['section']
199 : '';
201 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
202 $this->mUseMultipart = true;
205 $field = self::loadInputFromParameters( $fieldname, $info );
206 $field->mParent = $this;
208 $setSection =& $loadedDescriptor;
209 if ( $section ) {
210 $sectionParts = explode( '/', $section );
212 while ( count( $sectionParts ) ) {
213 $newName = array_shift( $sectionParts );
215 if ( !isset( $setSection[$newName] ) ) {
216 $setSection[$newName] = array();
219 $setSection =& $setSection[$newName];
223 $setSection[$fieldname] = $field;
224 $this->mFlatFields[$fieldname] = $field;
227 $this->mFieldTree = $loadedDescriptor;
231 * Set format in which to display the form
232 * @param $format String the name of the format to use, must be one of
233 * $this->availableDisplayFormats
234 * @since 1.20
236 public function setDisplayFormat( $format ) {
237 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
238 throw new MWException ( 'Display format must be one of ' . print_r( $this->availableDisplayFormats, true ) );
240 $this->displayFormat = $format;
244 * Getter for displayFormat
245 * @since 1.20
246 * @return String
248 public function getDisplayFormat() {
249 return $this->displayFormat;
253 * Add the HTMLForm-specific JavaScript, if it hasn't been
254 * done already.
255 * @deprecated since 1.18 load modules with ResourceLoader instead
257 static function addJS() { wfDeprecated( __METHOD__, '1.18' ); }
260 * Initialise a new Object for the field
261 * @param $fieldname string
262 * @param $descriptor string input Descriptor, as described above
263 * @return HTMLFormField subclass
265 static function loadInputFromParameters( $fieldname, $descriptor ) {
266 if ( isset( $descriptor['class'] ) ) {
267 $class = $descriptor['class'];
268 } elseif ( isset( $descriptor['type'] ) ) {
269 $class = self::$typeMappings[$descriptor['type']];
270 $descriptor['class'] = $class;
271 } else {
272 $class = null;
275 if ( !$class ) {
276 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
279 $descriptor['fieldname'] = $fieldname;
281 # TODO
282 # This will throw a fatal error whenever someone try to use
283 # 'class' to feed a CSS class instead of 'cssclass'. Would be
284 # great to avoid the fatal error and show a nice error.
285 $obj = new $class( $descriptor );
287 return $obj;
291 * Prepare form for submission
293 function prepareForm() {
294 # Check if we have the info we need
295 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
296 throw new MWException( "You must call setTitle() on an HTMLForm" );
299 # Load data from the request.
300 $this->loadData();
304 * Try submitting, with edit token check first
305 * @return Status|boolean
307 function tryAuthorizedSubmit() {
308 $result = false;
310 $submit = false;
311 if ( $this->getMethod() != 'post' ) {
312 $submit = true; // no session check needed
313 } elseif ( $this->getRequest()->wasPosted() ) {
314 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
315 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
316 // Session tokens for logged-out users have no security value.
317 // However, if the user gave one, check it in order to give a nice
318 // "session expired" error instead of "permission denied" or such.
319 $submit = $this->getUser()->matchEditToken( $editToken );
320 } else {
321 $submit = true;
325 if ( $submit ) {
326 $result = $this->trySubmit();
329 return $result;
333 * The here's-one-I-made-earlier option: do the submission if
334 * posted, or display the form with or without funky validation
335 * errors
336 * @return Bool or Status whether submission was successful.
338 function show() {
339 $this->prepareForm();
341 $result = $this->tryAuthorizedSubmit();
342 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
343 return $result;
346 $this->displayForm( $result );
347 return false;
351 * Validate all the fields, and call the submision callback
352 * function if everything is kosher.
353 * @return Mixed Bool true == Successful submission, Bool false
354 * == No submission attempted, anything else == Error to
355 * display.
357 function trySubmit() {
358 # Check for validation
359 foreach ( $this->mFlatFields as $fieldname => $field ) {
360 if ( !empty( $field->mParams['nodata'] ) ) {
361 continue;
363 if ( $field->validate(
364 $this->mFieldData[$fieldname],
365 $this->mFieldData )
366 !== true
368 return isset( $this->mValidationErrorMessage )
369 ? $this->mValidationErrorMessage
370 : array( 'htmlform-invalid-input' );
374 $callback = $this->mSubmitCallback;
375 if ( !is_callable( $callback ) ) {
376 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
379 $data = $this->filterDataForSubmit( $this->mFieldData );
381 $res = call_user_func( $callback, $data, $this );
383 return $res;
387 * Set a callback to a function to do something with the form
388 * once it's been successfully validated.
389 * @param $cb String function name. The function will be passed
390 * the output from HTMLForm::filterDataForSubmit, and must
391 * return Bool true on success, Bool false if no submission
392 * was attempted, or String HTML output to display on error.
394 function setSubmitCallback( $cb ) {
395 $this->mSubmitCallback = $cb;
399 * Set a message to display on a validation error.
400 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
401 * (so each entry can be either a String or Array)
403 function setValidationErrorMessage( $msg ) {
404 $this->mValidationErrorMessage = $msg;
408 * Set the introductory message, overwriting any existing message.
409 * @param $msg String complete text of message to display
411 function setIntro( $msg ) {
412 $this->setPreText( $msg );
416 * Set the introductory message, overwriting any existing message.
417 * @since 1.19
418 * @param $msg String complete text of message to display
420 function setPreText( $msg ) { $this->mPre = $msg; }
423 * Add introductory text.
424 * @param $msg String complete text of message to display
426 function addPreText( $msg ) { $this->mPre .= $msg; }
429 * Add header text, inside the form.
430 * @param $msg String complete text of message to display
431 * @param $section string The section to add the header to
433 function addHeaderText( $msg, $section = null ) {
434 if ( is_null( $section ) ) {
435 $this->mHeader .= $msg;
436 } else {
437 if ( !isset( $this->mSectionHeaders[$section] ) ) {
438 $this->mSectionHeaders[$section] = '';
440 $this->mSectionHeaders[$section] .= $msg;
445 * Set header text, inside the form.
446 * @since 1.19
447 * @param $msg String complete text of message to display
448 * @param $section The section to add the header to
450 function setHeaderText( $msg, $section = null ) {
451 if ( is_null( $section ) ) {
452 $this->mHeader = $msg;
453 } else {
454 $this->mSectionHeaders[$section] = $msg;
459 * Add footer text, inside the form.
460 * @param $msg String complete text of message to display
461 * @param $section string The section to add the footer text to
463 function addFooterText( $msg, $section = null ) {
464 if ( is_null( $section ) ) {
465 $this->mFooter .= $msg;
466 } else {
467 if ( !isset( $this->mSectionFooters[$section] ) ) {
468 $this->mSectionFooters[$section] = '';
470 $this->mSectionFooters[$section] .= $msg;
475 * Set footer text, inside the form.
476 * @since 1.19
477 * @param $msg String complete text of message to display
478 * @param $section string The section to add the footer text to
480 function setFooterText( $msg, $section = null ) {
481 if ( is_null( $section ) ) {
482 $this->mFooter = $msg;
483 } else {
484 $this->mSectionFooters[$section] = $msg;
489 * Add text to the end of the display.
490 * @param $msg String complete text of message to display
492 function addPostText( $msg ) { $this->mPost .= $msg; }
495 * Set text at the end of the display.
496 * @param $msg String complete text of message to display
498 function setPostText( $msg ) { $this->mPost = $msg; }
501 * Add a hidden field to the output
502 * @param $name String field name. This will be used exactly as entered
503 * @param $value String field value
504 * @param $attribs Array
506 public function addHiddenField( $name, $value, $attribs = array() ) {
507 $attribs += array( 'name' => $name );
508 $this->mHiddenFields[] = array( $value, $attribs );
511 public function addButton( $name, $value, $id = null, $attribs = null ) {
512 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
516 * Display the form (sending to $wgOut), with an appropriate error
517 * message or stack of messages, and any validation errors, etc.
518 * @param $submitResult Mixed output from HTMLForm::trySubmit()
520 function displayForm( $submitResult ) {
521 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
525 * Returns the raw HTML generated by the form
526 * @param $submitResult Mixed output from HTMLForm::trySubmit()
527 * @return string
529 function getHTML( $submitResult ) {
530 # For good measure (it is the default)
531 $this->getOutput()->preventClickjacking();
532 $this->getOutput()->addModules( 'mediawiki.htmlform' );
534 $html = ''
535 . $this->getErrors( $submitResult )
536 . $this->mHeader
537 . $this->getBody()
538 . $this->getHiddenFields()
539 . $this->getButtons()
540 . $this->mFooter
543 $html = $this->wrapForm( $html );
545 return '' . $this->mPre . $html . $this->mPost;
549 * Wrap the form innards in an actual <form> element
550 * @param $html String HTML contents to wrap.
551 * @return String wrapped HTML.
553 function wrapForm( $html ) {
555 # Include a <fieldset> wrapper for style, if requested.
556 if ( $this->mWrapperLegend !== false ) {
557 $html = Xml::fieldset( $this->mWrapperLegend, $html );
559 # Use multipart/form-data
560 $encType = $this->mUseMultipart
561 ? 'multipart/form-data'
562 : 'application/x-www-form-urlencoded';
563 # Attributes
564 $attribs = array(
565 'action' => $this->mAction === false ? $this->getTitle()->getFullURL() : $this->mAction,
566 'method' => $this->mMethod,
567 'class' => 'visualClear',
568 'enctype' => $encType,
570 if ( !empty( $this->mId ) ) {
571 $attribs['id'] = $this->mId;
574 return Html::rawElement( 'form', $attribs, $html );
578 * Get the hidden fields that should go inside the form.
579 * @return String HTML.
581 function getHiddenFields() {
582 global $wgArticlePath;
584 $html = '';
585 if ( $this->getMethod() == 'post' ) {
586 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
587 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
590 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
591 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
594 foreach ( $this->mHiddenFields as $data ) {
595 list( $value, $attribs ) = $data;
596 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
599 return $html;
603 * Get the submit and (potentially) reset buttons.
604 * @return String HTML.
606 function getButtons() {
607 $html = '';
608 $attribs = array();
610 if ( isset( $this->mSubmitID ) ) {
611 $attribs['id'] = $this->mSubmitID;
614 if ( isset( $this->mSubmitName ) ) {
615 $attribs['name'] = $this->mSubmitName;
618 if ( isset( $this->mSubmitTooltip ) ) {
619 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
622 $attribs['class'] = 'mw-htmlform-submit';
624 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
626 if ( $this->mShowReset ) {
627 $html .= Html::element(
628 'input',
629 array(
630 'type' => 'reset',
631 'value' => wfMsg( 'htmlform-reset' )
633 ) . "\n";
636 foreach ( $this->mButtons as $button ) {
637 $attrs = array(
638 'type' => 'submit',
639 'name' => $button['name'],
640 'value' => $button['value']
643 if ( $button['attribs'] ) {
644 $attrs += $button['attribs'];
647 if ( isset( $button['id'] ) ) {
648 $attrs['id'] = $button['id'];
651 $html .= Html::element( 'input', $attrs );
654 return $html;
658 * Get the whole body of the form.
659 * @return String
661 function getBody() {
662 return $this->displaySection( $this->mFieldTree );
666 * Format and display an error message stack.
667 * @param $errors String|Array|Status
668 * @return String
670 function getErrors( $errors ) {
671 if ( $errors instanceof Status ) {
672 if ( $errors->isOK() ) {
673 $errorstr = '';
674 } else {
675 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
677 } elseif ( is_array( $errors ) ) {
678 $errorstr = $this->formatErrors( $errors );
679 } else {
680 $errorstr = $errors;
683 return $errorstr
684 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
685 : '';
689 * Format a stack of error messages into a single HTML string
690 * @param $errors Array of message keys/values
691 * @return String HTML, a <ul> list of errors
693 public static function formatErrors( $errors ) {
694 $errorstr = '';
696 foreach ( $errors as $error ) {
697 if ( is_array( $error ) ) {
698 $msg = array_shift( $error );
699 } else {
700 $msg = $error;
701 $error = array();
704 $errorstr .= Html::rawElement(
705 'li',
706 array(),
707 wfMsgExt( $msg, array( 'parseinline' ), $error )
711 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
713 return $errorstr;
717 * Set the text for the submit button
718 * @param $t String plaintext.
720 function setSubmitText( $t ) {
721 $this->mSubmitText = $t;
725 * Set the text for the submit button to a message
726 * @since 1.19
727 * @param $msg String message key
729 public function setSubmitTextMsg( $msg ) {
730 return $this->setSubmitText( $this->msg( $msg )->text() );
734 * Get the text for the submit button, either customised or a default.
735 * @return string
737 function getSubmitText() {
738 return $this->mSubmitText
739 ? $this->mSubmitText
740 : wfMsg( 'htmlform-submit' );
743 public function setSubmitName( $name ) {
744 $this->mSubmitName = $name;
747 public function setSubmitTooltip( $name ) {
748 $this->mSubmitTooltip = $name;
752 * Set the id for the submit button.
753 * @param $t String.
754 * @todo FIXME: Integrity of $t is *not* validated
756 function setSubmitID( $t ) {
757 $this->mSubmitID = $t;
760 public function setId( $id ) {
761 $this->mId = $id;
764 * Prompt the whole form to be wrapped in a <fieldset>, with
765 * this text as its <legend> element.
766 * @param $legend String HTML to go inside the <legend> element.
767 * Will be escaped
769 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
772 * Prompt the whole form to be wrapped in a <fieldset>, with
773 * this message as its <legend> element.
774 * @since 1.19
775 * @param $msg String message key
777 public function setWrapperLegendMsg( $msg ) {
778 return $this->setWrapperLegend( $this->msg( $msg )->escaped() );
782 * Set the prefix for various default messages
783 * TODO: currently only used for the <fieldset> legend on forms
784 * with multiple sections; should be used elsewhre?
785 * @param $p String
787 function setMessagePrefix( $p ) {
788 $this->mMessagePrefix = $p;
792 * Set the title for form submission
793 * @param $t Title of page the form is on/should be posted to
795 function setTitle( $t ) {
796 $this->mTitle = $t;
800 * Get the title
801 * @return Title
803 function getTitle() {
804 return $this->mTitle === false
805 ? $this->getContext()->getTitle()
806 : $this->mTitle;
810 * Set the method used to submit the form
811 * @param $method String
813 public function setMethod( $method = 'post' ) {
814 $this->mMethod = $method;
817 public function getMethod() {
818 return $this->mMethod;
822 * TODO: Document
823 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
824 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
825 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
826 * @return String
828 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
829 $displayFormat = $this->getDisplayFormat();
831 $html = '';
832 $subsectionHtml = '';
833 $hasLabel = false;
835 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ? 'getTableRow' : 'get' . ucfirst( $displayFormat );
837 foreach ( $fields as $key => $value ) {
838 if ( $value instanceof HTMLFormField ) {
839 $v = empty( $value->mParams['nodata'] )
840 ? $this->mFieldData[$key]
841 : $value->getDefault();
842 $html .= $value->$getFieldHtmlMethod( $v );
844 $labelValue = trim( $value->getLabel() );
845 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
846 $hasLabel = true;
848 } elseif ( is_array( $value ) ) {
849 $section = $this->displaySection( $value, $key );
850 $legend = $this->getLegend( $key );
851 if ( isset( $this->mSectionHeaders[$key] ) ) {
852 $section = $this->mSectionHeaders[$key] . $section;
854 if ( isset( $this->mSectionFooters[$key] ) ) {
855 $section .= $this->mSectionFooters[$key];
857 $attributes = array();
858 if ( $fieldsetIDPrefix ) {
859 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
861 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
865 if ( $displayFormat !== 'raw' ) {
866 $classes = array();
868 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
869 $classes[] = 'mw-htmlform-nolabel';
872 $attribs = array(
873 'class' => implode( ' ', $classes ),
876 if ( $sectionName ) {
877 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
880 if ( $displayFormat === 'table' ) {
881 $html = Html::rawElement( 'table', $attribs,
882 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
883 } elseif ( $displayFormat === 'div' ) {
884 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
888 if ( $this->mSubSectionBeforeFields ) {
889 return $subsectionHtml . "\n" . $html;
890 } else {
891 return $html . "\n" . $subsectionHtml;
896 * Construct the form fields from the Descriptor array
898 function loadData() {
899 $fieldData = array();
901 foreach ( $this->mFlatFields as $fieldname => $field ) {
902 if ( !empty( $field->mParams['nodata'] ) ) {
903 continue;
904 } elseif ( !empty( $field->mParams['disabled'] ) ) {
905 $fieldData[$fieldname] = $field->getDefault();
906 } else {
907 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
911 # Filter data.
912 foreach ( $fieldData as $name => &$value ) {
913 $field = $this->mFlatFields[$name];
914 $value = $field->filter( $value, $this->mFlatFields );
917 $this->mFieldData = $fieldData;
921 * Stop a reset button being shown for this form
922 * @param $suppressReset Bool set to false to re-enable the
923 * button again
925 function suppressReset( $suppressReset = true ) {
926 $this->mShowReset = !$suppressReset;
930 * Overload this if you want to apply special filtration routines
931 * to the form as a whole, after it's submitted but before it's
932 * processed.
933 * @param $data
934 * @return
936 function filterDataForSubmit( $data ) {
937 return $data;
941 * Get a string to go in the <legend> of a section fieldset. Override this if you
942 * want something more complicated
943 * @param $key String
944 * @return String
946 public function getLegend( $key ) {
947 return wfMsg( "{$this->mMessagePrefix}-$key" );
951 * Set the value for the action attribute of the form.
952 * When set to false (which is the default state), the set title is used.
954 * @since 1.19
956 * @param string|bool $action
958 public function setAction( $action ) {
959 $this->mAction = $action;
965 * The parent class to generate form fields. Any field type should
966 * be a subclass of this.
968 abstract class HTMLFormField {
970 protected $mValidationCallback;
971 protected $mFilterCallback;
972 protected $mName;
973 public $mParams;
974 protected $mLabel; # String label. Set on construction
975 protected $mID;
976 protected $mClass = '';
977 protected $mDefault;
980 * @var HTMLForm
982 public $mParent;
985 * This function must be implemented to return the HTML to generate
986 * the input object itself. It should not implement the surrounding
987 * table cells/rows, or labels/help messages.
988 * @param $value String the value to set the input to; eg a default
989 * text for a text input.
990 * @return String valid HTML.
992 abstract function getInputHTML( $value );
995 * Override this function to add specific validation checks on the
996 * field input. Don't forget to call parent::validate() to ensure
997 * that the user-defined callback mValidationCallback is still run
998 * @param $value String the value the field was submitted with
999 * @param $alldata Array the data collected from the form
1000 * @return Mixed Bool true on success, or String error to display.
1002 function validate( $value, $alldata ) {
1003 if ( isset( $this->mParams['required'] ) && $value === '' ) {
1004 return wfMsgExt( 'htmlform-required', 'parseinline' );
1007 if ( isset( $this->mValidationCallback ) ) {
1008 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1011 return true;
1014 function filter( $value, $alldata ) {
1015 if ( isset( $this->mFilterCallback ) ) {
1016 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1019 return $value;
1023 * Should this field have a label, or is there no input element with the
1024 * appropriate id for the label to point to?
1026 * @return bool True to output a label, false to suppress
1028 protected function needsLabel() {
1029 return true;
1033 * Get the value that this input has been set to from a posted form,
1034 * or the input's default value if it has not been set.
1035 * @param $request WebRequest
1036 * @return String the value
1038 function loadDataFromRequest( $request ) {
1039 if ( $request->getCheck( $this->mName ) ) {
1040 return $request->getText( $this->mName );
1041 } else {
1042 return $this->getDefault();
1047 * Initialise the object
1048 * @param $params array Associative Array. See HTMLForm doc for syntax.
1050 function __construct( $params ) {
1051 $this->mParams = $params;
1053 # Generate the label from a message, if possible
1054 if ( isset( $params['label-message'] ) ) {
1055 $msgInfo = $params['label-message'];
1057 if ( is_array( $msgInfo ) ) {
1058 $msg = array_shift( $msgInfo );
1059 } else {
1060 $msg = $msgInfo;
1061 $msgInfo = array();
1064 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
1065 } elseif ( isset( $params['label'] ) ) {
1066 $this->mLabel = $params['label'];
1069 $this->mName = "wp{$params['fieldname']}";
1070 if ( isset( $params['name'] ) ) {
1071 $this->mName = $params['name'];
1074 $validName = Sanitizer::escapeId( $this->mName );
1075 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1076 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1079 $this->mID = "mw-input-{$this->mName}";
1081 if ( isset( $params['default'] ) ) {
1082 $this->mDefault = $params['default'];
1085 if ( isset( $params['id'] ) ) {
1086 $id = $params['id'];
1087 $validId = Sanitizer::escapeId( $id );
1089 if ( $id != $validId ) {
1090 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1093 $this->mID = $id;
1096 if ( isset( $params['cssclass'] ) ) {
1097 $this->mClass = $params['cssclass'];
1100 if ( isset( $params['validation-callback'] ) ) {
1101 $this->mValidationCallback = $params['validation-callback'];
1104 if ( isset( $params['filter-callback'] ) ) {
1105 $this->mFilterCallback = $params['filter-callback'];
1108 if ( isset( $params['flatlist'] ) ) {
1109 $this->mClass .= ' mw-htmlform-flatlist';
1114 * Get the complete table row for the input, including help text,
1115 * labels, and whatever.
1116 * @param $value String the value to set the input to.
1117 * @return String complete HTML table row.
1119 function getTableRow( $value ) {
1120 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1121 $inputHtml = $this->getInputHTML( $value );
1122 $fieldType = get_class( $this );
1123 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1124 $cellAttributes = array();
1126 if ( !empty( $this->mParams['vertical-label'] ) ) {
1127 $cellAttributes['colspan'] = 2;
1128 $verticalLabel = true;
1129 } else {
1130 $verticalLabel = false;
1133 $label = $this->getLabelHtml( $cellAttributes );
1135 $field = Html::rawElement(
1136 'td',
1137 array( 'class' => 'mw-input' ) + $cellAttributes,
1138 $inputHtml . "\n$errors"
1141 if ( $verticalLabel ) {
1142 $html = Html::rawElement( 'tr',
1143 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1144 $html .= Html::rawElement( 'tr',
1145 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1146 $field );
1147 } else {
1148 $html = Html::rawElement( 'tr',
1149 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1150 $label . $field );
1153 return $html . $helptext;
1157 * Get the complete div for the input, including help text,
1158 * labels, and whatever.
1159 * @since 1.20
1160 * @param $value String the value to set the input to.
1161 * @return String complete HTML table row.
1163 public function getDiv( $value ) {
1164 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1165 $inputHtml = $this->getInputHTML( $value );
1166 $fieldType = get_class( $this );
1167 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1168 $cellAttributes = array();
1169 $label = $this->getLabelHtml( $cellAttributes );
1171 $field = Html::rawElement(
1172 'div',
1173 array( 'class' => 'mw-input' ) + $cellAttributes,
1174 $inputHtml . "\n$errors"
1176 $html = Html::rawElement( 'div',
1177 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1178 $label . $field );
1179 $html .= $helptext;
1180 return $html;
1184 * Get the complete raw fields for the input, including help text,
1185 * labels, and whatever.
1186 * @since 1.20
1187 * @param $value String the value to set the input to.
1188 * @return String complete HTML table row.
1190 public function getRaw( $value ) {
1191 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1192 $inputHtml = $this->getInputHTML( $value );
1193 $fieldType = get_class( $this );
1194 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1195 $cellAttributes = array();
1196 $label = $this->getLabelHtml( $cellAttributes );
1198 $html = "\n$errors";
1199 $html .= $label;
1200 $html .= $inputHtml;
1201 $html .= $helptext;
1202 return $html;
1206 * Generate help text HTML in table format
1207 * @since 1.20
1208 * @param $helptext String|null
1209 * @return String
1211 public function getHelpTextHtmlTable( $helptext ) {
1212 if ( is_null( $helptext ) ) {
1213 return '';
1216 $row = Html::rawElement(
1217 'td',
1218 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1219 $helptext
1221 $row = Html::rawElement( 'tr', array(), $row );
1222 return $row;
1226 * Generate help text HTML in div format
1227 * @since 1.20
1228 * @param $helptext String|null
1229 * @return String
1231 public function getHelpTextHtmlDiv( $helptext ) {
1232 if ( is_null( $helptext ) ) {
1233 return '';
1236 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1237 return $div;
1241 * Generate help text HTML formatted for raw output
1242 * @since 1.20
1243 * @param $helptext String|null
1244 * @return String
1246 public function getHelpTextHtmlRaw( $helptext ) {
1247 return $this->getHelpTextHtmlDiv( $helptext );
1251 * Determine the help text to display
1252 * @since 1.20
1253 * @return String
1255 public function getHelpText() {
1256 $helptext = null;
1258 if ( isset( $this->mParams['help-message'] ) ) {
1259 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1262 if ( isset( $this->mParams['help-messages'] ) ) {
1263 foreach ( $this->mParams['help-messages'] as $name ) {
1264 $helpMessage = (array)$name;
1265 $msg = wfMessage( array_shift( $helpMessage ), $helpMessage );
1267 if ( $msg->exists() ) {
1268 if ( is_null( $helptext ) ) {
1269 $helptext = '';
1270 } else {
1271 $helptext .= wfMessage( 'word-separator' )->escaped(); // some space
1273 $helptext .= $msg->parse(); // Append message
1277 elseif ( isset( $this->mParams['help'] ) ) {
1278 $helptext = $this->mParams['help'];
1280 return $helptext;
1284 * Determine form errors to display and their classes
1285 * @since 1.20
1286 * @param $value String the value of the input
1287 * @return Array
1289 public function getErrorsAndErrorClass( $value ) {
1290 $errors = $this->validate( $value, $this->mParent->mFieldData );
1292 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1293 $errors = '';
1294 $errorClass = '';
1295 } else {
1296 $errors = self::formatErrors( $errors );
1297 $errorClass = 'mw-htmlform-invalid-input';
1299 return array( $errors, $errorClass );
1302 function getLabel() {
1303 return $this->mLabel;
1306 function getLabelHtml( $cellAttributes = array() ) {
1307 # Don't output a for= attribute for labels with no associated input.
1308 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1309 $for = array();
1311 if ( $this->needsLabel() ) {
1312 $for['for'] = $this->mID;
1315 $displayFormat = $this->mParent->getDisplayFormat();
1316 $labelElement = Html::rawElement( 'label', $for, $this->getLabel() );
1318 if ( $displayFormat == 'table' ) {
1319 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1320 Html::rawElement( 'label', $for, $this->getLabel() )
1322 } elseif ( $displayFormat == 'div' ) {
1323 return Html::rawElement( 'div', array( 'class' => 'mw-label' ) + $cellAttributes,
1324 Html::rawElement( 'label', $for, $this->getLabel() )
1326 } else {
1327 return $labelElement;
1331 function getDefault() {
1332 if ( isset( $this->mDefault ) ) {
1333 return $this->mDefault;
1334 } else {
1335 return null;
1340 * Returns the attributes required for the tooltip and accesskey.
1342 * @return array Attributes
1344 public function getTooltipAndAccessKey() {
1345 if ( empty( $this->mParams['tooltip'] ) ) {
1346 return array();
1348 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1352 * flatten an array of options to a single array, for instance,
1353 * a set of <options> inside <optgroups>.
1354 * @param $options array Associative Array with values either Strings
1355 * or Arrays
1356 * @return Array flattened input
1358 public static function flattenOptions( $options ) {
1359 $flatOpts = array();
1361 foreach ( $options as $value ) {
1362 if ( is_array( $value ) ) {
1363 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1364 } else {
1365 $flatOpts[] = $value;
1369 return $flatOpts;
1373 * Formats one or more errors as accepted by field validation-callback.
1374 * @param $errors String|Message|Array of strings or Message instances
1375 * @return String html
1376 * @since 1.18
1378 protected static function formatErrors( $errors ) {
1379 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1380 $errors = array_shift( $errors );
1383 if ( is_array( $errors ) ) {
1384 $lines = array();
1385 foreach ( $errors as $error ) {
1386 if ( $error instanceof Message ) {
1387 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1388 } else {
1389 $lines[] = Html::rawElement( 'li', array(), $error );
1392 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1393 } else {
1394 if ( $errors instanceof Message ) {
1395 $errors = $errors->parse();
1397 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1402 class HTMLTextField extends HTMLFormField {
1403 function getSize() {
1404 return isset( $this->mParams['size'] )
1405 ? $this->mParams['size']
1406 : 45;
1409 function getInputHTML( $value ) {
1410 $attribs = array(
1411 'id' => $this->mID,
1412 'name' => $this->mName,
1413 'size' => $this->getSize(),
1414 'value' => $value,
1415 ) + $this->getTooltipAndAccessKey();
1417 if ( $this->mClass !== '' ) {
1418 $attribs['class'] = $this->mClass;
1421 if ( isset( $this->mParams['maxlength'] ) ) {
1422 $attribs['maxlength'] = $this->mParams['maxlength'];
1425 if ( !empty( $this->mParams['disabled'] ) ) {
1426 $attribs['disabled'] = 'disabled';
1429 # TODO: Enforce pattern, step, required, readonly on the server side as
1430 # well
1431 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1432 'placeholder' ) as $param ) {
1433 if ( isset( $this->mParams[$param] ) ) {
1434 $attribs[$param] = $this->mParams[$param];
1438 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1439 if ( isset( $this->mParams[$param] ) ) {
1440 $attribs[$param] = '';
1444 # Implement tiny differences between some field variants
1445 # here, rather than creating a new class for each one which
1446 # is essentially just a clone of this one.
1447 if ( isset( $this->mParams['type'] ) ) {
1448 switch ( $this->mParams['type'] ) {
1449 case 'email':
1450 $attribs['type'] = 'email';
1451 break;
1452 case 'int':
1453 $attribs['type'] = 'number';
1454 break;
1455 case 'float':
1456 $attribs['type'] = 'number';
1457 $attribs['step'] = 'any';
1458 break;
1459 # Pass through
1460 case 'password':
1461 case 'file':
1462 $attribs['type'] = $this->mParams['type'];
1463 break;
1467 return Html::element( 'input', $attribs );
1470 class HTMLTextAreaField extends HTMLFormField {
1471 function getCols() {
1472 return isset( $this->mParams['cols'] )
1473 ? $this->mParams['cols']
1474 : 80;
1477 function getRows() {
1478 return isset( $this->mParams['rows'] )
1479 ? $this->mParams['rows']
1480 : 25;
1483 function getInputHTML( $value ) {
1484 $attribs = array(
1485 'id' => $this->mID,
1486 'name' => $this->mName,
1487 'cols' => $this->getCols(),
1488 'rows' => $this->getRows(),
1489 ) + $this->getTooltipAndAccessKey();
1491 if ( $this->mClass !== '' ) {
1492 $attribs['class'] = $this->mClass;
1495 if ( !empty( $this->mParams['disabled'] ) ) {
1496 $attribs['disabled'] = 'disabled';
1499 if ( !empty( $this->mParams['readonly'] ) ) {
1500 $attribs['readonly'] = 'readonly';
1503 if ( isset( $this->mParams['placeholder'] ) ) {
1504 $attribs['placeholder'] = $this->mParams['placeholder'];
1507 foreach ( array( 'required', 'autofocus' ) as $param ) {
1508 if ( isset( $this->mParams[$param] ) ) {
1509 $attribs[$param] = '';
1513 return Html::element( 'textarea', $attribs, $value );
1518 * A field that will contain a numeric value
1520 class HTMLFloatField extends HTMLTextField {
1521 function getSize() {
1522 return isset( $this->mParams['size'] )
1523 ? $this->mParams['size']
1524 : 20;
1527 function validate( $value, $alldata ) {
1528 $p = parent::validate( $value, $alldata );
1530 if ( $p !== true ) {
1531 return $p;
1534 $value = trim( $value );
1536 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1537 # with the addition that a leading '+' sign is ok.
1538 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1539 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1542 # The "int" part of these message names is rather confusing.
1543 # They make equal sense for all numbers.
1544 if ( isset( $this->mParams['min'] ) ) {
1545 $min = $this->mParams['min'];
1547 if ( $min > $value ) {
1548 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1552 if ( isset( $this->mParams['max'] ) ) {
1553 $max = $this->mParams['max'];
1555 if ( $max < $value ) {
1556 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1560 return true;
1565 * A field that must contain a number
1567 class HTMLIntField extends HTMLFloatField {
1568 function validate( $value, $alldata ) {
1569 $p = parent::validate( $value, $alldata );
1571 if ( $p !== true ) {
1572 return $p;
1575 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1576 # with the addition that a leading '+' sign is ok. Note that leading zeros
1577 # are fine, and will be left in the input, which is useful for things like
1578 # phone numbers when you know that they are integers (the HTML5 type=tel
1579 # input does not require its value to be numeric). If you want a tidier
1580 # value to, eg, save in the DB, clean it up with intval().
1581 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1583 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1586 return true;
1591 * A checkbox field
1593 class HTMLCheckField extends HTMLFormField {
1594 function getInputHTML( $value ) {
1595 if ( !empty( $this->mParams['invert'] ) ) {
1596 $value = !$value;
1599 $attr = $this->getTooltipAndAccessKey();
1600 $attr['id'] = $this->mID;
1602 if ( !empty( $this->mParams['disabled'] ) ) {
1603 $attr['disabled'] = 'disabled';
1606 if ( $this->mClass !== '' ) {
1607 $attr['class'] = $this->mClass;
1610 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1611 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1615 * For a checkbox, the label goes on the right hand side, and is
1616 * added in getInputHTML(), rather than HTMLFormField::getRow()
1617 * @return String
1619 function getLabel() {
1620 return '&#160;';
1624 * @param $request WebRequest
1625 * @return String
1627 function loadDataFromRequest( $request ) {
1628 $invert = false;
1629 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1630 $invert = true;
1633 // GetCheck won't work like we want for checks.
1634 // Fetch the value in either one of the two following case:
1635 // - we have a valid token (form got posted or GET forged by the user)
1636 // - checkbox name has a value (false or true), ie is not null
1637 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1638 // XOR has the following truth table, which is what we want
1639 // INVERT VALUE | OUTPUT
1640 // true true | false
1641 // false true | true
1642 // false false | false
1643 // true false | true
1644 return $request->getBool( $this->mName ) xor $invert;
1645 } else {
1646 return $this->getDefault();
1652 * A select dropdown field. Basically a wrapper for Xmlselect class
1654 class HTMLSelectField extends HTMLFormField {
1655 function validate( $value, $alldata ) {
1656 $p = parent::validate( $value, $alldata );
1658 if ( $p !== true ) {
1659 return $p;
1662 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1664 if ( in_array( $value, $validOptions ) )
1665 return true;
1666 else
1667 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1670 function getInputHTML( $value ) {
1671 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1673 # If one of the options' 'name' is int(0), it is automatically selected.
1674 # because PHP sucks and thinks int(0) == 'some string'.
1675 # Working around this by forcing all of them to strings.
1676 foreach ( $this->mParams['options'] as &$opt ) {
1677 if ( is_int( $opt ) ) {
1678 $opt = strval( $opt );
1681 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1683 if ( !empty( $this->mParams['disabled'] ) ) {
1684 $select->setAttribute( 'disabled', 'disabled' );
1687 if ( $this->mClass !== '' ) {
1688 $select->setAttribute( 'class', $this->mClass );
1691 $select->addOptions( $this->mParams['options'] );
1693 return $select->getHTML();
1698 * Select dropdown field, with an additional "other" textbox.
1700 class HTMLSelectOrOtherField extends HTMLTextField {
1701 static $jsAdded = false;
1703 function __construct( $params ) {
1704 if ( !in_array( 'other', $params['options'], true ) ) {
1705 $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
1706 $params['options'][$msg] = 'other';
1709 parent::__construct( $params );
1712 static function forceToStringRecursive( $array ) {
1713 if ( is_array( $array ) ) {
1714 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1715 } else {
1716 return strval( $array );
1720 function getInputHTML( $value ) {
1721 $valInSelect = false;
1723 if ( $value !== false ) {
1724 $valInSelect = in_array(
1725 $value,
1726 HTMLFormField::flattenOptions( $this->mParams['options'] )
1730 $selected = $valInSelect ? $value : 'other';
1732 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1734 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1735 $select->addOptions( $opts );
1737 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1739 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1741 if ( !empty( $this->mParams['disabled'] ) ) {
1742 $select->setAttribute( 'disabled', 'disabled' );
1743 $tbAttribs['disabled'] = 'disabled';
1746 $select = $select->getHTML();
1748 if ( isset( $this->mParams['maxlength'] ) ) {
1749 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1752 if ( $this->mClass !== '' ) {
1753 $tbAttribs['class'] = $this->mClass;
1756 $textbox = Html::input(
1757 $this->mName . '-other',
1758 $valInSelect ? '' : $value,
1759 'text',
1760 $tbAttribs
1763 return "$select<br />\n$textbox";
1767 * @param $request WebRequest
1768 * @return String
1770 function loadDataFromRequest( $request ) {
1771 if ( $request->getCheck( $this->mName ) ) {
1772 $val = $request->getText( $this->mName );
1774 if ( $val == 'other' ) {
1775 $val = $request->getText( $this->mName . '-other' );
1778 return $val;
1779 } else {
1780 return $this->getDefault();
1786 * Multi-select field
1788 class HTMLMultiSelectField extends HTMLFormField {
1790 function validate( $value, $alldata ) {
1791 $p = parent::validate( $value, $alldata );
1793 if ( $p !== true ) {
1794 return $p;
1797 if ( !is_array( $value ) ) {
1798 return false;
1801 # If all options are valid, array_intersect of the valid options
1802 # and the provided options will return the provided options.
1803 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1805 $validValues = array_intersect( $value, $validOptions );
1806 if ( count( $validValues ) == count( $value ) ) {
1807 return true;
1808 } else {
1809 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1813 function getInputHTML( $value ) {
1814 $html = $this->formatOptions( $this->mParams['options'], $value );
1816 return $html;
1819 function formatOptions( $options, $value ) {
1820 $html = '';
1822 $attribs = array();
1824 if ( !empty( $this->mParams['disabled'] ) ) {
1825 $attribs['disabled'] = 'disabled';
1828 foreach ( $options as $label => $info ) {
1829 if ( is_array( $info ) ) {
1830 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1831 $html .= $this->formatOptions( $info, $value );
1832 } else {
1833 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1835 $checkbox = Xml::check(
1836 $this->mName . '[]',
1837 in_array( $info, $value, true ),
1838 $attribs + $thisAttribs );
1839 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1841 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1845 return $html;
1849 * @param $request WebRequest
1850 * @return String
1852 function loadDataFromRequest( $request ) {
1853 if ( $this->mParent->getMethod() == 'post' ) {
1854 if ( $request->wasPosted() ) {
1855 # Checkboxes are just not added to the request arrays if they're not checked,
1856 # so it's perfectly possible for there not to be an entry at all
1857 return $request->getArray( $this->mName, array() );
1858 } else {
1859 # That's ok, the user has not yet submitted the form, so show the defaults
1860 return $this->getDefault();
1862 } else {
1863 # This is the impossible case: if we look at $_GET and see no data for our
1864 # field, is it because the user has not yet submitted the form, or that they
1865 # have submitted it with all the options unchecked? We will have to assume the
1866 # latter, which basically means that you can't specify 'positive' defaults
1867 # for GET forms.
1868 # @todo FIXME...
1869 return $request->getArray( $this->mName, array() );
1873 function getDefault() {
1874 if ( isset( $this->mDefault ) ) {
1875 return $this->mDefault;
1876 } else {
1877 return array();
1881 protected function needsLabel() {
1882 return false;
1887 * Double field with a dropdown list constructed from a system message in the format
1888 * * Optgroup header
1889 * ** <option value>
1890 * * New Optgroup header
1891 * Plus a text field underneath for an additional reason. The 'value' of the field is
1892 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1893 * select dropdown.
1894 * @todo FIXME: If made 'required', only the text field should be compulsory.
1896 class HTMLSelectAndOtherField extends HTMLSelectField {
1898 function __construct( $params ) {
1899 if ( array_key_exists( 'other', $params ) ) {
1900 } elseif ( array_key_exists( 'other-message', $params ) ) {
1901 $params['other'] = wfMessage( $params['other-message'] )->plain();
1902 } else {
1903 $params['other'] = null;
1906 if ( array_key_exists( 'options', $params ) ) {
1907 # Options array already specified
1908 } elseif ( array_key_exists( 'options-message', $params ) ) {
1909 # Generate options array from a system message
1910 $params['options'] = self::parseMessage(
1911 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1912 $params['other']
1914 } else {
1915 # Sulk
1916 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1918 $this->mFlatOptions = self::flattenOptions( $params['options'] );
1920 parent::__construct( $params );
1924 * Build a drop-down box from a textual list.
1925 * @param $string String message text
1926 * @param $otherName String name of "other reason" option
1927 * @return Array
1928 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1930 public static function parseMessage( $string, $otherName = null ) {
1931 if ( $otherName === null ) {
1932 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1935 $optgroup = false;
1936 $options = array( $otherName => 'other' );
1938 foreach ( explode( "\n", $string ) as $option ) {
1939 $value = trim( $option );
1940 if ( $value == '' ) {
1941 continue;
1942 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1943 # A new group is starting...
1944 $value = trim( substr( $value, 1 ) );
1945 $optgroup = $value;
1946 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1947 # groupmember
1948 $opt = trim( substr( $value, 2 ) );
1949 if ( $optgroup === false ) {
1950 $options[$opt] = $opt;
1951 } else {
1952 $options[$optgroup][$opt] = $opt;
1954 } else {
1955 # groupless reason list
1956 $optgroup = false;
1957 $options[$option] = $option;
1961 return $options;
1964 function getInputHTML( $value ) {
1965 $select = parent::getInputHTML( $value[1] );
1967 $textAttribs = array(
1968 'id' => $this->mID . '-other',
1969 'size' => $this->getSize(),
1972 if ( $this->mClass !== '' ) {
1973 $textAttribs['class'] = $this->mClass;
1976 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1977 if ( isset( $this->mParams[$param] ) ) {
1978 $textAttribs[$param] = '';
1982 $textbox = Html::input(
1983 $this->mName . '-other',
1984 $value[2],
1985 'text',
1986 $textAttribs
1989 return "$select<br />\n$textbox";
1993 * @param $request WebRequest
1994 * @return Array( <overall message>, <select value>, <text field value> )
1996 function loadDataFromRequest( $request ) {
1997 if ( $request->getCheck( $this->mName ) ) {
1999 $list = $request->getText( $this->mName );
2000 $text = $request->getText( $this->mName . '-other' );
2002 if ( $list == 'other' ) {
2003 $final = $text;
2004 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2005 # User has spoofed the select form to give an option which wasn't
2006 # in the original offer. Sulk...
2007 $final = $text;
2008 } elseif ( $text == '' ) {
2009 $final = $list;
2010 } else {
2011 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
2014 } else {
2015 $final = $this->getDefault();
2017 $list = 'other';
2018 $text = $final;
2019 foreach ( $this->mFlatOptions as $option ) {
2020 $match = $option . wfMsgForContent( 'colon-separator' );
2021 if ( strpos( $text, $match ) === 0 ) {
2022 $list = $option;
2023 $text = substr( $text, strlen( $match ) );
2024 break;
2028 return array( $final, $list, $text );
2031 function getSize() {
2032 return isset( $this->mParams['size'] )
2033 ? $this->mParams['size']
2034 : 45;
2037 function validate( $value, $alldata ) {
2038 # HTMLSelectField forces $value to be one of the options in the select
2039 # field, which is not useful here. But we do want the validation further up
2040 # the chain
2041 $p = parent::validate( $value[1], $alldata );
2043 if ( $p !== true ) {
2044 return $p;
2047 if ( isset( $this->mParams['required'] ) && $value[1] === '' ) {
2048 return wfMsgExt( 'htmlform-required', 'parseinline' );
2051 return true;
2056 * Radio checkbox fields.
2058 class HTMLRadioField extends HTMLFormField {
2061 function validate( $value, $alldata ) {
2062 $p = parent::validate( $value, $alldata );
2064 if ( $p !== true ) {
2065 return $p;
2068 if ( !is_string( $value ) && !is_int( $value ) ) {
2069 return false;
2072 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2074 if ( in_array( $value, $validOptions ) ) {
2075 return true;
2076 } else {
2077 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
2082 * This returns a block of all the radio options, in one cell.
2083 * @see includes/HTMLFormField#getInputHTML()
2084 * @param $value String
2085 * @return String
2087 function getInputHTML( $value ) {
2088 $html = $this->formatOptions( $this->mParams['options'], $value );
2090 return $html;
2093 function formatOptions( $options, $value ) {
2094 $html = '';
2096 $attribs = array();
2097 if ( !empty( $this->mParams['disabled'] ) ) {
2098 $attribs['disabled'] = 'disabled';
2101 # TODO: should this produce an unordered list perhaps?
2102 foreach ( $options as $label => $info ) {
2103 if ( is_array( $info ) ) {
2104 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2105 $html .= $this->formatOptions( $info, $value );
2106 } else {
2107 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2108 $radio = Xml::radio(
2109 $this->mName,
2110 $info,
2111 $info == $value,
2112 $attribs + array( 'id' => $id )
2114 $radio .= '&#160;' .
2115 Html::rawElement( 'label', array( 'for' => $id ), $label );
2117 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2121 return $html;
2124 protected function needsLabel() {
2125 return false;
2130 * An information field (text blob), not a proper input.
2132 class HTMLInfoField extends HTMLFormField {
2133 public function __construct( $info ) {
2134 $info['nodata'] = true;
2136 parent::__construct( $info );
2139 public function getInputHTML( $value ) {
2140 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2143 public function getTableRow( $value ) {
2144 if ( !empty( $this->mParams['rawrow'] ) ) {
2145 return $value;
2148 return parent::getTableRow( $value );
2152 * @since 1.20
2154 public function getDiv( $value ) {
2155 if ( !empty( $this->mParams['rawrow'] ) ) {
2156 return $value;
2159 return parent::getDiv( $value );
2163 * @since 1.20
2165 public function getRaw( $value ) {
2166 if ( !empty( $this->mParams['rawrow'] ) ) {
2167 return $value;
2170 return parent::getRaw( $value );
2173 protected function needsLabel() {
2174 return false;
2178 class HTMLHiddenField extends HTMLFormField {
2179 public function __construct( $params ) {
2180 parent::__construct( $params );
2182 # Per HTML5 spec, hidden fields cannot be 'required'
2183 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2184 unset( $this->mParams['required'] );
2187 public function getTableRow( $value ) {
2188 $params = array();
2189 if ( $this->mID ) {
2190 $params['id'] = $this->mID;
2193 $this->mParent->addHiddenField(
2194 $this->mName,
2195 $this->mDefault,
2196 $params
2199 return '';
2203 * @since 1.20
2205 public function getDiv( $value ) {
2206 return $this->getTableRow( $value );
2210 * @since 1.20
2212 public function getRaw( $value ) {
2213 return $this->getTableRow( $value );
2216 public function getInputHTML( $value ) { return ''; }
2220 * Add a submit button inline in the form (as opposed to
2221 * HTMLForm::addButton(), which will add it at the end).
2223 class HTMLSubmitField extends HTMLFormField {
2225 public function __construct( $info ) {
2226 $info['nodata'] = true;
2227 parent::__construct( $info );
2230 public function getInputHTML( $value ) {
2231 return Xml::submitButton(
2232 $value,
2233 array(
2234 'class' => 'mw-htmlform-submit ' . $this->mClass,
2235 'name' => $this->mName,
2236 'id' => $this->mID,
2241 protected function needsLabel() {
2242 return false;
2246 * Button cannot be invalid
2247 * @param $value String
2248 * @param $alldata Array
2249 * @return Bool
2251 public function validate( $value, $alldata ) {
2252 return true;
2256 class HTMLEditTools extends HTMLFormField {
2257 public function getInputHTML( $value ) {
2258 return '';
2261 public function getTableRow( $value ) {
2262 $msg = $this->formatMsg();
2264 return '<tr><td></td><td class="mw-input">'
2265 . '<div class="mw-editTools">'
2266 . $msg->parseAsBlock()
2267 . "</div></td></tr>\n";
2271 * @since 1.20
2273 public function getDiv( $value ) {
2274 $msg = $this->formatMsg();
2275 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2279 * @since 1.20
2281 public function getRaw( $value ) {
2282 return $this->getDiv( $value );
2285 protected function formatMsg() {
2286 if ( empty( $this->mParams['message'] ) ) {
2287 $msg = wfMessage( 'edittools' );
2288 } else {
2289 $msg = wfMessage( $this->mParams['message'] );
2290 if ( $msg->isDisabled() ) {
2291 $msg = wfMessage( 'edittools' );
2294 $msg->inContentLanguage();
2295 return $msg;