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