Followup r81034, remove the global statements
[mediawiki.git] / includes / HTMLForm.php
blob7277908f9069d1818496af7b2c0bd6ac2a6d787d
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 $mSectionHeaders = array();
96 protected $mSectionFooters = array();
97 protected $mPost = '';
98 protected $mId;
100 protected $mSubmitID;
101 protected $mSubmitName;
102 protected $mSubmitText;
103 protected $mSubmitTooltip;
104 protected $mTitle;
105 protected $mMethod = 'post';
107 protected $mUseMultipart = false;
108 protected $mHiddenFields = array();
109 protected $mButtons = array();
111 protected $mWrapperLegend = false;
114 * Build a new HTMLForm from an array of field attributes
115 * @param $descriptor Array of Field constructs, as described above
116 * @param $messagePrefix String a prefix to go in front of default messages
118 public function __construct( $descriptor, $messagePrefix = '' ) {
119 $this->mMessagePrefix = $messagePrefix;
121 // Expand out into a tree.
122 $loadedDescriptor = array();
123 $this->mFlatFields = array();
125 foreach ( $descriptor as $fieldname => $info ) {
126 $section = isset( $info['section'] )
127 ? $info['section']
128 : '';
130 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
131 $this->mUseMultipart = true;
134 $field = self::loadInputFromParameters( $fieldname, $info );
135 $field->mParent = $this;
137 $setSection =& $loadedDescriptor;
138 if ( $section ) {
139 $sectionParts = explode( '/', $section );
141 while ( count( $sectionParts ) ) {
142 $newName = array_shift( $sectionParts );
144 if ( !isset( $setSection[$newName] ) ) {
145 $setSection[$newName] = array();
148 $setSection =& $setSection[$newName];
152 $setSection[$fieldname] = $field;
153 $this->mFlatFields[$fieldname] = $field;
156 $this->mFieldTree = $loadedDescriptor;
160 * Add the HTMLForm-specific JavaScript, if it hasn't been
161 * done already.
163 static function addJS() {
164 if ( self::$jsAdded ) return;
166 global $wgOut;
168 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
172 * Initialise a new Object for the field
173 * @param $descriptor input Descriptor, as described above
174 * @return HTMLFormField subclass
176 static function loadInputFromParameters( $fieldname, $descriptor ) {
177 if ( isset( $descriptor['class'] ) ) {
178 $class = $descriptor['class'];
179 } elseif ( isset( $descriptor['type'] ) ) {
180 $class = self::$typeMappings[$descriptor['type']];
181 $descriptor['class'] = $class;
184 if ( !$class ) {
185 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
188 $descriptor['fieldname'] = $fieldname;
190 $obj = new $class( $descriptor );
192 return $obj;
196 * Prepare form for submission
198 function prepareForm() {
199 # Check if we have the info we need
200 if ( ! $this->mTitle ) {
201 throw new MWException( "You must call setTitle() on an HTMLForm" );
204 // FIXME shouldn't this be closer to displayForm() ?
205 self::addJS();
207 # Load data from the request.
208 $this->loadData();
212 * Try submitting, with edit token check first
213 * @return Status|boolean
215 function tryAuthorizedSubmit() {
216 global $wgUser, $wgRequest;
217 $editToken = $wgRequest->getVal( 'wpEditToken' );
219 $result = false;
220 if ( $this->getMethod() != 'post' || $wgUser->matchEditToken( $editToken ) ) {
221 $result = $this->trySubmit();
223 return $result;
227 * The here's-one-I-made-earlier option: do the submission if
228 * posted, or display the form with or without funky valiation
229 * errors
230 * @return Bool or Status whether submission was successful.
232 function show() {
233 $this->prepareForm();
235 $result = $this->tryAuthorizedSubmit();
236 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ){
237 return $result;
240 $this->displayForm( $result );
241 return false;
245 * Validate all the fields, and call the submision callback
246 * function if everything is kosher.
247 * @return Mixed Bool true == Successful submission, Bool false
248 * == No submission attempted, anything else == Error to
249 * display.
251 function trySubmit() {
252 # Check for validation
253 foreach ( $this->mFlatFields as $fieldname => $field ) {
254 if ( !empty( $field->mParams['nodata'] ) ) {
255 continue;
257 if ( $field->validate(
258 $this->mFieldData[$fieldname],
259 $this->mFieldData )
260 !== true
262 return isset( $this->mValidationErrorMessage )
263 ? $this->mValidationErrorMessage
264 : array( 'htmlform-invalid-input' );
268 $callback = $this->mSubmitCallback;
270 $data = $this->filterDataForSubmit( $this->mFieldData );
272 $res = call_user_func( $callback, $data );
274 return $res;
278 * Set a callback to a function to do something with the form
279 * once it's been successfully validated.
280 * @param $cb String function name. The function will be passed
281 * the output from HTMLForm::filterDataForSubmit, and must
282 * return Bool true on success, Bool false if no submission
283 * was attempted, or String HTML output to display on error.
285 function setSubmitCallback( $cb ) {
286 $this->mSubmitCallback = $cb;
290 * Set a message to display on a validation error.
291 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
292 * (so each entry can be either a String or Array)
294 function setValidationErrorMessage( $msg ) {
295 $this->mValidationErrorMessage = $msg;
299 * Set the introductory message, overwriting any existing message.
300 * @param $msg String complete text of message to display
302 function setIntro( $msg ) { $this->mPre = $msg; }
305 * Add introductory text.
306 * @param $msg String complete text of message to display
308 function addPreText( $msg ) { $this->mPre .= $msg; }
311 * Add header text, inside the form.
312 * @param $msg String complete text of message to display
314 function addHeaderText( $msg, $section = null ) {
315 if ( is_null( $section ) ) {
316 $this->mHeader .= $msg;
317 } else {
318 if ( !isset( $this->mSectionHeaders[$section] ) ) {
319 $this->mSectionHeaders[$section] = '';
321 $this->mSectionHeaders[$section] .= $msg;
326 * Add footer text, inside the form.
327 * @param $msg String complete text of message to display
329 function addFooterText( $msg, $section = null ) {
330 if ( is_null( $section ) ) {
331 $this->mFooter .= $msg;
332 } else {
333 if ( !isset( $this->mSectionFooters[$section] ) ) {
334 $this->mSectionFooters[$section] = '';
336 $this->mSectionFooters[$section] .= $msg;
341 * Add text to the end of the display.
342 * @param $msg String complete text of message to display
344 function addPostText( $msg ) { $this->mPost .= $msg; }
347 * Add a hidden field to the output
348 * @param $name String field name. This will be used exactly as entered
349 * @param $value String field value
350 * @param $attribs Array
352 public function addHiddenField( $name, $value, $attribs = array() ) {
353 $attribs += array( 'name' => $name );
354 $this->mHiddenFields[] = array( $value, $attribs );
357 public function addButton( $name, $value, $id = null, $attribs = null ) {
358 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
362 * Display the form (sending to wgOut), with an appropriate error
363 * message or stack of messages, and any validation errors, etc.
364 * @param $submitResult Mixed output from HTMLForm::trySubmit()
366 function displayForm( $submitResult ) {
367 global $wgOut;
369 # For good measure (it is the default)
370 $wgOut->preventClickjacking();
372 $html = ''
373 . $this->getErrors( $submitResult )
374 . $this->mHeader
375 . $this->getBody()
376 . $this->getHiddenFields()
377 . $this->getButtons()
378 . $this->mFooter
381 $html = $this->wrapForm( $html );
383 $wgOut->addHTML( ''
384 . $this->mPre
385 . $html
386 . $this->mPost
391 * Wrap the form innards in an actual <form> element
392 * @param $html String HTML contents to wrap.
393 * @return String wrapped HTML.
395 function wrapForm( $html ) {
397 # Include a <fieldset> wrapper for style, if requested.
398 if ( $this->mWrapperLegend !== false ) {
399 $html = Xml::fieldset( $this->mWrapperLegend, $html );
401 # Use multipart/form-data
402 $encType = $this->mUseMultipart
403 ? 'multipart/form-data'
404 : 'application/x-www-form-urlencoded';
405 # Attributes
406 $attribs = array(
407 'action' => $this->getTitle()->getFullURL(),
408 'method' => $this->mMethod,
409 'class' => 'visualClear',
410 'enctype' => $encType,
412 if ( !empty( $this->mId ) ) {
413 $attribs['id'] = $this->mId;
416 return Html::rawElement( 'form', $attribs, $html );
420 * Get the hidden fields that should go inside the form.
421 * @return String HTML.
423 function getHiddenFields() {
424 global $wgUser;
426 $html = '';
428 if( $this->getMethod() == 'post' ){
429 $html .= Html::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
430 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
433 foreach ( $this->mHiddenFields as $data ) {
434 list( $value, $attribs ) = $data;
435 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
438 return $html;
442 * Get the submit and (potentially) reset buttons.
443 * @return String HTML.
445 function getButtons() {
446 $html = '';
447 $attribs = array();
449 if ( isset( $this->mSubmitID ) ) {
450 $attribs['id'] = $this->mSubmitID;
453 if ( isset( $this->mSubmitName ) ) {
454 $attribs['name'] = $this->mSubmitName;
457 if ( isset( $this->mSubmitTooltip ) ) {
458 global $wgUser;
459 $attribs += $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip );
462 $attribs['class'] = 'mw-htmlform-submit';
464 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
466 if ( $this->mShowReset ) {
467 $html .= Html::element(
468 'input',
469 array(
470 'type' => 'reset',
471 'value' => wfMsg( 'htmlform-reset' )
473 ) . "\n";
476 foreach ( $this->mButtons as $button ) {
477 $attrs = array(
478 'type' => 'submit',
479 'name' => $button['name'],
480 'value' => $button['value']
483 if ( $button['attribs'] ) {
484 $attrs += $button['attribs'];
487 if ( isset( $button['id'] ) ) {
488 $attrs['id'] = $button['id'];
491 $html .= Html::element( 'input', $attrs );
494 return $html;
498 * Get the whole body of the form.
500 function getBody() {
501 return $this->displaySection( $this->mFieldTree );
505 * Format and display an error message stack.
506 * @param $errors Mixed String or Array of message keys
507 * @return String
509 function getErrors( $errors ) {
510 if ( $errors instanceof Status ) {
511 global $wgOut;
512 $errorstr = $wgOut->parse( $errors->getWikiText() );
513 } elseif ( is_array( $errors ) ) {
514 $errorstr = $this->formatErrors( $errors );
515 } else {
516 $errorstr = $errors;
519 return $errorstr
520 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
521 : '';
525 * Format a stack of error messages into a single HTML string
526 * @param $errors Array of message keys/values
527 * @return String HTML, a <ul> list of errors
529 static function formatErrors( $errors ) {
530 $errorstr = '';
532 foreach ( $errors as $error ) {
533 if ( is_array( $error ) ) {
534 $msg = array_shift( $error );
535 } else {
536 $msg = $error;
537 $error = array();
540 $errorstr .= Html::rawElement(
541 'li',
542 null,
543 wfMsgExt( $msg, array( 'parseinline' ), $error )
547 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
549 return $errorstr;
553 * Set the text for the submit button
554 * @param $t String plaintext.
556 function setSubmitText( $t ) {
557 $this->mSubmitText = $t;
561 * Get the text for the submit button, either customised or a default.
562 * @return unknown_type
564 function getSubmitText() {
565 return $this->mSubmitText
566 ? $this->mSubmitText
567 : wfMsg( 'htmlform-submit' );
570 public function setSubmitName( $name ) {
571 $this->mSubmitName = $name;
574 public function setSubmitTooltip( $name ) {
575 $this->mSubmitTooltip = $name;
579 * Set the id for the submit button.
580 * @param $t String. FIXME: Integrity is *not* validated
582 function setSubmitID( $t ) {
583 $this->mSubmitID = $t;
586 public function setId( $id ) {
587 $this->mId = $id;
590 * Prompt the whole form to be wrapped in a <fieldset>, with
591 * this text as its <legend> element.
592 * @param $legend String HTML to go inside the <legend> element.
593 * Will be escaped
595 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
598 * Set the prefix for various default messages
599 * TODO: currently only used for the <fieldset> legend on forms
600 * with multiple sections; should be used elsewhre?
601 * @param $p String
603 function setMessagePrefix( $p ) {
604 $this->mMessagePrefix = $p;
608 * Set the title for form submission
609 * @param $t Title of page the form is on/should be posted to
611 function setTitle( $t ) {
612 $this->mTitle = $t;
616 * Get the title
617 * @return Title
619 function getTitle() {
620 return $this->mTitle;
624 * Set the method used to submit the form
625 * @param $method String
627 public function setMethod( $method='post' ){
628 $this->mMethod = $method;
631 public function getMethod(){
632 return $this->mMethod;
636 * TODO: Document
637 * @param $fields
639 function displaySection( $fields, $sectionName = '' ) {
640 $tableHtml = '';
641 $subsectionHtml = '';
642 $hasLeftColumn = false;
644 foreach ( $fields as $key => $value ) {
645 if ( is_object( $value ) ) {
646 $v = empty( $value->mParams['nodata'] )
647 ? $this->mFieldData[$key]
648 : $value->getDefault();
649 $tableHtml .= $value->getTableRow( $v );
651 if ( $value->getLabel() != '&#160;' )
652 $hasLeftColumn = true;
653 } elseif ( is_array( $value ) ) {
654 $section = $this->displaySection( $value, $key );
655 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
656 if ( isset( $this->mSectionHeaders[$key] ) ) {
657 $section = $this->mSectionHeaders[$key] . $section;
659 if ( isset( $this->mSectionFooters[$key] ) ) {
660 $section .= $this->mSectionFooters[$key];
662 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
666 $classes = array();
668 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
669 $classes[] = 'mw-htmlform-nolabel';
672 $attribs = array(
673 'class' => implode( ' ', $classes ),
676 if ( $sectionName ) {
677 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
680 $tableHtml = Html::rawElement( 'table', $attribs,
681 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
683 return $subsectionHtml . "\n" . $tableHtml;
687 * Construct the form fields from the Descriptor array
689 function loadData() {
690 global $wgRequest;
692 $fieldData = array();
694 foreach ( $this->mFlatFields as $fieldname => $field ) {
695 if ( !empty( $field->mParams['nodata'] ) ) {
696 continue;
697 } elseif ( !empty( $field->mParams['disabled'] ) ) {
698 $fieldData[$fieldname] = $field->getDefault();
699 } else {
700 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
704 # Filter data.
705 foreach ( $fieldData as $name => &$value ) {
706 $field = $this->mFlatFields[$name];
707 $value = $field->filter( $value, $this->mFlatFields );
710 $this->mFieldData = $fieldData;
714 * Stop a reset button being shown for this form
715 * @param $suppressReset Bool set to false to re-enable the
716 * button again
718 function suppressReset( $suppressReset = true ) {
719 $this->mShowReset = !$suppressReset;
723 * Overload this if you want to apply special filtration routines
724 * to the form as a whole, after it's submitted but before it's
725 * processed.
726 * @param $data
727 * @return unknown_type
729 function filterDataForSubmit( $data ) {
730 return $data;
735 * The parent class to generate form fields. Any field type should
736 * be a subclass of this.
738 abstract class HTMLFormField {
740 protected $mValidationCallback;
741 protected $mFilterCallback;
742 protected $mName;
743 public $mParams;
744 protected $mLabel; # String label. Set on construction
745 protected $mID;
746 protected $mClass = '';
747 protected $mDefault;
748 public $mParent;
751 * This function must be implemented to return the HTML to generate
752 * the input object itself. It should not implement the surrounding
753 * table cells/rows, or labels/help messages.
754 * @param $value String the value to set the input to; eg a default
755 * text for a text input.
756 * @return String valid HTML.
758 abstract function getInputHTML( $value );
761 * Override this function to add specific validation checks on the
762 * field input. Don't forget to call parent::validate() to ensure
763 * that the user-defined callback mValidationCallback is still run
764 * @param $value String the value the field was submitted with
765 * @param $alldata Array the data collected from the form
766 * @return Mixed Bool true on success, or String error to display.
768 function validate( $value, $alldata ) {
769 if ( isset( $this->mValidationCallback ) ) {
770 return call_user_func( $this->mValidationCallback, $value, $alldata );
773 if ( isset( $this->mParams['required'] ) && $value === '' ) {
774 return wfMsgExt( 'htmlform-required', 'parseinline' );
777 return true;
780 function filter( $value, $alldata ) {
781 if ( isset( $this->mFilterCallback ) ) {
782 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
785 return $value;
789 * Should this field have a label, or is there no input element with the
790 * appropriate id for the label to point to?
792 * @return bool True to output a label, false to suppress
794 protected function needsLabel() {
795 return true;
799 * Get the value that this input has been set to from a posted form,
800 * or the input's default value if it has not been set.
801 * @param $request WebRequest
802 * @return String the value
804 function loadDataFromRequest( $request ) {
805 if ( $request->getCheck( $this->mName ) ) {
806 return $request->getText( $this->mName );
807 } else {
808 return $this->getDefault();
813 * Initialise the object
814 * @param $params Associative Array. See HTMLForm doc for syntax.
816 function __construct( $params ) {
817 $this->mParams = $params;
819 # Generate the label from a message, if possible
820 if ( isset( $params['label-message'] ) ) {
821 $msgInfo = $params['label-message'];
823 if ( is_array( $msgInfo ) ) {
824 $msg = array_shift( $msgInfo );
825 } else {
826 $msg = $msgInfo;
827 $msgInfo = array();
830 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
831 } elseif ( isset( $params['label'] ) ) {
832 $this->mLabel = $params['label'];
835 $this->mName = "wp{$params['fieldname']}";
836 if ( isset( $params['name'] ) ) {
837 $this->mName = $params['name'];
840 $validName = Sanitizer::escapeId( $this->mName );
841 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
842 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
845 $this->mID = "mw-input-{$this->mName}";
847 if ( isset( $params['default'] ) ) {
848 $this->mDefault = $params['default'];
851 if ( isset( $params['id'] ) ) {
852 $id = $params['id'];
853 $validId = Sanitizer::escapeId( $id );
855 if ( $id != $validId ) {
856 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
859 $this->mID = $id;
862 if ( isset( $params['cssclass'] ) ) {
863 $this->mClass = $params['cssclass'];
866 if ( isset( $params['validation-callback'] ) ) {
867 $this->mValidationCallback = $params['validation-callback'];
870 if ( isset( $params['filter-callback'] ) ) {
871 $this->mFilterCallback = $params['filter-callback'];
876 * Get the complete table row for the input, including help text,
877 * labels, and whatever.
878 * @param $value String the value to set the input to.
879 * @return String complete HTML table row.
881 function getTableRow( $value ) {
882 # Check for invalid data.
883 global $wgRequest;
885 $errors = $this->validate( $value, $this->mParent->mFieldData );
887 $cellAttributes = array();
888 $verticalLabel = false;
890 if ( !empty($this->mParams['vertical-label']) ) {
891 $cellAttributes['colspan'] = 2;
892 $verticalLabel = true;
895 if ( $errors === true || ( !$wgRequest->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
896 $errors = '';
897 } else {
898 $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
901 $label = $this->getLabelHtml( $cellAttributes );
902 $field = Html::rawElement(
903 'td',
904 array( 'class' => 'mw-input' ) + $cellAttributes,
905 $this->getInputHTML( $value ) . "\n$errors"
908 $fieldType = get_class( $this );
910 if ($verticalLabel) {
911 $html = Html::rawElement( 'tr',
912 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
913 $html .= Html::rawElement( 'tr',
914 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
915 $field );
916 } else {
917 $html = Html::rawElement( 'tr',
918 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
919 $label . $field );
922 $helptext = null;
924 if ( isset( $this->mParams['help-message'] ) ) {
925 $msg = $this->mParams['help-message'];
926 $helptext = wfMsgExt( $msg, 'parseinline' );
927 if ( wfEmptyMsg( $msg, $helptext ) ) {
928 # Never mind
929 $helptext = null;
931 } elseif ( isset( $this->mParams['help-messages'] ) ) {
932 # help-message can be passed a message key (string) or an array containing
933 # a message key and additional parameters. This makes it impossible to pass
934 # an array of message key
935 foreach( $this->mParams['help-messages'] as $msg ) {
936 $candidate = wfMsgExt( $msg, 'parseinline' );
937 if( wfEmptyMsg( $msg ) ) {
938 $candidate = null;
940 $helptext .= $candidate; // append message
942 } elseif ( isset( $this->mParams['help'] ) ) {
943 $helptext = $this->mParams['help'];
946 if ( !is_null( $helptext ) ) {
947 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
948 $helptext );
949 $row = Html::rawElement( 'tr', array(), $row );
950 $html .= "$row\n";
953 return $html;
956 function getLabel() {
957 return $this->mLabel;
959 function getLabelHtml( $cellAttributes = array() ) {
960 # Don't output a for= attribute for labels with no associated input.
961 # Kind of hacky here, possibly we don't want these to be <label>s at all.
962 $for = array();
964 if ( $this->needsLabel() ) {
965 $for['for'] = $this->mID;
968 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
969 Html::rawElement( 'label', $for, $this->getLabel() )
973 function getDefault() {
974 if ( isset( $this->mDefault ) ) {
975 return $this->mDefault;
976 } else {
977 return null;
982 * Returns the attributes required for the tooltip and accesskey.
984 * @return array Attributes
986 public function getTooltipAndAccessKey() {
987 if ( empty( $this->mParams['tooltip'] ) ) {
988 return array();
991 global $wgUser;
993 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
997 * flatten an array of options to a single array, for instance,
998 * a set of <options> inside <optgroups>.
999 * @param $options Associative Array with values either Strings
1000 * or Arrays
1001 * @return Array flattened input
1003 public static function flattenOptions( $options ) {
1004 $flatOpts = array();
1006 foreach ( $options as $value ) {
1007 if ( is_array( $value ) ) {
1008 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1009 } else {
1010 $flatOpts[] = $value;
1014 return $flatOpts;
1018 class HTMLTextField extends HTMLFormField {
1019 function getSize() {
1020 return isset( $this->mParams['size'] )
1021 ? $this->mParams['size']
1022 : 45;
1025 function getInputHTML( $value ) {
1026 $attribs = array(
1027 'id' => $this->mID,
1028 'name' => $this->mName,
1029 'size' => $this->getSize(),
1030 'value' => $value,
1031 ) + $this->getTooltipAndAccessKey();
1033 if ( isset( $this->mParams['maxlength'] ) ) {
1034 $attribs['maxlength'] = $this->mParams['maxlength'];
1037 if ( !empty( $this->mParams['disabled'] ) ) {
1038 $attribs['disabled'] = 'disabled';
1041 # TODO: Enforce pattern, step, required, readonly on the server side as
1042 # well
1043 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1044 'placeholder' ) as $param ) {
1045 if ( isset( $this->mParams[$param] ) ) {
1046 $attribs[$param] = $this->mParams[$param];
1050 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1051 if ( isset( $this->mParams[$param] ) ) {
1052 $attribs[$param] = '';
1056 # Implement tiny differences between some field variants
1057 # here, rather than creating a new class for each one which
1058 # is essentially just a clone of this one.
1059 if ( isset( $this->mParams['type'] ) ) {
1060 switch ( $this->mParams['type'] ) {
1061 case 'email':
1062 $attribs['type'] = 'email';
1063 break;
1064 case 'int':
1065 $attribs['type'] = 'number';
1066 break;
1067 case 'float':
1068 $attribs['type'] = 'number';
1069 $attribs['step'] = 'any';
1070 break;
1071 # Pass through
1072 case 'password':
1073 case 'file':
1074 $attribs['type'] = $this->mParams['type'];
1075 break;
1079 return Html::element( 'input', $attribs );
1082 class HTMLTextAreaField extends HTMLFormField {
1083 function getCols() {
1084 return isset( $this->mParams['cols'] )
1085 ? $this->mParams['cols']
1086 : 80;
1089 function getRows() {
1090 return isset( $this->mParams['rows'] )
1091 ? $this->mParams['rows']
1092 : 25;
1095 function getInputHTML( $value ) {
1096 $attribs = array(
1097 'id' => $this->mID,
1098 'name' => $this->mName,
1099 'cols' => $this->getCols(),
1100 'rows' => $this->getRows(),
1101 ) + $this->getTooltipAndAccessKey();
1104 if ( !empty( $this->mParams['disabled'] ) ) {
1105 $attribs['disabled'] = 'disabled';
1108 if ( !empty( $this->mParams['readonly'] ) ) {
1109 $attribs['readonly'] = 'readonly';
1112 foreach ( array( 'required', 'autofocus' ) as $param ) {
1113 if ( isset( $this->mParams[$param] ) ) {
1114 $attribs[$param] = '';
1118 return Html::element( 'textarea', $attribs, $value );
1123 * A field that will contain a numeric value
1125 class HTMLFloatField extends HTMLTextField {
1126 function getSize() {
1127 return isset( $this->mParams['size'] )
1128 ? $this->mParams['size']
1129 : 20;
1132 function validate( $value, $alldata ) {
1133 $p = parent::validate( $value, $alldata );
1135 if ( $p !== true ) {
1136 return $p;
1139 $value = trim( $value );
1141 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1142 # with the addition that a leading '+' sign is ok.
1143 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1144 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1147 # The "int" part of these message names is rather confusing.
1148 # They make equal sense for all numbers.
1149 if ( isset( $this->mParams['min'] ) ) {
1150 $min = $this->mParams['min'];
1152 if ( $min > $value ) {
1153 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1157 if ( isset( $this->mParams['max'] ) ) {
1158 $max = $this->mParams['max'];
1160 if ( $max < $value ) {
1161 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1165 return true;
1170 * A field that must contain a number
1172 class HTMLIntField extends HTMLFloatField {
1173 function validate( $value, $alldata ) {
1174 $p = parent::validate( $value, $alldata );
1176 if ( $p !== true ) {
1177 return $p;
1180 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1181 # with the addition that a leading '+' sign is ok. Note that leading zeros
1182 # are fine, and will be left in the input, which is useful for things like
1183 # phone numbers when you know that they are integers (the HTML5 type=tel
1184 # input does not require its value to be numeric). If you want a tidier
1185 # value to, eg, save in the DB, clean it up with intval().
1186 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1188 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1191 return true;
1196 * A checkbox field
1198 class HTMLCheckField extends HTMLFormField {
1199 function getInputHTML( $value ) {
1200 if ( !empty( $this->mParams['invert'] ) ) {
1201 $value = !$value;
1204 $attr = $this->getTooltipAndAccessKey();
1205 $attr['id'] = $this->mID;
1207 if ( !empty( $this->mParams['disabled'] ) ) {
1208 $attr['disabled'] = 'disabled';
1211 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1212 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1216 * For a checkbox, the label goes on the right hand side, and is
1217 * added in getInputHTML(), rather than HTMLFormField::getRow()
1219 function getLabel() {
1220 return '&#160;';
1223 function loadDataFromRequest( $request ) {
1224 $invert = false;
1225 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1226 $invert = true;
1229 // GetCheck won't work like we want for checks.
1230 if ( $request->getCheck( 'wpEditToken' ) ) {
1231 // XOR has the following truth table, which is what we want
1232 // INVERT VALUE | OUTPUT
1233 // true true | false
1234 // false true | true
1235 // false false | false
1236 // true false | true
1237 return $request->getBool( $this->mName ) xor $invert;
1238 } else {
1239 return $this->getDefault();
1245 * A select dropdown field. Basically a wrapper for Xmlselect class
1247 class HTMLSelectField extends HTMLFormField {
1248 function validate( $value, $alldata ) {
1249 $p = parent::validate( $value, $alldata );
1251 if ( $p !== true ) {
1252 return $p;
1255 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1257 if ( in_array( $value, $validOptions ) )
1258 return true;
1259 else
1260 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1263 function getInputHTML( $value ) {
1264 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1266 # If one of the options' 'name' is int(0), it is automatically selected.
1267 # because PHP sucks and things int(0) == 'some string'.
1268 # Working around this by forcing all of them to strings.
1269 foreach( $this->mParams['options'] as $key => &$opt ){
1270 if( is_int( $opt ) ){
1271 $opt = strval( $opt );
1274 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1276 if ( !empty( $this->mParams['disabled'] ) ) {
1277 $select->setAttribute( 'disabled', 'disabled' );
1280 $select->addOptions( $this->mParams['options'] );
1282 return $select->getHTML();
1287 * Select dropdown field, with an additional "other" textbox.
1289 class HTMLSelectOrOtherField extends HTMLTextField {
1290 static $jsAdded = false;
1292 function __construct( $params ) {
1293 if ( !in_array( 'other', $params['options'], true ) ) {
1294 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1297 parent::__construct( $params );
1300 static function forceToStringRecursive( $array ) {
1301 if ( is_array( $array ) ) {
1302 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1303 } else {
1304 return strval( $array );
1308 function getInputHTML( $value ) {
1309 $valInSelect = false;
1311 if ( $value !== false ) {
1312 $valInSelect = in_array(
1313 $value,
1314 HTMLFormField::flattenOptions( $this->mParams['options'] )
1318 $selected = $valInSelect ? $value : 'other';
1320 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1322 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1323 $select->addOptions( $opts );
1325 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1327 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1329 if ( !empty( $this->mParams['disabled'] ) ) {
1330 $select->setAttribute( 'disabled', 'disabled' );
1331 $tbAttribs['disabled'] = 'disabled';
1334 $select = $select->getHTML();
1336 if ( isset( $this->mParams['maxlength'] ) ) {
1337 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1340 $textbox = Html::input(
1341 $this->mName . '-other',
1342 $valInSelect ? '' : $value,
1343 'text',
1344 $tbAttribs
1347 return "$select<br />\n$textbox";
1350 function loadDataFromRequest( $request ) {
1351 if ( $request->getCheck( $this->mName ) ) {
1352 $val = $request->getText( $this->mName );
1354 if ( $val == 'other' ) {
1355 $val = $request->getText( $this->mName . '-other' );
1358 return $val;
1359 } else {
1360 return $this->getDefault();
1366 * Multi-select field
1368 class HTMLMultiSelectField extends HTMLFormField {
1369 function validate( $value, $alldata ) {
1370 $p = parent::validate( $value, $alldata );
1372 if ( $p !== true ) {
1373 return $p;
1376 if ( !is_array( $value ) ) {
1377 return false;
1380 # If all options are valid, array_intersect of the valid options
1381 # and the provided options will return the provided options.
1382 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1384 $validValues = array_intersect( $value, $validOptions );
1385 if ( count( $validValues ) == count( $value ) ) {
1386 return true;
1387 } else {
1388 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1392 function getInputHTML( $value ) {
1393 $html = $this->formatOptions( $this->mParams['options'], $value );
1395 return $html;
1398 function formatOptions( $options, $value ) {
1399 $html = '';
1401 $attribs = array();
1403 if ( !empty( $this->mParams['disabled'] ) ) {
1404 $attribs['disabled'] = 'disabled';
1407 foreach ( $options as $label => $info ) {
1408 if ( is_array( $info ) ) {
1409 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1410 $html .= $this->formatOptions( $info, $value );
1411 } else {
1412 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1414 $checkbox = Xml::check(
1415 $this->mName . '[]',
1416 in_array( $info, $value, true ),
1417 $attribs + $thisAttribs );
1418 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1420 $html .= $checkbox . '<br />';
1424 return $html;
1427 function loadDataFromRequest( $request ) {
1428 # won't work with getCheck
1429 if ( $request->getCheck( 'wpEditToken' ) ) {
1430 $arr = $request->getArray( $this->mName );
1432 if ( !$arr ) {
1433 $arr = array();
1436 return $arr;
1437 } else {
1438 return $this->getDefault();
1442 function getDefault() {
1443 if ( isset( $this->mDefault ) ) {
1444 return $this->mDefault;
1445 } else {
1446 return array();
1450 protected function needsLabel() {
1451 return false;
1456 * Radio checkbox fields.
1458 class HTMLRadioField extends HTMLFormField {
1459 function validate( $value, $alldata ) {
1460 $p = parent::validate( $value, $alldata );
1462 if ( $p !== true ) {
1463 return $p;
1466 if ( !is_string( $value ) && !is_int( $value ) ) {
1467 return false;
1470 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1472 if ( in_array( $value, $validOptions ) ) {
1473 return true;
1474 } else {
1475 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1480 * This returns a block of all the radio options, in one cell.
1481 * @see includes/HTMLFormField#getInputHTML()
1483 function getInputHTML( $value ) {
1484 $html = $this->formatOptions( $this->mParams['options'], $value );
1486 return $html;
1489 function formatOptions( $options, $value ) {
1490 $html = '';
1492 $attribs = array();
1493 if ( !empty( $this->mParams['disabled'] ) ) {
1494 $attribs['disabled'] = 'disabled';
1497 # TODO: should this produce an unordered list perhaps?
1498 foreach ( $options as $label => $info ) {
1499 if ( is_array( $info ) ) {
1500 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1501 $html .= $this->formatOptions( $info, $value );
1502 } else {
1503 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1504 $html .= Xml::radio(
1505 $this->mName,
1506 $info,
1507 $info == $value,
1508 $attribs + array( 'id' => $id )
1510 $html .= '&#160;' .
1511 Html::rawElement( 'label', array( 'for' => $id ), $label );
1513 $html .= "<br />\n";
1517 return $html;
1520 protected function needsLabel() {
1521 return false;
1526 * An information field (text blob), not a proper input.
1528 class HTMLInfoField extends HTMLFormField {
1529 function __construct( $info ) {
1530 $info['nodata'] = true;
1532 parent::__construct( $info );
1535 function getInputHTML( $value ) {
1536 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1539 function getTableRow( $value ) {
1540 if ( !empty( $this->mParams['rawrow'] ) ) {
1541 return $value;
1544 return parent::getTableRow( $value );
1547 protected function needsLabel() {
1548 return false;
1552 class HTMLHiddenField extends HTMLFormField {
1553 public function __construct( $params ) {
1554 parent::__construct( $params );
1556 # Per HTML5 spec, hidden fields cannot be 'required'
1557 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1558 unset( $this->mParams['required'] );
1561 public function getTableRow( $value ) {
1562 $params = array();
1563 if ( $this->mID ) {
1564 $params['id'] = $this->mID;
1567 $this->mParent->addHiddenField(
1568 $this->mName,
1569 $this->mDefault,
1570 $params
1573 return '';
1576 public function getInputHTML( $value ) { return ''; }
1580 * Add a submit button inline in the form (as opposed to
1581 * HTMLForm::addButton(), which will add it at the end).
1583 class HTMLSubmitField extends HTMLFormField {
1585 function __construct( $info ) {
1586 $info['nodata'] = true;
1587 parent::__construct( $info );
1590 function getInputHTML( $value ) {
1591 return Xml::submitButton(
1592 $value,
1593 array(
1594 'class' => 'mw-htmlform-submit',
1595 'name' => $this->mName,
1596 'id' => $this->mID,
1601 protected function needsLabel() {
1602 return false;
1606 * Button cannot be invalid
1608 public function validate( $value, $alldata ){
1609 return true;
1613 class HTMLEditTools extends HTMLFormField {
1614 public function getInputHTML( $value ) {
1615 return '';
1618 public function getTableRow( $value ) {
1619 return "<tr><td></td><td class=\"mw-input\">"
1620 . '<div class="mw-editTools">'
1621 . wfMsgExt( empty( $this->mParams['message'] )
1622 ? 'edittools' : $this->mParams['message'],
1623 array( 'parse', 'content' ) )
1624 . "</div></td></tr>\n";