HTMLForm mutators can now be chained
[lhc/web/wiklou.git] / includes / HTMLForm.php
1 <?php
2 /**
3 * HTML form generation and submission handling.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * Object handling generic submission, CSRF protection, layout and
25 * other logic for UI forms. in a reusable manner.
26 *
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.
32 *
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.
36 *
37 * The constructor input is an associative array of $fieldname => $info,
38 * where $info is an Associative Array with any of the following:
39 *
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.
75 *
76 * Since 1.20, you can chain mutators to ease the form generation:
77 * @par Example:
78 * @code
79 * $form = new HTMLForm( $someFields );
80 * $form->setMethod( 'get' )
81 * ->setWrapperLegendMsg( 'message-key' )
82 * ->suppressReset()
83 * ->prepareForm()
84 * ->displayForm();
85 * @endcode
86 * Note that you will have prepareForm and displayForm at the end. Other
87 * methods call done after that would simply not be part of the form :(
88 *
89 * TODO: Document 'section' / 'subsection' stuff
90 */
91 class HTMLForm extends ContextSource {
92
93 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
94 static $typeMappings = array(
95 'text' => 'HTMLTextField',
96 'textarea' => 'HTMLTextAreaField',
97 'select' => 'HTMLSelectField',
98 'radio' => 'HTMLRadioField',
99 'multiselect' => 'HTMLMultiSelectField',
100 'check' => 'HTMLCheckField',
101 'toggle' => 'HTMLCheckField',
102 'int' => 'HTMLIntField',
103 'float' => 'HTMLFloatField',
104 'info' => 'HTMLInfoField',
105 'selectorother' => 'HTMLSelectOrOtherField',
106 'selectandother' => 'HTMLSelectAndOtherField',
107 'submit' => 'HTMLSubmitField',
108 'hidden' => 'HTMLHiddenField',
109 'edittools' => 'HTMLEditTools',
110
111 // HTMLTextField will output the correct type="" attribute automagically.
112 // There are about four zillion other HTML5 input types, like url, but
113 // we don't use those at the moment, so no point in adding all of them.
114 'email' => 'HTMLTextField',
115 'password' => 'HTMLTextField',
116 );
117
118 protected $mMessagePrefix;
119
120 /** @var HTMLFormField[] */
121 protected $mFlatFields;
122
123 protected $mFieldTree;
124 protected $mShowReset = false;
125 public $mFieldData;
126
127 protected $mSubmitCallback;
128 protected $mValidationErrorMessage;
129
130 protected $mPre = '';
131 protected $mHeader = '';
132 protected $mFooter = '';
133 protected $mSectionHeaders = array();
134 protected $mSectionFooters = array();
135 protected $mPost = '';
136 protected $mId;
137
138 protected $mSubmitID;
139 protected $mSubmitName;
140 protected $mSubmitText;
141 protected $mSubmitTooltip;
142
143 protected $mTitle;
144 protected $mMethod = 'post';
145
146 /**
147 * Form action URL. false means we will use the URL to set Title
148 * @since 1.19
149 * @var bool|string
150 */
151 protected $mAction = false;
152
153 protected $mUseMultipart = false;
154 protected $mHiddenFields = array();
155 protected $mButtons = array();
156
157 protected $mWrapperLegend = false;
158
159 /**
160 * If true, sections that contain both fields and subsections will
161 * render their subsections before their fields.
162 *
163 * Subclasses may set this to false to render subsections after fields
164 * instead.
165 */
166 protected $mSubSectionBeforeFields = true;
167
168 /**
169 * Format in which to display form. For viable options,
170 * @see $availableDisplayFormats
171 * @var String
172 */
173 protected $displayFormat = 'table';
174
175 /**
176 * Available formats in which to display the form
177 * @var Array
178 */
179 protected $availableDisplayFormats = array(
180 'table',
181 'div',
182 'raw',
183 );
184
185 /**
186 * Build a new HTMLForm from an array of field attributes
187 * @param $descriptor Array of Field constructs, as described above
188 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
189 * Obviates the need to call $form->setTitle()
190 * @param $messagePrefix String a prefix to go in front of default messages
191 */
192 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
193 if ( $context instanceof IContextSource ) {
194 $this->setContext( $context );
195 $this->mTitle = false; // We don't need them to set a title
196 $this->mMessagePrefix = $messagePrefix;
197 } else {
198 // B/C since 1.18
199 if ( is_string( $context ) && $messagePrefix === '' ) {
200 // it's actually $messagePrefix
201 $this->mMessagePrefix = $context;
202 }
203 }
204
205 // Expand out into a tree.
206 $loadedDescriptor = array();
207 $this->mFlatFields = array();
208
209 foreach ( $descriptor as $fieldname => $info ) {
210 $section = isset( $info['section'] )
211 ? $info['section']
212 : '';
213
214 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
215 $this->mUseMultipart = true;
216 }
217
218 $field = self::loadInputFromParameters( $fieldname, $info );
219 $field->mParent = $this;
220
221 $setSection =& $loadedDescriptor;
222 if ( $section ) {
223 $sectionParts = explode( '/', $section );
224
225 while ( count( $sectionParts ) ) {
226 $newName = array_shift( $sectionParts );
227
228 if ( !isset( $setSection[$newName] ) ) {
229 $setSection[$newName] = array();
230 }
231
232 $setSection =& $setSection[$newName];
233 }
234 }
235
236 $setSection[$fieldname] = $field;
237 $this->mFlatFields[$fieldname] = $field;
238 }
239
240 $this->mFieldTree = $loadedDescriptor;
241 }
242
243 /**
244 * Set format in which to display the form
245 * @param $format String the name of the format to use, must be one of
246 * $this->availableDisplayFormats
247 * @since 1.20
248 * @return HTMLForm $this for chaining calls (since 1.20)
249 */
250 public function setDisplayFormat( $format ) {
251 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
252 throw new MWException ( 'Display format must be one of ' . print_r( $this->availableDisplayFormats, true ) );
253 }
254 $this->displayFormat = $format;
255 return $this;
256 }
257
258 /**
259 * Getter for displayFormat
260 * @since 1.20
261 * @return String
262 */
263 public function getDisplayFormat() {
264 return $this->displayFormat;
265 }
266
267 /**
268 * Add the HTMLForm-specific JavaScript, if it hasn't been
269 * done already.
270 * @deprecated since 1.18 load modules with ResourceLoader instead
271 */
272 static function addJS() { wfDeprecated( __METHOD__, '1.18' ); }
273
274 /**
275 * Initialise a new Object for the field
276 * @param $fieldname string
277 * @param $descriptor string input Descriptor, as described above
278 * @return HTMLFormField subclass
279 */
280 static function loadInputFromParameters( $fieldname, $descriptor ) {
281 if ( isset( $descriptor['class'] ) ) {
282 $class = $descriptor['class'];
283 } elseif ( isset( $descriptor['type'] ) ) {
284 $class = self::$typeMappings[$descriptor['type']];
285 $descriptor['class'] = $class;
286 } else {
287 $class = null;
288 }
289
290 if ( !$class ) {
291 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
292 }
293
294 $descriptor['fieldname'] = $fieldname;
295
296 # TODO
297 # This will throw a fatal error whenever someone try to use
298 # 'class' to feed a CSS class instead of 'cssclass'. Would be
299 # great to avoid the fatal error and show a nice error.
300 $obj = new $class( $descriptor );
301
302 return $obj;
303 }
304
305 /**
306 * Prepare form for submission.
307 *
308 * @attention When doing method chaining, that should be the very last
309 * method call before displayForm().
310 *
311 * @return HTMLForm $this for chaining calls (since 1.20)
312 */
313 function prepareForm() {
314 # Check if we have the info we need
315 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
316 throw new MWException( "You must call setTitle() on an HTMLForm" );
317 }
318
319 # Load data from the request.
320 $this->loadData();
321 return $this;
322 }
323
324 /**
325 * Try submitting, with edit token check first
326 * @return Status|boolean
327 */
328 function tryAuthorizedSubmit() {
329 $result = false;
330
331 $submit = false;
332 if ( $this->getMethod() != 'post' ) {
333 $submit = true; // no session check needed
334 } elseif ( $this->getRequest()->wasPosted() ) {
335 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
336 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
337 // Session tokens for logged-out users have no security value.
338 // However, if the user gave one, check it in order to give a nice
339 // "session expired" error instead of "permission denied" or such.
340 $submit = $this->getUser()->matchEditToken( $editToken );
341 } else {
342 $submit = true;
343 }
344 }
345
346 if ( $submit ) {
347 $result = $this->trySubmit();
348 }
349
350 return $result;
351 }
352
353 /**
354 * The here's-one-I-made-earlier option: do the submission if
355 * posted, or display the form with or without funky validation
356 * errors
357 * @return Bool or Status whether submission was successful.
358 */
359 function show() {
360 $this->prepareForm();
361
362 $result = $this->tryAuthorizedSubmit();
363 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
364 return $result;
365 }
366
367 $this->displayForm( $result );
368 return false;
369 }
370
371 /**
372 * Validate all the fields, and call the submision callback
373 * function if everything is kosher.
374 * @return Mixed Bool true == Successful submission, Bool false
375 * == No submission attempted, anything else == Error to
376 * display.
377 */
378 function trySubmit() {
379 # Check for validation
380 foreach ( $this->mFlatFields as $fieldname => $field ) {
381 if ( !empty( $field->mParams['nodata'] ) ) {
382 continue;
383 }
384 if ( $field->validate(
385 $this->mFieldData[$fieldname],
386 $this->mFieldData )
387 !== true
388 ) {
389 return isset( $this->mValidationErrorMessage )
390 ? $this->mValidationErrorMessage
391 : array( 'htmlform-invalid-input' );
392 }
393 }
394
395 $callback = $this->mSubmitCallback;
396 if ( !is_callable( $callback ) ) {
397 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
398 }
399
400 $data = $this->filterDataForSubmit( $this->mFieldData );
401
402 $res = call_user_func( $callback, $data, $this );
403
404 return $res;
405 }
406
407 /**
408 * Set a callback to a function to do something with the form
409 * once it's been successfully validated.
410 * @param $cb String function name. The function will be passed
411 * the output from HTMLForm::filterDataForSubmit, and must
412 * return Bool true on success, Bool false if no submission
413 * was attempted, or String HTML output to display on error.
414 * @return HTMLForm $this for chaining calls (since 1.20)
415 */
416 function setSubmitCallback( $cb ) {
417 $this->mSubmitCallback = $cb;
418 return $this;
419 }
420
421 /**
422 * Set a message to display on a validation error.
423 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
424 * (so each entry can be either a String or Array)
425 * @return HTMLForm $this for chaining calls (since 1.20)
426 */
427 function setValidationErrorMessage( $msg ) {
428 $this->mValidationErrorMessage = $msg;
429 return $this;
430 }
431
432 /**
433 * Set the introductory message, overwriting any existing message.
434 * @param $msg String complete text of message to display
435 * @return HTMLForm $this for chaining calls (since 1.20)
436 */
437 function setIntro( $msg ) {
438 $this->setPreText( $msg );
439 return $this;
440 }
441
442 /**
443 * Set the introductory message, overwriting any existing message.
444 * @since 1.19
445 * @param $msg String complete text of message to display
446 * @return HTMLForm $this for chaining calls (since 1.20)
447 */
448 function setPreText( $msg ) {
449 $this->mPre = $msg;
450 return $this;
451 }
452
453 /**
454 * Add introductory text.
455 * @param $msg String complete text of message to display
456 * @return HTMLForm $this for chaining calls (since 1.20)
457 */
458 function addPreText( $msg ) {
459 $this->mPre .= $msg;
460 return $this;
461 }
462
463 /**
464 * Add header text, inside the form.
465 * @param $msg String complete text of message to display
466 * @param $section string The section to add the header to
467 * @return HTMLForm $this for chaining calls (since 1.20)
468 */
469 function addHeaderText( $msg, $section = null ) {
470 if ( is_null( $section ) ) {
471 $this->mHeader .= $msg;
472 } else {
473 if ( !isset( $this->mSectionHeaders[$section] ) ) {
474 $this->mSectionHeaders[$section] = '';
475 }
476 $this->mSectionHeaders[$section] .= $msg;
477 }
478 return $this;
479 }
480
481 /**
482 * Set header text, inside the form.
483 * @since 1.19
484 * @param $msg String complete text of message to display
485 * @param $section The section to add the header to
486 * @return HTMLForm $this for chaining calls (since 1.20)
487 */
488 function setHeaderText( $msg, $section = null ) {
489 if ( is_null( $section ) ) {
490 $this->mHeader = $msg;
491 } else {
492 $this->mSectionHeaders[$section] = $msg;
493 }
494 return $this;
495 }
496
497 /**
498 * Add footer text, inside the form.
499 * @param $msg String complete text of message to display
500 * @param $section string The section to add the footer text to
501 * @return HTMLForm $this for chaining calls (since 1.20)
502 */
503 function addFooterText( $msg, $section = null ) {
504 if ( is_null( $section ) ) {
505 $this->mFooter .= $msg;
506 } else {
507 if ( !isset( $this->mSectionFooters[$section] ) ) {
508 $this->mSectionFooters[$section] = '';
509 }
510 $this->mSectionFooters[$section] .= $msg;
511 }
512 return $this;
513 }
514
515 /**
516 * Set footer text, inside the form.
517 * @since 1.19
518 * @param $msg String complete text of message to display
519 * @param $section string The section to add the footer text to
520 * @return HTMLForm $this for chaining calls (since 1.20)
521 */
522 function setFooterText( $msg, $section = null ) {
523 if ( is_null( $section ) ) {
524 $this->mFooter = $msg;
525 } else {
526 $this->mSectionFooters[$section] = $msg;
527 }
528 return $this;
529 }
530
531 /**
532 * Add text to the end of the display.
533 * @param $msg String complete text of message to display
534 * @return HTMLForm $this for chaining calls (since 1.20)
535 */
536 function addPostText( $msg ) {
537 $this->mPost .= $msg;
538 return $this;
539 }
540
541 /**
542 * Set text at the end of the display.
543 * @param $msg String complete text of message to display
544 * @return HTMLForm $this for chaining calls (since 1.20)
545 */
546 function setPostText( $msg ) {
547 $this->mPost = $msg;
548 return $this;
549 }
550
551 /**
552 * Add a hidden field to the output
553 * @param $name String field name. This will be used exactly as entered
554 * @param $value String field value
555 * @param $attribs Array
556 * @return HTMLForm $this for chaining calls (since 1.20)
557 */
558 public function addHiddenField( $name, $value, $attribs = array() ) {
559 $attribs += array( 'name' => $name );
560 $this->mHiddenFields[] = array( $value, $attribs );
561 return $this;
562 }
563
564 /**
565 * Add a button to the form
566 * @param $name String field name.
567 * @param $value String field value
568 * @param $id String DOM id for the button (default: null)
569 * @param $attribs Array
570 * @return HTMLForm $this for chaining calls (since 1.20)
571 */
572 public function addButton( $name, $value, $id = null, $attribs = null ) {
573 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
574 return $this;
575 }
576
577 /**
578 * Display the form (sending to $wgOut), with an appropriate error
579 * message or stack of messages, and any validation errors, etc.
580 *
581 * @attention You should call prepareForm() before calling this function.
582 * Moreover, when doing method chaining this should be the very last method
583 * call just after prepareForm().
584 *
585 * @param $submitResult Mixed output from HTMLForm::trySubmit()
586 * @return Nothing, should be last call
587 */
588 function displayForm( $submitResult ) {
589 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
590 }
591
592 /**
593 * Returns the raw HTML generated by the form
594 * @param $submitResult Mixed output from HTMLForm::trySubmit()
595 * @return string
596 */
597 function getHTML( $submitResult ) {
598 # For good measure (it is the default)
599 $this->getOutput()->preventClickjacking();
600 $this->getOutput()->addModules( 'mediawiki.htmlform' );
601
602 $html = ''
603 . $this->getErrors( $submitResult )
604 . $this->mHeader
605 . $this->getBody()
606 . $this->getHiddenFields()
607 . $this->getButtons()
608 . $this->mFooter
609 ;
610
611 $html = $this->wrapForm( $html );
612
613 return '' . $this->mPre . $html . $this->mPost;
614 }
615
616 /**
617 * Wrap the form innards in an actual "<form>" element
618 * @param $html String HTML contents to wrap.
619 * @return String wrapped HTML.
620 */
621 function wrapForm( $html ) {
622
623 # Include a <fieldset> wrapper for style, if requested.
624 if ( $this->mWrapperLegend !== false ) {
625 $html = Xml::fieldset( $this->mWrapperLegend, $html );
626 }
627 # Use multipart/form-data
628 $encType = $this->mUseMultipart
629 ? 'multipart/form-data'
630 : 'application/x-www-form-urlencoded';
631 # Attributes
632 $attribs = array(
633 'action' => $this->mAction === false ? $this->getTitle()->getFullURL() : $this->mAction,
634 'method' => $this->mMethod,
635 'class' => 'visualClear',
636 'enctype' => $encType,
637 );
638 if ( !empty( $this->mId ) ) {
639 $attribs['id'] = $this->mId;
640 }
641
642 return Html::rawElement( 'form', $attribs, $html );
643 }
644
645 /**
646 * Get the hidden fields that should go inside the form.
647 * @return String HTML.
648 */
649 function getHiddenFields() {
650 global $wgArticlePath;
651
652 $html = '';
653 if ( $this->getMethod() == 'post' ) {
654 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
655 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
656 }
657
658 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
659 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
660 }
661
662 foreach ( $this->mHiddenFields as $data ) {
663 list( $value, $attribs ) = $data;
664 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
665 }
666
667 return $html;
668 }
669
670 /**
671 * Get the submit and (potentially) reset buttons.
672 * @return String HTML.
673 */
674 function getButtons() {
675 $html = '';
676 $attribs = array();
677
678 if ( isset( $this->mSubmitID ) ) {
679 $attribs['id'] = $this->mSubmitID;
680 }
681
682 if ( isset( $this->mSubmitName ) ) {
683 $attribs['name'] = $this->mSubmitName;
684 }
685
686 if ( isset( $this->mSubmitTooltip ) ) {
687 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
688 }
689
690 $attribs['class'] = 'mw-htmlform-submit';
691
692 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
693
694 if ( $this->mShowReset ) {
695 $html .= Html::element(
696 'input',
697 array(
698 'type' => 'reset',
699 'value' => wfMsg( 'htmlform-reset' )
700 )
701 ) . "\n";
702 }
703
704 foreach ( $this->mButtons as $button ) {
705 $attrs = array(
706 'type' => 'submit',
707 'name' => $button['name'],
708 'value' => $button['value']
709 );
710
711 if ( $button['attribs'] ) {
712 $attrs += $button['attribs'];
713 }
714
715 if ( isset( $button['id'] ) ) {
716 $attrs['id'] = $button['id'];
717 }
718
719 $html .= Html::element( 'input', $attrs );
720 }
721
722 return $html;
723 }
724
725 /**
726 * Get the whole body of the form.
727 * @return String
728 */
729 function getBody() {
730 return $this->displaySection( $this->mFieldTree );
731 }
732
733 /**
734 * Format and display an error message stack.
735 * @param $errors String|Array|Status
736 * @return String
737 */
738 function getErrors( $errors ) {
739 if ( $errors instanceof Status ) {
740 if ( $errors->isOK() ) {
741 $errorstr = '';
742 } else {
743 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
744 }
745 } elseif ( is_array( $errors ) ) {
746 $errorstr = $this->formatErrors( $errors );
747 } else {
748 $errorstr = $errors;
749 }
750
751 return $errorstr
752 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
753 : '';
754 }
755
756 /**
757 * Format a stack of error messages into a single HTML string
758 * @param $errors Array of message keys/values
759 * @return String HTML, a "<ul>" list of errors
760 */
761 public static function formatErrors( $errors ) {
762 $errorstr = '';
763
764 foreach ( $errors as $error ) {
765 if ( is_array( $error ) ) {
766 $msg = array_shift( $error );
767 } else {
768 $msg = $error;
769 $error = array();
770 }
771
772 $errorstr .= Html::rawElement(
773 'li',
774 array(),
775 wfMsgExt( $msg, array( 'parseinline' ), $error )
776 );
777 }
778
779 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
780
781 return $errorstr;
782 }
783
784 /**
785 * Set the text for the submit button
786 * @param $t String plaintext.
787 * @return HTMLForm $this for chaining calls (since 1.20)
788 */
789 function setSubmitText( $t ) {
790 $this->mSubmitText = $t;
791 return $this;
792 }
793
794 /**
795 * Set the text for the submit button to a message
796 * @since 1.19
797 * @param $msg String message key
798 * @return HTMLForm $this for chaining calls (since 1.20)
799 */
800 public function setSubmitTextMsg( $msg ) {
801 $this->setSubmitText( $this->msg( $msg )->text() );
802 return $this;
803 }
804
805 /**
806 * Get the text for the submit button, either customised or a default.
807 * @return string
808 */
809 function getSubmitText() {
810 return $this->mSubmitText
811 ? $this->mSubmitText
812 : wfMsg( 'htmlform-submit' );
813 }
814
815 /**
816 * @param $name String Submit button name
817 * @return HTMLForm $this for chaining calls (since 1.20)
818 */
819 public function setSubmitName( $name ) {
820 $this->mSubmitName = $name;
821 return $this;
822 }
823
824 /**
825 * @param $name String Tooltip for the submit button
826 * @return HTMLForm $this for chaining calls (since 1.20)
827 */
828 public function setSubmitTooltip( $name ) {
829 $this->mSubmitTooltip = $name;
830 return $this;
831 }
832
833 /**
834 * Set the id for the submit button.
835 * @param $t String.
836 * @todo FIXME: Integrity of $t is *not* validated
837 * @return HTMLForm $this for chaining calls (since 1.20)
838 */
839 function setSubmitID( $t ) {
840 $this->mSubmitID = $t;
841 return $this;
842 }
843
844 /**
845 * @param $id String DOM id for the form
846 * @return HTMLForm $this for chaining calls (since 1.20)
847 */
848 public function setId( $id ) {
849 $this->mId = $id;
850 return $this;
851 }
852 /**
853 * Prompt the whole form to be wrapped in a "<fieldset>", with
854 * this text as its "<legend>" element.
855 * @param $legend String HTML to go inside the "<legend>" element.
856 * Will be escaped
857 * @return HTMLForm $this for chaining calls (since 1.20)
858 */
859 public function setWrapperLegend( $legend ) {
860 $this->mWrapperLegend = $legend;
861 return $this;
862 }
863
864 /**
865 * Prompt the whole form to be wrapped in a "<fieldset>", with
866 * this message as its "<legend>" element.
867 * @since 1.19
868 * @param $msg String message key
869 * @return HTMLForm $this for chaining calls (since 1.20)
870 */
871 public function setWrapperLegendMsg( $msg ) {
872 $this->setWrapperLegend( $this->msg( $msg )->escaped() );
873 return $this;
874 }
875
876 /**
877 * Set the prefix for various default messages
878 * @todo currently only used for the "<fieldset>" legend on forms
879 * with multiple sections; should be used elsewhre?
880 * @param $p String
881 * @return HTMLForm $this for chaining calls (since 1.20)
882 */
883 function setMessagePrefix( $p ) {
884 $this->mMessagePrefix = $p;
885 return $this;
886 }
887
888 /**
889 * Set the title for form submission
890 * @param $t Title of page the form is on/should be posted to
891 * @return HTMLForm $this for chaining calls (since 1.20)
892 */
893 function setTitle( $t ) {
894 $this->mTitle = $t;
895 return $this;
896 }
897
898 /**
899 * Get the title
900 * @return Title
901 */
902 function getTitle() {
903 return $this->mTitle === false
904 ? $this->getContext()->getTitle()
905 : $this->mTitle;
906 }
907
908 /**
909 * Set the method used to submit the form
910 * @param $method String
911 * @return HTMLForm $this for chaining calls (since 1.20)
912 */
913 public function setMethod( $method = 'post' ) {
914 $this->mMethod = $method;
915 return $this;
916 }
917
918 public function getMethod() {
919 return $this->mMethod;
920 }
921
922 /**
923 * @todo Document
924 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
925 * @param $sectionName string ID attribute of the "<table>" tag for this section, ignored if empty
926 * @param $fieldsetIDPrefix string ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
927 * @return String
928 */
929 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
930 $displayFormat = $this->getDisplayFormat();
931
932 $html = '';
933 $subsectionHtml = '';
934 $hasLabel = false;
935
936 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ? 'getTableRow' : 'get' . ucfirst( $displayFormat );
937
938 foreach ( $fields as $key => $value ) {
939 if ( $value instanceof HTMLFormField ) {
940 $v = empty( $value->mParams['nodata'] )
941 ? $this->mFieldData[$key]
942 : $value->getDefault();
943 $html .= $value->$getFieldHtmlMethod( $v );
944
945 $labelValue = trim( $value->getLabel() );
946 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
947 $hasLabel = true;
948 }
949 } elseif ( is_array( $value ) ) {
950 $section = $this->displaySection( $value, $key );
951 $legend = $this->getLegend( $key );
952 if ( isset( $this->mSectionHeaders[$key] ) ) {
953 $section = $this->mSectionHeaders[$key] . $section;
954 }
955 if ( isset( $this->mSectionFooters[$key] ) ) {
956 $section .= $this->mSectionFooters[$key];
957 }
958 $attributes = array();
959 if ( $fieldsetIDPrefix ) {
960 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
961 }
962 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
963 }
964 }
965
966 if ( $displayFormat !== 'raw' ) {
967 $classes = array();
968
969 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
970 $classes[] = 'mw-htmlform-nolabel';
971 }
972
973 $attribs = array(
974 'class' => implode( ' ', $classes ),
975 );
976
977 if ( $sectionName ) {
978 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
979 }
980
981 if ( $displayFormat === 'table' ) {
982 $html = Html::rawElement( 'table', $attribs,
983 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
984 } elseif ( $displayFormat === 'div' ) {
985 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
986 }
987 }
988
989 if ( $this->mSubSectionBeforeFields ) {
990 return $subsectionHtml . "\n" . $html;
991 } else {
992 return $html . "\n" . $subsectionHtml;
993 }
994 }
995
996 /**
997 * Construct the form fields from the Descriptor array
998 */
999 function loadData() {
1000 $fieldData = array();
1001
1002 foreach ( $this->mFlatFields as $fieldname => $field ) {
1003 if ( !empty( $field->mParams['nodata'] ) ) {
1004 continue;
1005 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1006 $fieldData[$fieldname] = $field->getDefault();
1007 } else {
1008 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1009 }
1010 }
1011
1012 # Filter data.
1013 foreach ( $fieldData as $name => &$value ) {
1014 $field = $this->mFlatFields[$name];
1015 $value = $field->filter( $value, $this->mFlatFields );
1016 }
1017
1018 $this->mFieldData = $fieldData;
1019 }
1020
1021 /**
1022 * Stop a reset button being shown for this form
1023 * @param $suppressReset Bool set to false to re-enable the
1024 * button again
1025 * @return HTMLForm $this for chaining calls (since 1.20)
1026 */
1027 function suppressReset( $suppressReset = true ) {
1028 $this->mShowReset = !$suppressReset;
1029 return $this;
1030 }
1031
1032 /**
1033 * Overload this if you want to apply special filtration routines
1034 * to the form as a whole, after it's submitted but before it's
1035 * processed.
1036 * @param $data
1037 * @return
1038 */
1039 function filterDataForSubmit( $data ) {
1040 return $data;
1041 }
1042
1043 /**
1044 * Get a string to go in the "<legend>" of a section fieldset.
1045 * Override this if you want something more complicated.
1046 * @param $key String
1047 * @return String
1048 */
1049 public function getLegend( $key ) {
1050 return wfMsg( "{$this->mMessagePrefix}-$key" );
1051 }
1052
1053 /**
1054 * Set the value for the action attribute of the form.
1055 * When set to false (which is the default state), the set title is used.
1056 *
1057 * @since 1.19
1058 *
1059 * @param string|bool $action
1060 * @return HTMLForm $this for chaining calls (since 1.20)
1061 */
1062 public function setAction( $action ) {
1063 $this->mAction = $action;
1064 return $this;
1065 }
1066
1067 }
1068
1069 /**
1070 * The parent class to generate form fields. Any field type should
1071 * be a subclass of this.
1072 */
1073 abstract class HTMLFormField {
1074
1075 protected $mValidationCallback;
1076 protected $mFilterCallback;
1077 protected $mName;
1078 public $mParams;
1079 protected $mLabel; # String label. Set on construction
1080 protected $mID;
1081 protected $mClass = '';
1082 protected $mDefault;
1083
1084 /**
1085 * @var HTMLForm
1086 */
1087 public $mParent;
1088
1089 /**
1090 * This function must be implemented to return the HTML to generate
1091 * the input object itself. It should not implement the surrounding
1092 * table cells/rows, or labels/help messages.
1093 * @param $value String the value to set the input to; eg a default
1094 * text for a text input.
1095 * @return String valid HTML.
1096 */
1097 abstract function getInputHTML( $value );
1098
1099 /**
1100 * Override this function to add specific validation checks on the
1101 * field input. Don't forget to call parent::validate() to ensure
1102 * that the user-defined callback mValidationCallback is still run
1103 * @param $value String the value the field was submitted with
1104 * @param $alldata Array the data collected from the form
1105 * @return Mixed Bool true on success, or String error to display.
1106 */
1107 function validate( $value, $alldata ) {
1108 if ( isset( $this->mParams['required'] ) && $value === '' ) {
1109 return wfMsgExt( 'htmlform-required', 'parseinline' );
1110 }
1111
1112 if ( isset( $this->mValidationCallback ) ) {
1113 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1114 }
1115
1116 return true;
1117 }
1118
1119 function filter( $value, $alldata ) {
1120 if ( isset( $this->mFilterCallback ) ) {
1121 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1122 }
1123
1124 return $value;
1125 }
1126
1127 /**
1128 * Should this field have a label, or is there no input element with the
1129 * appropriate id for the label to point to?
1130 *
1131 * @return bool True to output a label, false to suppress
1132 */
1133 protected function needsLabel() {
1134 return true;
1135 }
1136
1137 /**
1138 * Get the value that this input has been set to from a posted form,
1139 * or the input's default value if it has not been set.
1140 * @param $request WebRequest
1141 * @return String the value
1142 */
1143 function loadDataFromRequest( $request ) {
1144 if ( $request->getCheck( $this->mName ) ) {
1145 return $request->getText( $this->mName );
1146 } else {
1147 return $this->getDefault();
1148 }
1149 }
1150
1151 /**
1152 * Initialise the object
1153 * @param $params array Associative Array. See HTMLForm doc for syntax.
1154 */
1155 function __construct( $params ) {
1156 $this->mParams = $params;
1157
1158 # Generate the label from a message, if possible
1159 if ( isset( $params['label-message'] ) ) {
1160 $msgInfo = $params['label-message'];
1161
1162 if ( is_array( $msgInfo ) ) {
1163 $msg = array_shift( $msgInfo );
1164 } else {
1165 $msg = $msgInfo;
1166 $msgInfo = array();
1167 }
1168
1169 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
1170 } elseif ( isset( $params['label'] ) ) {
1171 $this->mLabel = $params['label'];
1172 }
1173
1174 $this->mName = "wp{$params['fieldname']}";
1175 if ( isset( $params['name'] ) ) {
1176 $this->mName = $params['name'];
1177 }
1178
1179 $validName = Sanitizer::escapeId( $this->mName );
1180 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1181 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1182 }
1183
1184 $this->mID = "mw-input-{$this->mName}";
1185
1186 if ( isset( $params['default'] ) ) {
1187 $this->mDefault = $params['default'];
1188 }
1189
1190 if ( isset( $params['id'] ) ) {
1191 $id = $params['id'];
1192 $validId = Sanitizer::escapeId( $id );
1193
1194 if ( $id != $validId ) {
1195 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1196 }
1197
1198 $this->mID = $id;
1199 }
1200
1201 if ( isset( $params['cssclass'] ) ) {
1202 $this->mClass = $params['cssclass'];
1203 }
1204
1205 if ( isset( $params['validation-callback'] ) ) {
1206 $this->mValidationCallback = $params['validation-callback'];
1207 }
1208
1209 if ( isset( $params['filter-callback'] ) ) {
1210 $this->mFilterCallback = $params['filter-callback'];
1211 }
1212
1213 if ( isset( $params['flatlist'] ) ) {
1214 $this->mClass .= ' mw-htmlform-flatlist';
1215 }
1216 }
1217
1218 /**
1219 * Get the complete table row for the input, including help text,
1220 * labels, and whatever.
1221 * @param $value String the value to set the input to.
1222 * @return String complete HTML table row.
1223 */
1224 function getTableRow( $value ) {
1225 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1226 $inputHtml = $this->getInputHTML( $value );
1227 $fieldType = get_class( $this );
1228 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1229 $cellAttributes = array();
1230
1231 if ( !empty( $this->mParams['vertical-label'] ) ) {
1232 $cellAttributes['colspan'] = 2;
1233 $verticalLabel = true;
1234 } else {
1235 $verticalLabel = false;
1236 }
1237
1238 $label = $this->getLabelHtml( $cellAttributes );
1239
1240 $field = Html::rawElement(
1241 'td',
1242 array( 'class' => 'mw-input' ) + $cellAttributes,
1243 $inputHtml . "\n$errors"
1244 );
1245
1246 if ( $verticalLabel ) {
1247 $html = Html::rawElement( 'tr',
1248 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1249 $html .= Html::rawElement( 'tr',
1250 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1251 $field );
1252 } else {
1253 $html = Html::rawElement( 'tr',
1254 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1255 $label . $field );
1256 }
1257
1258 return $html . $helptext;
1259 }
1260
1261 /**
1262 * Get the complete div for the input, including help text,
1263 * labels, and whatever.
1264 * @since 1.20
1265 * @param $value String the value to set the input to.
1266 * @return String complete HTML table row.
1267 */
1268 public function getDiv( $value ) {
1269 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1270 $inputHtml = $this->getInputHTML( $value );
1271 $fieldType = get_class( $this );
1272 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1273 $cellAttributes = array();
1274 $label = $this->getLabelHtml( $cellAttributes );
1275
1276 $field = Html::rawElement(
1277 'div',
1278 array( 'class' => 'mw-input' ) + $cellAttributes,
1279 $inputHtml . "\n$errors"
1280 );
1281 $html = Html::rawElement( 'div',
1282 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1283 $label . $field );
1284 $html .= $helptext;
1285 return $html;
1286 }
1287
1288 /**
1289 * Get the complete raw fields for the input, including help text,
1290 * labels, and whatever.
1291 * @since 1.20
1292 * @param $value String the value to set the input to.
1293 * @return String complete HTML table row.
1294 */
1295 public function getRaw( $value ) {
1296 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1297 $inputHtml = $this->getInputHTML( $value );
1298 $fieldType = get_class( $this );
1299 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1300 $cellAttributes = array();
1301 $label = $this->getLabelHtml( $cellAttributes );
1302
1303 $html = "\n$errors";
1304 $html .= $label;
1305 $html .= $inputHtml;
1306 $html .= $helptext;
1307 return $html;
1308 }
1309
1310 /**
1311 * Generate help text HTML in table format
1312 * @since 1.20
1313 * @param $helptext String|null
1314 * @return String
1315 */
1316 public function getHelpTextHtmlTable( $helptext ) {
1317 if ( is_null( $helptext ) ) {
1318 return '';
1319 }
1320
1321 $row = Html::rawElement(
1322 'td',
1323 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1324 $helptext
1325 );
1326 $row = Html::rawElement( 'tr', array(), $row );
1327 return $row;
1328 }
1329
1330 /**
1331 * Generate help text HTML in div format
1332 * @since 1.20
1333 * @param $helptext String|null
1334 * @return String
1335 */
1336 public function getHelpTextHtmlDiv( $helptext ) {
1337 if ( is_null( $helptext ) ) {
1338 return '';
1339 }
1340
1341 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1342 return $div;
1343 }
1344
1345 /**
1346 * Generate help text HTML formatted for raw output
1347 * @since 1.20
1348 * @param $helptext String|null
1349 * @return String
1350 */
1351 public function getHelpTextHtmlRaw( $helptext ) {
1352 return $this->getHelpTextHtmlDiv( $helptext );
1353 }
1354
1355 /**
1356 * Determine the help text to display
1357 * @since 1.20
1358 * @return String
1359 */
1360 public function getHelpText() {
1361 $helptext = null;
1362
1363 if ( isset( $this->mParams['help-message'] ) ) {
1364 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1365 }
1366
1367 if ( isset( $this->mParams['help-messages'] ) ) {
1368 foreach ( $this->mParams['help-messages'] as $name ) {
1369 $helpMessage = (array)$name;
1370 $msg = wfMessage( array_shift( $helpMessage ), $helpMessage );
1371
1372 if ( $msg->exists() ) {
1373 if ( is_null( $helptext ) ) {
1374 $helptext = '';
1375 } else {
1376 $helptext .= wfMessage( 'word-separator' )->escaped(); // some space
1377 }
1378 $helptext .= $msg->parse(); // Append message
1379 }
1380 }
1381 }
1382 elseif ( isset( $this->mParams['help'] ) ) {
1383 $helptext = $this->mParams['help'];
1384 }
1385 return $helptext;
1386 }
1387
1388 /**
1389 * Determine form errors to display and their classes
1390 * @since 1.20
1391 * @param $value String the value of the input
1392 * @return Array
1393 */
1394 public function getErrorsAndErrorClass( $value ) {
1395 $errors = $this->validate( $value, $this->mParent->mFieldData );
1396
1397 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1398 $errors = '';
1399 $errorClass = '';
1400 } else {
1401 $errors = self::formatErrors( $errors );
1402 $errorClass = 'mw-htmlform-invalid-input';
1403 }
1404 return array( $errors, $errorClass );
1405 }
1406
1407 function getLabel() {
1408 return $this->mLabel;
1409 }
1410
1411 function getLabelHtml( $cellAttributes = array() ) {
1412 # Don't output a for= attribute for labels with no associated input.
1413 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1414 $for = array();
1415
1416 if ( $this->needsLabel() ) {
1417 $for['for'] = $this->mID;
1418 }
1419
1420 $displayFormat = $this->mParent->getDisplayFormat();
1421 $labelElement = Html::rawElement( 'label', $for, $this->getLabel() );
1422
1423 if ( $displayFormat == 'table' ) {
1424 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1425 Html::rawElement( 'label', $for, $this->getLabel() )
1426 );
1427 } elseif ( $displayFormat == 'div' ) {
1428 return Html::rawElement( 'div', array( 'class' => 'mw-label' ) + $cellAttributes,
1429 Html::rawElement( 'label', $for, $this->getLabel() )
1430 );
1431 } else {
1432 return $labelElement;
1433 }
1434 }
1435
1436 function getDefault() {
1437 if ( isset( $this->mDefault ) ) {
1438 return $this->mDefault;
1439 } else {
1440 return null;
1441 }
1442 }
1443
1444 /**
1445 * Returns the attributes required for the tooltip and accesskey.
1446 *
1447 * @return array Attributes
1448 */
1449 public function getTooltipAndAccessKey() {
1450 if ( empty( $this->mParams['tooltip'] ) ) {
1451 return array();
1452 }
1453 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1454 }
1455
1456 /**
1457 * flatten an array of options to a single array, for instance,
1458 * a set of "<options>" inside "<optgroups>".
1459 * @param $options array Associative Array with values either Strings
1460 * or Arrays
1461 * @return Array flattened input
1462 */
1463 public static function flattenOptions( $options ) {
1464 $flatOpts = array();
1465
1466 foreach ( $options as $value ) {
1467 if ( is_array( $value ) ) {
1468 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1469 } else {
1470 $flatOpts[] = $value;
1471 }
1472 }
1473
1474 return $flatOpts;
1475 }
1476
1477 /**
1478 * Formats one or more errors as accepted by field validation-callback.
1479 * @param $errors String|Message|Array of strings or Message instances
1480 * @return String html
1481 * @since 1.18
1482 */
1483 protected static function formatErrors( $errors ) {
1484 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1485 $errors = array_shift( $errors );
1486 }
1487
1488 if ( is_array( $errors ) ) {
1489 $lines = array();
1490 foreach ( $errors as $error ) {
1491 if ( $error instanceof Message ) {
1492 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1493 } else {
1494 $lines[] = Html::rawElement( 'li', array(), $error );
1495 }
1496 }
1497 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1498 } else {
1499 if ( $errors instanceof Message ) {
1500 $errors = $errors->parse();
1501 }
1502 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1503 }
1504 }
1505 }
1506
1507 class HTMLTextField extends HTMLFormField {
1508 function getSize() {
1509 return isset( $this->mParams['size'] )
1510 ? $this->mParams['size']
1511 : 45;
1512 }
1513
1514 function getInputHTML( $value ) {
1515 $attribs = array(
1516 'id' => $this->mID,
1517 'name' => $this->mName,
1518 'size' => $this->getSize(),
1519 'value' => $value,
1520 ) + $this->getTooltipAndAccessKey();
1521
1522 if ( $this->mClass !== '' ) {
1523 $attribs['class'] = $this->mClass;
1524 }
1525
1526 if ( isset( $this->mParams['maxlength'] ) ) {
1527 $attribs['maxlength'] = $this->mParams['maxlength'];
1528 }
1529
1530 if ( !empty( $this->mParams['disabled'] ) ) {
1531 $attribs['disabled'] = 'disabled';
1532 }
1533
1534 # TODO: Enforce pattern, step, required, readonly on the server side as
1535 # well
1536 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1537 'placeholder' ) as $param ) {
1538 if ( isset( $this->mParams[$param] ) ) {
1539 $attribs[$param] = $this->mParams[$param];
1540 }
1541 }
1542
1543 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1544 if ( isset( $this->mParams[$param] ) ) {
1545 $attribs[$param] = '';
1546 }
1547 }
1548
1549 # Implement tiny differences between some field variants
1550 # here, rather than creating a new class for each one which
1551 # is essentially just a clone of this one.
1552 if ( isset( $this->mParams['type'] ) ) {
1553 switch ( $this->mParams['type'] ) {
1554 case 'email':
1555 $attribs['type'] = 'email';
1556 break;
1557 case 'int':
1558 $attribs['type'] = 'number';
1559 break;
1560 case 'float':
1561 $attribs['type'] = 'number';
1562 $attribs['step'] = 'any';
1563 break;
1564 # Pass through
1565 case 'password':
1566 case 'file':
1567 $attribs['type'] = $this->mParams['type'];
1568 break;
1569 }
1570 }
1571
1572 return Html::element( 'input', $attribs );
1573 }
1574 }
1575 class HTMLTextAreaField extends HTMLFormField {
1576 function getCols() {
1577 return isset( $this->mParams['cols'] )
1578 ? $this->mParams['cols']
1579 : 80;
1580 }
1581
1582 function getRows() {
1583 return isset( $this->mParams['rows'] )
1584 ? $this->mParams['rows']
1585 : 25;
1586 }
1587
1588 function getInputHTML( $value ) {
1589 $attribs = array(
1590 'id' => $this->mID,
1591 'name' => $this->mName,
1592 'cols' => $this->getCols(),
1593 'rows' => $this->getRows(),
1594 ) + $this->getTooltipAndAccessKey();
1595
1596 if ( $this->mClass !== '' ) {
1597 $attribs['class'] = $this->mClass;
1598 }
1599
1600 if ( !empty( $this->mParams['disabled'] ) ) {
1601 $attribs['disabled'] = 'disabled';
1602 }
1603
1604 if ( !empty( $this->mParams['readonly'] ) ) {
1605 $attribs['readonly'] = 'readonly';
1606 }
1607
1608 if ( isset( $this->mParams['placeholder'] ) ) {
1609 $attribs['placeholder'] = $this->mParams['placeholder'];
1610 }
1611
1612 foreach ( array( 'required', 'autofocus' ) as $param ) {
1613 if ( isset( $this->mParams[$param] ) ) {
1614 $attribs[$param] = '';
1615 }
1616 }
1617
1618 return Html::element( 'textarea', $attribs, $value );
1619 }
1620 }
1621
1622 /**
1623 * A field that will contain a numeric value
1624 */
1625 class HTMLFloatField extends HTMLTextField {
1626 function getSize() {
1627 return isset( $this->mParams['size'] )
1628 ? $this->mParams['size']
1629 : 20;
1630 }
1631
1632 function validate( $value, $alldata ) {
1633 $p = parent::validate( $value, $alldata );
1634
1635 if ( $p !== true ) {
1636 return $p;
1637 }
1638
1639 $value = trim( $value );
1640
1641 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1642 # with the addition that a leading '+' sign is ok.
1643 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1644 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1645 }
1646
1647 # The "int" part of these message names is rather confusing.
1648 # They make equal sense for all numbers.
1649 if ( isset( $this->mParams['min'] ) ) {
1650 $min = $this->mParams['min'];
1651
1652 if ( $min > $value ) {
1653 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1654 }
1655 }
1656
1657 if ( isset( $this->mParams['max'] ) ) {
1658 $max = $this->mParams['max'];
1659
1660 if ( $max < $value ) {
1661 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1662 }
1663 }
1664
1665 return true;
1666 }
1667 }
1668
1669 /**
1670 * A field that must contain a number
1671 */
1672 class HTMLIntField extends HTMLFloatField {
1673 function validate( $value, $alldata ) {
1674 $p = parent::validate( $value, $alldata );
1675
1676 if ( $p !== true ) {
1677 return $p;
1678 }
1679
1680 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1681 # with the addition that a leading '+' sign is ok. Note that leading zeros
1682 # are fine, and will be left in the input, which is useful for things like
1683 # phone numbers when you know that they are integers (the HTML5 type=tel
1684 # input does not require its value to be numeric). If you want a tidier
1685 # value to, eg, save in the DB, clean it up with intval().
1686 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1687 ) {
1688 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1689 }
1690
1691 return true;
1692 }
1693 }
1694
1695 /**
1696 * A checkbox field
1697 */
1698 class HTMLCheckField extends HTMLFormField {
1699 function getInputHTML( $value ) {
1700 if ( !empty( $this->mParams['invert'] ) ) {
1701 $value = !$value;
1702 }
1703
1704 $attr = $this->getTooltipAndAccessKey();
1705 $attr['id'] = $this->mID;
1706
1707 if ( !empty( $this->mParams['disabled'] ) ) {
1708 $attr['disabled'] = 'disabled';
1709 }
1710
1711 if ( $this->mClass !== '' ) {
1712 $attr['class'] = $this->mClass;
1713 }
1714
1715 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1716 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1717 }
1718
1719 /**
1720 * For a checkbox, the label goes on the right hand side, and is
1721 * added in getInputHTML(), rather than HTMLFormField::getRow()
1722 * @return String
1723 */
1724 function getLabel() {
1725 return '&#160;';
1726 }
1727
1728 /**
1729 * @param $request WebRequest
1730 * @return String
1731 */
1732 function loadDataFromRequest( $request ) {
1733 $invert = false;
1734 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1735 $invert = true;
1736 }
1737
1738 // GetCheck won't work like we want for checks.
1739 // Fetch the value in either one of the two following case:
1740 // - we have a valid token (form got posted or GET forged by the user)
1741 // - checkbox name has a value (false or true), ie is not null
1742 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1743 // XOR has the following truth table, which is what we want
1744 // INVERT VALUE | OUTPUT
1745 // true true | false
1746 // false true | true
1747 // false false | false
1748 // true false | true
1749 return $request->getBool( $this->mName ) xor $invert;
1750 } else {
1751 return $this->getDefault();
1752 }
1753 }
1754 }
1755
1756 /**
1757 * A select dropdown field. Basically a wrapper for Xmlselect class
1758 */
1759 class HTMLSelectField extends HTMLFormField {
1760 function validate( $value, $alldata ) {
1761 $p = parent::validate( $value, $alldata );
1762
1763 if ( $p !== true ) {
1764 return $p;
1765 }
1766
1767 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1768
1769 if ( in_array( $value, $validOptions ) )
1770 return true;
1771 else
1772 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1773 }
1774
1775 function getInputHTML( $value ) {
1776 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1777
1778 # If one of the options' 'name' is int(0), it is automatically selected.
1779 # because PHP sucks and thinks int(0) == 'some string'.
1780 # Working around this by forcing all of them to strings.
1781 foreach ( $this->mParams['options'] as &$opt ) {
1782 if ( is_int( $opt ) ) {
1783 $opt = strval( $opt );
1784 }
1785 }
1786 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1787
1788 if ( !empty( $this->mParams['disabled'] ) ) {
1789 $select->setAttribute( 'disabled', 'disabled' );
1790 }
1791
1792 if ( $this->mClass !== '' ) {
1793 $select->setAttribute( 'class', $this->mClass );
1794 }
1795
1796 $select->addOptions( $this->mParams['options'] );
1797
1798 return $select->getHTML();
1799 }
1800 }
1801
1802 /**
1803 * Select dropdown field, with an additional "other" textbox.
1804 */
1805 class HTMLSelectOrOtherField extends HTMLTextField {
1806 static $jsAdded = false;
1807
1808 function __construct( $params ) {
1809 if ( !in_array( 'other', $params['options'], true ) ) {
1810 $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
1811 $params['options'][$msg] = 'other';
1812 }
1813
1814 parent::__construct( $params );
1815 }
1816
1817 static function forceToStringRecursive( $array ) {
1818 if ( is_array( $array ) ) {
1819 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1820 } else {
1821 return strval( $array );
1822 }
1823 }
1824
1825 function getInputHTML( $value ) {
1826 $valInSelect = false;
1827
1828 if ( $value !== false ) {
1829 $valInSelect = in_array(
1830 $value,
1831 HTMLFormField::flattenOptions( $this->mParams['options'] )
1832 );
1833 }
1834
1835 $selected = $valInSelect ? $value : 'other';
1836
1837 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1838
1839 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1840 $select->addOptions( $opts );
1841
1842 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1843
1844 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1845
1846 if ( !empty( $this->mParams['disabled'] ) ) {
1847 $select->setAttribute( 'disabled', 'disabled' );
1848 $tbAttribs['disabled'] = 'disabled';
1849 }
1850
1851 $select = $select->getHTML();
1852
1853 if ( isset( $this->mParams['maxlength'] ) ) {
1854 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1855 }
1856
1857 if ( $this->mClass !== '' ) {
1858 $tbAttribs['class'] = $this->mClass;
1859 }
1860
1861 $textbox = Html::input(
1862 $this->mName . '-other',
1863 $valInSelect ? '' : $value,
1864 'text',
1865 $tbAttribs
1866 );
1867
1868 return "$select<br />\n$textbox";
1869 }
1870
1871 /**
1872 * @param $request WebRequest
1873 * @return String
1874 */
1875 function loadDataFromRequest( $request ) {
1876 if ( $request->getCheck( $this->mName ) ) {
1877 $val = $request->getText( $this->mName );
1878
1879 if ( $val == 'other' ) {
1880 $val = $request->getText( $this->mName . '-other' );
1881 }
1882
1883 return $val;
1884 } else {
1885 return $this->getDefault();
1886 }
1887 }
1888 }
1889
1890 /**
1891 * Multi-select field
1892 */
1893 class HTMLMultiSelectField extends HTMLFormField {
1894
1895 function validate( $value, $alldata ) {
1896 $p = parent::validate( $value, $alldata );
1897
1898 if ( $p !== true ) {
1899 return $p;
1900 }
1901
1902 if ( !is_array( $value ) ) {
1903 return false;
1904 }
1905
1906 # If all options are valid, array_intersect of the valid options
1907 # and the provided options will return the provided options.
1908 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1909
1910 $validValues = array_intersect( $value, $validOptions );
1911 if ( count( $validValues ) == count( $value ) ) {
1912 return true;
1913 } else {
1914 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1915 }
1916 }
1917
1918 function getInputHTML( $value ) {
1919 $html = $this->formatOptions( $this->mParams['options'], $value );
1920
1921 return $html;
1922 }
1923
1924 function formatOptions( $options, $value ) {
1925 $html = '';
1926
1927 $attribs = array();
1928
1929 if ( !empty( $this->mParams['disabled'] ) ) {
1930 $attribs['disabled'] = 'disabled';
1931 }
1932
1933 foreach ( $options as $label => $info ) {
1934 if ( is_array( $info ) ) {
1935 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1936 $html .= $this->formatOptions( $info, $value );
1937 } else {
1938 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1939
1940 $checkbox = Xml::check(
1941 $this->mName . '[]',
1942 in_array( $info, $value, true ),
1943 $attribs + $thisAttribs );
1944 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1945
1946 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1947 }
1948 }
1949
1950 return $html;
1951 }
1952
1953 /**
1954 * @param $request WebRequest
1955 * @return String
1956 */
1957 function loadDataFromRequest( $request ) {
1958 if ( $this->mParent->getMethod() == 'post' ) {
1959 if ( $request->wasPosted() ) {
1960 # Checkboxes are just not added to the request arrays if they're not checked,
1961 # so it's perfectly possible for there not to be an entry at all
1962 return $request->getArray( $this->mName, array() );
1963 } else {
1964 # That's ok, the user has not yet submitted the form, so show the defaults
1965 return $this->getDefault();
1966 }
1967 } else {
1968 # This is the impossible case: if we look at $_GET and see no data for our
1969 # field, is it because the user has not yet submitted the form, or that they
1970 # have submitted it with all the options unchecked? We will have to assume the
1971 # latter, which basically means that you can't specify 'positive' defaults
1972 # for GET forms.
1973 # @todo FIXME...
1974 return $request->getArray( $this->mName, array() );
1975 }
1976 }
1977
1978 function getDefault() {
1979 if ( isset( $this->mDefault ) ) {
1980 return $this->mDefault;
1981 } else {
1982 return array();
1983 }
1984 }
1985
1986 protected function needsLabel() {
1987 return false;
1988 }
1989 }
1990
1991 /**
1992 * Double field with a dropdown list constructed from a system message in the format
1993 * * Optgroup header
1994 * ** <option value>
1995 * * New Optgroup header
1996 * Plus a text field underneath for an additional reason. The 'value' of the field is
1997 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
1998 * select dropdown.
1999 * @todo FIXME: If made 'required', only the text field should be compulsory.
2000 */
2001 class HTMLSelectAndOtherField extends HTMLSelectField {
2002
2003 function __construct( $params ) {
2004 if ( array_key_exists( 'other', $params ) ) {
2005 } elseif ( array_key_exists( 'other-message', $params ) ) {
2006 $params['other'] = wfMessage( $params['other-message'] )->plain();
2007 } else {
2008 $params['other'] = null;
2009 }
2010
2011 if ( array_key_exists( 'options', $params ) ) {
2012 # Options array already specified
2013 } elseif ( array_key_exists( 'options-message', $params ) ) {
2014 # Generate options array from a system message
2015 $params['options'] = self::parseMessage(
2016 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2017 $params['other']
2018 );
2019 } else {
2020 # Sulk
2021 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2022 }
2023 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2024
2025 parent::__construct( $params );
2026 }
2027
2028 /**
2029 * Build a drop-down box from a textual list.
2030 * @param $string String message text
2031 * @param $otherName String name of "other reason" option
2032 * @return Array
2033 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2034 */
2035 public static function parseMessage( $string, $otherName = null ) {
2036 if ( $otherName === null ) {
2037 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2038 }
2039
2040 $optgroup = false;
2041 $options = array( $otherName => 'other' );
2042
2043 foreach ( explode( "\n", $string ) as $option ) {
2044 $value = trim( $option );
2045 if ( $value == '' ) {
2046 continue;
2047 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2048 # A new group is starting...
2049 $value = trim( substr( $value, 1 ) );
2050 $optgroup = $value;
2051 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2052 # groupmember
2053 $opt = trim( substr( $value, 2 ) );
2054 if ( $optgroup === false ) {
2055 $options[$opt] = $opt;
2056 } else {
2057 $options[$optgroup][$opt] = $opt;
2058 }
2059 } else {
2060 # groupless reason list
2061 $optgroup = false;
2062 $options[$option] = $option;
2063 }
2064 }
2065
2066 return $options;
2067 }
2068
2069 function getInputHTML( $value ) {
2070 $select = parent::getInputHTML( $value[1] );
2071
2072 $textAttribs = array(
2073 'id' => $this->mID . '-other',
2074 'size' => $this->getSize(),
2075 );
2076
2077 if ( $this->mClass !== '' ) {
2078 $textAttribs['class'] = $this->mClass;
2079 }
2080
2081 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2082 if ( isset( $this->mParams[$param] ) ) {
2083 $textAttribs[$param] = '';
2084 }
2085 }
2086
2087 $textbox = Html::input(
2088 $this->mName . '-other',
2089 $value[2],
2090 'text',
2091 $textAttribs
2092 );
2093
2094 return "$select<br />\n$textbox";
2095 }
2096
2097 /**
2098 * @param $request WebRequest
2099 * @return Array("<overall message>","<select value>","<text field value>")
2100 */
2101 function loadDataFromRequest( $request ) {
2102 if ( $request->getCheck( $this->mName ) ) {
2103
2104 $list = $request->getText( $this->mName );
2105 $text = $request->getText( $this->mName . '-other' );
2106
2107 if ( $list == 'other' ) {
2108 $final = $text;
2109 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2110 # User has spoofed the select form to give an option which wasn't
2111 # in the original offer. Sulk...
2112 $final = $text;
2113 } elseif ( $text == '' ) {
2114 $final = $list;
2115 } else {
2116 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
2117 }
2118
2119 } else {
2120 $final = $this->getDefault();
2121
2122 $list = 'other';
2123 $text = $final;
2124 foreach ( $this->mFlatOptions as $option ) {
2125 $match = $option . wfMsgForContent( 'colon-separator' );
2126 if ( strpos( $text, $match ) === 0 ) {
2127 $list = $option;
2128 $text = substr( $text, strlen( $match ) );
2129 break;
2130 }
2131 }
2132 }
2133 return array( $final, $list, $text );
2134 }
2135
2136 function getSize() {
2137 return isset( $this->mParams['size'] )
2138 ? $this->mParams['size']
2139 : 45;
2140 }
2141
2142 function validate( $value, $alldata ) {
2143 # HTMLSelectField forces $value to be one of the options in the select
2144 # field, which is not useful here. But we do want the validation further up
2145 # the chain
2146 $p = parent::validate( $value[1], $alldata );
2147
2148 if ( $p !== true ) {
2149 return $p;
2150 }
2151
2152 if ( isset( $this->mParams['required'] ) && $value[1] === '' ) {
2153 return wfMsgExt( 'htmlform-required', 'parseinline' );
2154 }
2155
2156 return true;
2157 }
2158 }
2159
2160 /**
2161 * Radio checkbox fields.
2162 */
2163 class HTMLRadioField extends HTMLFormField {
2164
2165
2166 function validate( $value, $alldata ) {
2167 $p = parent::validate( $value, $alldata );
2168
2169 if ( $p !== true ) {
2170 return $p;
2171 }
2172
2173 if ( !is_string( $value ) && !is_int( $value ) ) {
2174 return false;
2175 }
2176
2177 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2178
2179 if ( in_array( $value, $validOptions ) ) {
2180 return true;
2181 } else {
2182 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
2183 }
2184 }
2185
2186 /**
2187 * This returns a block of all the radio options, in one cell.
2188 * @see includes/HTMLFormField#getInputHTML()
2189 * @param $value String
2190 * @return String
2191 */
2192 function getInputHTML( $value ) {
2193 $html = $this->formatOptions( $this->mParams['options'], $value );
2194
2195 return $html;
2196 }
2197
2198 function formatOptions( $options, $value ) {
2199 $html = '';
2200
2201 $attribs = array();
2202 if ( !empty( $this->mParams['disabled'] ) ) {
2203 $attribs['disabled'] = 'disabled';
2204 }
2205
2206 # TODO: should this produce an unordered list perhaps?
2207 foreach ( $options as $label => $info ) {
2208 if ( is_array( $info ) ) {
2209 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2210 $html .= $this->formatOptions( $info, $value );
2211 } else {
2212 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2213 $radio = Xml::radio(
2214 $this->mName,
2215 $info,
2216 $info == $value,
2217 $attribs + array( 'id' => $id )
2218 );
2219 $radio .= '&#160;' .
2220 Html::rawElement( 'label', array( 'for' => $id ), $label );
2221
2222 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2223 }
2224 }
2225
2226 return $html;
2227 }
2228
2229 protected function needsLabel() {
2230 return false;
2231 }
2232 }
2233
2234 /**
2235 * An information field (text blob), not a proper input.
2236 */
2237 class HTMLInfoField extends HTMLFormField {
2238 public function __construct( $info ) {
2239 $info['nodata'] = true;
2240
2241 parent::__construct( $info );
2242 }
2243
2244 public function getInputHTML( $value ) {
2245 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2246 }
2247
2248 public function getTableRow( $value ) {
2249 if ( !empty( $this->mParams['rawrow'] ) ) {
2250 return $value;
2251 }
2252
2253 return parent::getTableRow( $value );
2254 }
2255
2256 /**
2257 * @since 1.20
2258 */
2259 public function getDiv( $value ) {
2260 if ( !empty( $this->mParams['rawrow'] ) ) {
2261 return $value;
2262 }
2263
2264 return parent::getDiv( $value );
2265 }
2266
2267 /**
2268 * @since 1.20
2269 */
2270 public function getRaw( $value ) {
2271 if ( !empty( $this->mParams['rawrow'] ) ) {
2272 return $value;
2273 }
2274
2275 return parent::getRaw( $value );
2276 }
2277
2278 protected function needsLabel() {
2279 return false;
2280 }
2281 }
2282
2283 class HTMLHiddenField extends HTMLFormField {
2284 public function __construct( $params ) {
2285 parent::__construct( $params );
2286
2287 # Per HTML5 spec, hidden fields cannot be 'required'
2288 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2289 unset( $this->mParams['required'] );
2290 }
2291
2292 public function getTableRow( $value ) {
2293 $params = array();
2294 if ( $this->mID ) {
2295 $params['id'] = $this->mID;
2296 }
2297
2298 $this->mParent->addHiddenField(
2299 $this->mName,
2300 $this->mDefault,
2301 $params
2302 );
2303
2304 return '';
2305 }
2306
2307 /**
2308 * @since 1.20
2309 */
2310 public function getDiv( $value ) {
2311 return $this->getTableRow( $value );
2312 }
2313
2314 /**
2315 * @since 1.20
2316 */
2317 public function getRaw( $value ) {
2318 return $this->getTableRow( $value );
2319 }
2320
2321 public function getInputHTML( $value ) { return ''; }
2322 }
2323
2324 /**
2325 * Add a submit button inline in the form (as opposed to
2326 * HTMLForm::addButton(), which will add it at the end).
2327 */
2328 class HTMLSubmitField extends HTMLFormField {
2329
2330 public function __construct( $info ) {
2331 $info['nodata'] = true;
2332 parent::__construct( $info );
2333 }
2334
2335 public function getInputHTML( $value ) {
2336 return Xml::submitButton(
2337 $value,
2338 array(
2339 'class' => 'mw-htmlform-submit ' . $this->mClass,
2340 'name' => $this->mName,
2341 'id' => $this->mID,
2342 )
2343 );
2344 }
2345
2346 protected function needsLabel() {
2347 return false;
2348 }
2349
2350 /**
2351 * Button cannot be invalid
2352 * @param $value String
2353 * @param $alldata Array
2354 * @return Bool
2355 */
2356 public function validate( $value, $alldata ) {
2357 return true;
2358 }
2359 }
2360
2361 class HTMLEditTools extends HTMLFormField {
2362 public function getInputHTML( $value ) {
2363 return '';
2364 }
2365
2366 public function getTableRow( $value ) {
2367 $msg = $this->formatMsg();
2368
2369 return '<tr><td></td><td class="mw-input">'
2370 . '<div class="mw-editTools">'
2371 . $msg->parseAsBlock()
2372 . "</div></td></tr>\n";
2373 }
2374
2375 /**
2376 * @since 1.20
2377 */
2378 public function getDiv( $value ) {
2379 $msg = $this->formatMsg();
2380 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2381 }
2382
2383 /**
2384 * @since 1.20
2385 */
2386 public function getRaw( $value ) {
2387 return $this->getDiv( $value );
2388 }
2389
2390 protected function formatMsg() {
2391 if ( empty( $this->mParams['message'] ) ) {
2392 $msg = wfMessage( 'edittools' );
2393 } else {
2394 $msg = wfMessage( $this->mParams['message'] );
2395 if ( $msg->isDisabled() ) {
2396 $msg = wfMessage( 'edittools' );
2397 }
2398 }
2399 $msg->inContentLanguage();
2400 return $msg;
2401 }
2402 }