Merge "CologneBlue rewrite: kill mWatchLinkNum, watchThisPage() is only called once...
[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 * Get a translated interface message
1105 *
1106 * This is a wrapper arround $this->mParent->msg() if $this->mParent is set
1107 * and wfMessage() otherwise.
1108 *
1109 * Parameters are the same as wfMessage().
1110 *
1111 * @return Message object
1112 */
1113 function msg() {
1114 $args = func_get_args();
1115
1116 if ( $this->mParent ) {
1117 $callback = array( $this->mParent, 'msg' );
1118 } else {
1119 $callback = 'wfMessage';
1120 }
1121
1122 return call_user_func_array( $callback, $args );
1123 }
1124
1125 /**
1126 * Override this function to add specific validation checks on the
1127 * field input. Don't forget to call parent::validate() to ensure
1128 * that the user-defined callback mValidationCallback is still run
1129 * @param $value String the value the field was submitted with
1130 * @param $alldata Array the data collected from the form
1131 * @return Mixed Bool true on success, or String error to display.
1132 */
1133 function validate( $value, $alldata ) {
1134 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1135 return $this->msg( 'htmlform-required' )->parse();
1136 }
1137
1138 if ( isset( $this->mValidationCallback ) ) {
1139 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1140 }
1141
1142 return true;
1143 }
1144
1145 function filter( $value, $alldata ) {
1146 if ( isset( $this->mFilterCallback ) ) {
1147 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1148 }
1149
1150 return $value;
1151 }
1152
1153 /**
1154 * Should this field have a label, or is there no input element with the
1155 * appropriate id for the label to point to?
1156 *
1157 * @return bool True to output a label, false to suppress
1158 */
1159 protected function needsLabel() {
1160 return true;
1161 }
1162
1163 /**
1164 * Get the value that this input has been set to from a posted form,
1165 * or the input's default value if it has not been set.
1166 * @param $request WebRequest
1167 * @return String the value
1168 */
1169 function loadDataFromRequest( $request ) {
1170 if ( $request->getCheck( $this->mName ) ) {
1171 return $request->getText( $this->mName );
1172 } else {
1173 return $this->getDefault();
1174 }
1175 }
1176
1177 /**
1178 * Initialise the object
1179 * @param $params array Associative Array. See HTMLForm doc for syntax.
1180 */
1181 function __construct( $params ) {
1182 $this->mParams = $params;
1183
1184 # Generate the label from a message, if possible
1185 if ( isset( $params['label-message'] ) ) {
1186 $msgInfo = $params['label-message'];
1187
1188 if ( is_array( $msgInfo ) ) {
1189 $msg = array_shift( $msgInfo );
1190 } else {
1191 $msg = $msgInfo;
1192 $msgInfo = array();
1193 }
1194
1195 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1196 } elseif ( isset( $params['label'] ) ) {
1197 $this->mLabel = $params['label'];
1198 }
1199
1200 $this->mName = "wp{$params['fieldname']}";
1201 if ( isset( $params['name'] ) ) {
1202 $this->mName = $params['name'];
1203 }
1204
1205 $validName = Sanitizer::escapeId( $this->mName );
1206 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1207 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1208 }
1209
1210 $this->mID = "mw-input-{$this->mName}";
1211
1212 if ( isset( $params['default'] ) ) {
1213 $this->mDefault = $params['default'];
1214 }
1215
1216 if ( isset( $params['id'] ) ) {
1217 $id = $params['id'];
1218 $validId = Sanitizer::escapeId( $id );
1219
1220 if ( $id != $validId ) {
1221 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1222 }
1223
1224 $this->mID = $id;
1225 }
1226
1227 if ( isset( $params['cssclass'] ) ) {
1228 $this->mClass = $params['cssclass'];
1229 }
1230
1231 if ( isset( $params['validation-callback'] ) ) {
1232 $this->mValidationCallback = $params['validation-callback'];
1233 }
1234
1235 if ( isset( $params['filter-callback'] ) ) {
1236 $this->mFilterCallback = $params['filter-callback'];
1237 }
1238
1239 if ( isset( $params['flatlist'] ) ) {
1240 $this->mClass .= ' mw-htmlform-flatlist';
1241 }
1242 }
1243
1244 /**
1245 * Get the complete table row for the input, including help text,
1246 * labels, and whatever.
1247 * @param $value String the value to set the input to.
1248 * @return String complete HTML table row.
1249 */
1250 function getTableRow( $value ) {
1251 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1252 $inputHtml = $this->getInputHTML( $value );
1253 $fieldType = get_class( $this );
1254 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1255 $cellAttributes = array();
1256
1257 if ( !empty( $this->mParams['vertical-label'] ) ) {
1258 $cellAttributes['colspan'] = 2;
1259 $verticalLabel = true;
1260 } else {
1261 $verticalLabel = false;
1262 }
1263
1264 $label = $this->getLabelHtml( $cellAttributes );
1265
1266 $field = Html::rawElement(
1267 'td',
1268 array( 'class' => 'mw-input' ) + $cellAttributes,
1269 $inputHtml . "\n$errors"
1270 );
1271
1272 if ( $verticalLabel ) {
1273 $html = Html::rawElement( 'tr',
1274 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1275 $html .= Html::rawElement( 'tr',
1276 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1277 $field );
1278 } else {
1279 $html = Html::rawElement( 'tr',
1280 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1281 $label . $field );
1282 }
1283
1284 return $html . $helptext;
1285 }
1286
1287 /**
1288 * Get the complete div for the input, including help text,
1289 * labels, and whatever.
1290 * @since 1.20
1291 * @param $value String the value to set the input to.
1292 * @return String complete HTML table row.
1293 */
1294 public function getDiv( $value ) {
1295 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1296 $inputHtml = $this->getInputHTML( $value );
1297 $fieldType = get_class( $this );
1298 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1299 $cellAttributes = array();
1300 $label = $this->getLabelHtml( $cellAttributes );
1301
1302 $field = Html::rawElement(
1303 'div',
1304 array( 'class' => 'mw-input' ) + $cellAttributes,
1305 $inputHtml . "\n$errors"
1306 );
1307 $html = Html::rawElement( 'div',
1308 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1309 $label . $field );
1310 $html .= $helptext;
1311 return $html;
1312 }
1313
1314 /**
1315 * Get the complete raw fields for the input, including help text,
1316 * labels, and whatever.
1317 * @since 1.20
1318 * @param $value String the value to set the input to.
1319 * @return String complete HTML table row.
1320 */
1321 public function getRaw( $value ) {
1322 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1323 $inputHtml = $this->getInputHTML( $value );
1324 $fieldType = get_class( $this );
1325 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1326 $cellAttributes = array();
1327 $label = $this->getLabelHtml( $cellAttributes );
1328
1329 $html = "\n$errors";
1330 $html .= $label;
1331 $html .= $inputHtml;
1332 $html .= $helptext;
1333 return $html;
1334 }
1335
1336 /**
1337 * Generate help text HTML in table format
1338 * @since 1.20
1339 * @param $helptext String|null
1340 * @return String
1341 */
1342 public function getHelpTextHtmlTable( $helptext ) {
1343 if ( is_null( $helptext ) ) {
1344 return '';
1345 }
1346
1347 $row = Html::rawElement(
1348 'td',
1349 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1350 $helptext
1351 );
1352 $row = Html::rawElement( 'tr', array(), $row );
1353 return $row;
1354 }
1355
1356 /**
1357 * Generate help text HTML in div format
1358 * @since 1.20
1359 * @param $helptext String|null
1360 * @return String
1361 */
1362 public function getHelpTextHtmlDiv( $helptext ) {
1363 if ( is_null( $helptext ) ) {
1364 return '';
1365 }
1366
1367 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1368 return $div;
1369 }
1370
1371 /**
1372 * Generate help text HTML formatted for raw output
1373 * @since 1.20
1374 * @param $helptext String|null
1375 * @return String
1376 */
1377 public function getHelpTextHtmlRaw( $helptext ) {
1378 return $this->getHelpTextHtmlDiv( $helptext );
1379 }
1380
1381 /**
1382 * Determine the help text to display
1383 * @since 1.20
1384 * @return String
1385 */
1386 public function getHelpText() {
1387 $helptext = null;
1388
1389 if ( isset( $this->mParams['help-message'] ) ) {
1390 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1391 }
1392
1393 if ( isset( $this->mParams['help-messages'] ) ) {
1394 foreach ( $this->mParams['help-messages'] as $name ) {
1395 $helpMessage = (array)$name;
1396 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1397
1398 if ( $msg->exists() ) {
1399 if ( is_null( $helptext ) ) {
1400 $helptext = '';
1401 } else {
1402 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1403 }
1404 $helptext .= $msg->parse(); // Append message
1405 }
1406 }
1407 }
1408 elseif ( isset( $this->mParams['help'] ) ) {
1409 $helptext = $this->mParams['help'];
1410 }
1411 return $helptext;
1412 }
1413
1414 /**
1415 * Determine form errors to display and their classes
1416 * @since 1.20
1417 * @param $value String the value of the input
1418 * @return Array
1419 */
1420 public function getErrorsAndErrorClass( $value ) {
1421 $errors = $this->validate( $value, $this->mParent->mFieldData );
1422
1423 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1424 $errors = '';
1425 $errorClass = '';
1426 } else {
1427 $errors = self::formatErrors( $errors );
1428 $errorClass = 'mw-htmlform-invalid-input';
1429 }
1430 return array( $errors, $errorClass );
1431 }
1432
1433 function getLabel() {
1434 return $this->mLabel;
1435 }
1436
1437 function getLabelHtml( $cellAttributes = array() ) {
1438 # Don't output a for= attribute for labels with no associated input.
1439 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1440 $for = array();
1441
1442 if ( $this->needsLabel() ) {
1443 $for['for'] = $this->mID;
1444 }
1445
1446 $displayFormat = $this->mParent->getDisplayFormat();
1447 $labelElement = Html::rawElement( 'label', $for, $this->getLabel() );
1448
1449 if ( $displayFormat == 'table' ) {
1450 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1451 Html::rawElement( 'label', $for, $this->getLabel() )
1452 );
1453 } elseif ( $displayFormat == 'div' ) {
1454 return Html::rawElement( 'div', array( 'class' => 'mw-label' ) + $cellAttributes,
1455 Html::rawElement( 'label', $for, $this->getLabel() )
1456 );
1457 } else {
1458 return $labelElement;
1459 }
1460 }
1461
1462 function getDefault() {
1463 if ( isset( $this->mDefault ) ) {
1464 return $this->mDefault;
1465 } else {
1466 return null;
1467 }
1468 }
1469
1470 /**
1471 * Returns the attributes required for the tooltip and accesskey.
1472 *
1473 * @return array Attributes
1474 */
1475 public function getTooltipAndAccessKey() {
1476 if ( empty( $this->mParams['tooltip'] ) ) {
1477 return array();
1478 }
1479 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1480 }
1481
1482 /**
1483 * flatten an array of options to a single array, for instance,
1484 * a set of "<options>" inside "<optgroups>".
1485 * @param $options array Associative Array with values either Strings
1486 * or Arrays
1487 * @return Array flattened input
1488 */
1489 public static function flattenOptions( $options ) {
1490 $flatOpts = array();
1491
1492 foreach ( $options as $value ) {
1493 if ( is_array( $value ) ) {
1494 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1495 } else {
1496 $flatOpts[] = $value;
1497 }
1498 }
1499
1500 return $flatOpts;
1501 }
1502
1503 /**
1504 * Formats one or more errors as accepted by field validation-callback.
1505 * @param $errors String|Message|Array of strings or Message instances
1506 * @return String html
1507 * @since 1.18
1508 */
1509 protected static function formatErrors( $errors ) {
1510 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1511 $errors = array_shift( $errors );
1512 }
1513
1514 if ( is_array( $errors ) ) {
1515 $lines = array();
1516 foreach ( $errors as $error ) {
1517 if ( $error instanceof Message ) {
1518 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1519 } else {
1520 $lines[] = Html::rawElement( 'li', array(), $error );
1521 }
1522 }
1523 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1524 } else {
1525 if ( $errors instanceof Message ) {
1526 $errors = $errors->parse();
1527 }
1528 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1529 }
1530 }
1531 }
1532
1533 class HTMLTextField extends HTMLFormField {
1534 function getSize() {
1535 return isset( $this->mParams['size'] )
1536 ? $this->mParams['size']
1537 : 45;
1538 }
1539
1540 function getInputHTML( $value ) {
1541 $attribs = array(
1542 'id' => $this->mID,
1543 'name' => $this->mName,
1544 'size' => $this->getSize(),
1545 'value' => $value,
1546 ) + $this->getTooltipAndAccessKey();
1547
1548 if ( $this->mClass !== '' ) {
1549 $attribs['class'] = $this->mClass;
1550 }
1551
1552 if ( !empty( $this->mParams['disabled'] ) ) {
1553 $attribs['disabled'] = 'disabled';
1554 }
1555
1556 # TODO: Enforce pattern, step, required, readonly on the server side as
1557 # well
1558 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1559 'placeholder', 'list', 'maxlength' );
1560 foreach ( $allowedParams as $param ) {
1561 if ( isset( $this->mParams[$param] ) ) {
1562 $attribs[$param] = $this->mParams[$param];
1563 }
1564 }
1565
1566 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1567 if ( isset( $this->mParams[$param] ) ) {
1568 $attribs[$param] = '';
1569 }
1570 }
1571
1572 # Implement tiny differences between some field variants
1573 # here, rather than creating a new class for each one which
1574 # is essentially just a clone of this one.
1575 if ( isset( $this->mParams['type'] ) ) {
1576 switch ( $this->mParams['type'] ) {
1577 case 'email':
1578 $attribs['type'] = 'email';
1579 break;
1580 case 'int':
1581 $attribs['type'] = 'number';
1582 break;
1583 case 'float':
1584 $attribs['type'] = 'number';
1585 $attribs['step'] = 'any';
1586 break;
1587 # Pass through
1588 case 'password':
1589 case 'file':
1590 $attribs['type'] = $this->mParams['type'];
1591 break;
1592 }
1593 }
1594
1595 return Html::element( 'input', $attribs );
1596 }
1597 }
1598 class HTMLTextAreaField extends HTMLFormField {
1599 function getCols() {
1600 return isset( $this->mParams['cols'] )
1601 ? $this->mParams['cols']
1602 : 80;
1603 }
1604
1605 function getRows() {
1606 return isset( $this->mParams['rows'] )
1607 ? $this->mParams['rows']
1608 : 25;
1609 }
1610
1611 function getInputHTML( $value ) {
1612 $attribs = array(
1613 'id' => $this->mID,
1614 'name' => $this->mName,
1615 'cols' => $this->getCols(),
1616 'rows' => $this->getRows(),
1617 ) + $this->getTooltipAndAccessKey();
1618
1619 if ( $this->mClass !== '' ) {
1620 $attribs['class'] = $this->mClass;
1621 }
1622
1623 if ( !empty( $this->mParams['disabled'] ) ) {
1624 $attribs['disabled'] = 'disabled';
1625 }
1626
1627 if ( !empty( $this->mParams['readonly'] ) ) {
1628 $attribs['readonly'] = 'readonly';
1629 }
1630
1631 if ( isset( $this->mParams['placeholder'] ) ) {
1632 $attribs['placeholder'] = $this->mParams['placeholder'];
1633 }
1634
1635 foreach ( array( 'required', 'autofocus' ) as $param ) {
1636 if ( isset( $this->mParams[$param] ) ) {
1637 $attribs[$param] = '';
1638 }
1639 }
1640
1641 return Html::element( 'textarea', $attribs, $value );
1642 }
1643 }
1644
1645 /**
1646 * A field that will contain a numeric value
1647 */
1648 class HTMLFloatField extends HTMLTextField {
1649 function getSize() {
1650 return isset( $this->mParams['size'] )
1651 ? $this->mParams['size']
1652 : 20;
1653 }
1654
1655 function validate( $value, $alldata ) {
1656 $p = parent::validate( $value, $alldata );
1657
1658 if ( $p !== true ) {
1659 return $p;
1660 }
1661
1662 $value = trim( $value );
1663
1664 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1665 # with the addition that a leading '+' sign is ok.
1666 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1667 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1668 }
1669
1670 # The "int" part of these message names is rather confusing.
1671 # They make equal sense for all numbers.
1672 if ( isset( $this->mParams['min'] ) ) {
1673 $min = $this->mParams['min'];
1674
1675 if ( $min > $value ) {
1676 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1677 }
1678 }
1679
1680 if ( isset( $this->mParams['max'] ) ) {
1681 $max = $this->mParams['max'];
1682
1683 if ( $max < $value ) {
1684 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1685 }
1686 }
1687
1688 return true;
1689 }
1690 }
1691
1692 /**
1693 * A field that must contain a number
1694 */
1695 class HTMLIntField extends HTMLFloatField {
1696 function validate( $value, $alldata ) {
1697 $p = parent::validate( $value, $alldata );
1698
1699 if ( $p !== true ) {
1700 return $p;
1701 }
1702
1703 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1704 # with the addition that a leading '+' sign is ok. Note that leading zeros
1705 # are fine, and will be left in the input, which is useful for things like
1706 # phone numbers when you know that they are integers (the HTML5 type=tel
1707 # input does not require its value to be numeric). If you want a tidier
1708 # value to, eg, save in the DB, clean it up with intval().
1709 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1710 ) {
1711 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1712 }
1713
1714 return true;
1715 }
1716 }
1717
1718 /**
1719 * A checkbox field
1720 */
1721 class HTMLCheckField extends HTMLFormField {
1722 function getInputHTML( $value ) {
1723 if ( !empty( $this->mParams['invert'] ) ) {
1724 $value = !$value;
1725 }
1726
1727 $attr = $this->getTooltipAndAccessKey();
1728 $attr['id'] = $this->mID;
1729
1730 if ( !empty( $this->mParams['disabled'] ) ) {
1731 $attr['disabled'] = 'disabled';
1732 }
1733
1734 if ( $this->mClass !== '' ) {
1735 $attr['class'] = $this->mClass;
1736 }
1737
1738 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1739 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1740 }
1741
1742 /**
1743 * For a checkbox, the label goes on the right hand side, and is
1744 * added in getInputHTML(), rather than HTMLFormField::getRow()
1745 * @return String
1746 */
1747 function getLabel() {
1748 return '&#160;';
1749 }
1750
1751 /**
1752 * @param $request WebRequest
1753 * @return String
1754 */
1755 function loadDataFromRequest( $request ) {
1756 $invert = false;
1757 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1758 $invert = true;
1759 }
1760
1761 // GetCheck won't work like we want for checks.
1762 // Fetch the value in either one of the two following case:
1763 // - we have a valid token (form got posted or GET forged by the user)
1764 // - checkbox name has a value (false or true), ie is not null
1765 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1766 // XOR has the following truth table, which is what we want
1767 // INVERT VALUE | OUTPUT
1768 // true true | false
1769 // false true | true
1770 // false false | false
1771 // true false | true
1772 return $request->getBool( $this->mName ) xor $invert;
1773 } else {
1774 return $this->getDefault();
1775 }
1776 }
1777 }
1778
1779 /**
1780 * A select dropdown field. Basically a wrapper for Xmlselect class
1781 */
1782 class HTMLSelectField extends HTMLFormField {
1783 function validate( $value, $alldata ) {
1784 $p = parent::validate( $value, $alldata );
1785
1786 if ( $p !== true ) {
1787 return $p;
1788 }
1789
1790 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1791
1792 if ( in_array( $value, $validOptions ) )
1793 return true;
1794 else
1795 return $this->msg( 'htmlform-select-badoption' )->parse();
1796 }
1797
1798 function getInputHTML( $value ) {
1799 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1800
1801 # If one of the options' 'name' is int(0), it is automatically selected.
1802 # because PHP sucks and thinks int(0) == 'some string'.
1803 # Working around this by forcing all of them to strings.
1804 foreach ( $this->mParams['options'] as &$opt ) {
1805 if ( is_int( $opt ) ) {
1806 $opt = strval( $opt );
1807 }
1808 }
1809 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1810
1811 if ( !empty( $this->mParams['disabled'] ) ) {
1812 $select->setAttribute( 'disabled', 'disabled' );
1813 }
1814
1815 if ( $this->mClass !== '' ) {
1816 $select->setAttribute( 'class', $this->mClass );
1817 }
1818
1819 $select->addOptions( $this->mParams['options'] );
1820
1821 return $select->getHTML();
1822 }
1823 }
1824
1825 /**
1826 * Select dropdown field, with an additional "other" textbox.
1827 */
1828 class HTMLSelectOrOtherField extends HTMLTextField {
1829 static $jsAdded = false;
1830
1831 function __construct( $params ) {
1832 if ( !in_array( 'other', $params['options'], true ) ) {
1833 $msg = isset( $params['other'] ) ?
1834 $params['other'] :
1835 wfMessage( 'htmlform-selectorother-other' )->text();
1836 $params['options'][$msg] = 'other';
1837 }
1838
1839 parent::__construct( $params );
1840 }
1841
1842 static function forceToStringRecursive( $array ) {
1843 if ( is_array( $array ) ) {
1844 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1845 } else {
1846 return strval( $array );
1847 }
1848 }
1849
1850 function getInputHTML( $value ) {
1851 $valInSelect = false;
1852
1853 if ( $value !== false ) {
1854 $valInSelect = in_array(
1855 $value,
1856 HTMLFormField::flattenOptions( $this->mParams['options'] )
1857 );
1858 }
1859
1860 $selected = $valInSelect ? $value : 'other';
1861
1862 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1863
1864 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1865 $select->addOptions( $opts );
1866
1867 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1868
1869 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1870
1871 if ( !empty( $this->mParams['disabled'] ) ) {
1872 $select->setAttribute( 'disabled', 'disabled' );
1873 $tbAttribs['disabled'] = 'disabled';
1874 }
1875
1876 $select = $select->getHTML();
1877
1878 if ( isset( $this->mParams['maxlength'] ) ) {
1879 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1880 }
1881
1882 if ( $this->mClass !== '' ) {
1883 $tbAttribs['class'] = $this->mClass;
1884 }
1885
1886 $textbox = Html::input(
1887 $this->mName . '-other',
1888 $valInSelect ? '' : $value,
1889 'text',
1890 $tbAttribs
1891 );
1892
1893 return "$select<br />\n$textbox";
1894 }
1895
1896 /**
1897 * @param $request WebRequest
1898 * @return String
1899 */
1900 function loadDataFromRequest( $request ) {
1901 if ( $request->getCheck( $this->mName ) ) {
1902 $val = $request->getText( $this->mName );
1903
1904 if ( $val == 'other' ) {
1905 $val = $request->getText( $this->mName . '-other' );
1906 }
1907
1908 return $val;
1909 } else {
1910 return $this->getDefault();
1911 }
1912 }
1913 }
1914
1915 /**
1916 * Multi-select field
1917 */
1918 class HTMLMultiSelectField extends HTMLFormField {
1919
1920 function validate( $value, $alldata ) {
1921 $p = parent::validate( $value, $alldata );
1922
1923 if ( $p !== true ) {
1924 return $p;
1925 }
1926
1927 if ( !is_array( $value ) ) {
1928 return false;
1929 }
1930
1931 # If all options are valid, array_intersect of the valid options
1932 # and the provided options will return the provided options.
1933 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1934
1935 $validValues = array_intersect( $value, $validOptions );
1936 if ( count( $validValues ) == count( $value ) ) {
1937 return true;
1938 } else {
1939 return $this->msg( 'htmlform-select-badoption' )->parse();
1940 }
1941 }
1942
1943 function getInputHTML( $value ) {
1944 $html = $this->formatOptions( $this->mParams['options'], $value );
1945
1946 return $html;
1947 }
1948
1949 function formatOptions( $options, $value ) {
1950 $html = '';
1951
1952 $attribs = array();
1953
1954 if ( !empty( $this->mParams['disabled'] ) ) {
1955 $attribs['disabled'] = 'disabled';
1956 }
1957
1958 foreach ( $options as $label => $info ) {
1959 if ( is_array( $info ) ) {
1960 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1961 $html .= $this->formatOptions( $info, $value );
1962 } else {
1963 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1964
1965 $checkbox = Xml::check(
1966 $this->mName . '[]',
1967 in_array( $info, $value, true ),
1968 $attribs + $thisAttribs );
1969 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1970
1971 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1972 }
1973 }
1974
1975 return $html;
1976 }
1977
1978 /**
1979 * @param $request WebRequest
1980 * @return String
1981 */
1982 function loadDataFromRequest( $request ) {
1983 if ( $this->mParent->getMethod() == 'post' ) {
1984 if ( $request->wasPosted() ) {
1985 # Checkboxes are just not added to the request arrays if they're not checked,
1986 # so it's perfectly possible for there not to be an entry at all
1987 return $request->getArray( $this->mName, array() );
1988 } else {
1989 # That's ok, the user has not yet submitted the form, so show the defaults
1990 return $this->getDefault();
1991 }
1992 } else {
1993 # This is the impossible case: if we look at $_GET and see no data for our
1994 # field, is it because the user has not yet submitted the form, or that they
1995 # have submitted it with all the options unchecked? We will have to assume the
1996 # latter, which basically means that you can't specify 'positive' defaults
1997 # for GET forms.
1998 # @todo FIXME...
1999 return $request->getArray( $this->mName, array() );
2000 }
2001 }
2002
2003 function getDefault() {
2004 if ( isset( $this->mDefault ) ) {
2005 return $this->mDefault;
2006 } else {
2007 return array();
2008 }
2009 }
2010
2011 protected function needsLabel() {
2012 return false;
2013 }
2014 }
2015
2016 /**
2017 * Double field with a dropdown list constructed from a system message in the format
2018 * * Optgroup header
2019 * ** <option value>
2020 * * New Optgroup header
2021 * Plus a text field underneath for an additional reason. The 'value' of the field is
2022 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2023 * select dropdown.
2024 * @todo FIXME: If made 'required', only the text field should be compulsory.
2025 */
2026 class HTMLSelectAndOtherField extends HTMLSelectField {
2027
2028 function __construct( $params ) {
2029 if ( array_key_exists( 'other', $params ) ) {
2030 } elseif ( array_key_exists( 'other-message', $params ) ) {
2031 $params['other'] = wfMessage( $params['other-message'] )->plain();
2032 } else {
2033 $params['other'] = null;
2034 }
2035
2036 if ( array_key_exists( 'options', $params ) ) {
2037 # Options array already specified
2038 } elseif ( array_key_exists( 'options-message', $params ) ) {
2039 # Generate options array from a system message
2040 $params['options'] = self::parseMessage(
2041 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2042 $params['other']
2043 );
2044 } else {
2045 # Sulk
2046 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2047 }
2048 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2049
2050 parent::__construct( $params );
2051 }
2052
2053 /**
2054 * Build a drop-down box from a textual list.
2055 * @param $string String message text
2056 * @param $otherName String name of "other reason" option
2057 * @return Array
2058 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2059 */
2060 public static function parseMessage( $string, $otherName = null ) {
2061 if ( $otherName === null ) {
2062 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2063 }
2064
2065 $optgroup = false;
2066 $options = array( $otherName => 'other' );
2067
2068 foreach ( explode( "\n", $string ) as $option ) {
2069 $value = trim( $option );
2070 if ( $value == '' ) {
2071 continue;
2072 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2073 # A new group is starting...
2074 $value = trim( substr( $value, 1 ) );
2075 $optgroup = $value;
2076 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2077 # groupmember
2078 $opt = trim( substr( $value, 2 ) );
2079 if ( $optgroup === false ) {
2080 $options[$opt] = $opt;
2081 } else {
2082 $options[$optgroup][$opt] = $opt;
2083 }
2084 } else {
2085 # groupless reason list
2086 $optgroup = false;
2087 $options[$option] = $option;
2088 }
2089 }
2090
2091 return $options;
2092 }
2093
2094 function getInputHTML( $value ) {
2095 $select = parent::getInputHTML( $value[1] );
2096
2097 $textAttribs = array(
2098 'id' => $this->mID . '-other',
2099 'size' => $this->getSize(),
2100 );
2101
2102 if ( $this->mClass !== '' ) {
2103 $textAttribs['class'] = $this->mClass;
2104 }
2105
2106 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2107 if ( isset( $this->mParams[$param] ) ) {
2108 $textAttribs[$param] = '';
2109 }
2110 }
2111
2112 $textbox = Html::input(
2113 $this->mName . '-other',
2114 $value[2],
2115 'text',
2116 $textAttribs
2117 );
2118
2119 return "$select<br />\n$textbox";
2120 }
2121
2122 /**
2123 * @param $request WebRequest
2124 * @return Array("<overall message>","<select value>","<text field value>")
2125 */
2126 function loadDataFromRequest( $request ) {
2127 if ( $request->getCheck( $this->mName ) ) {
2128
2129 $list = $request->getText( $this->mName );
2130 $text = $request->getText( $this->mName . '-other' );
2131
2132 if ( $list == 'other' ) {
2133 $final = $text;
2134 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2135 # User has spoofed the select form to give an option which wasn't
2136 # in the original offer. Sulk...
2137 $final = $text;
2138 } elseif ( $text == '' ) {
2139 $final = $list;
2140 } else {
2141 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2142 }
2143
2144 } else {
2145 $final = $this->getDefault();
2146
2147 $list = 'other';
2148 $text = $final;
2149 foreach ( $this->mFlatOptions as $option ) {
2150 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2151 if ( strpos( $text, $match ) === 0 ) {
2152 $list = $option;
2153 $text = substr( $text, strlen( $match ) );
2154 break;
2155 }
2156 }
2157 }
2158 return array( $final, $list, $text );
2159 }
2160
2161 function getSize() {
2162 return isset( $this->mParams['size'] )
2163 ? $this->mParams['size']
2164 : 45;
2165 }
2166
2167 function validate( $value, $alldata ) {
2168 # HTMLSelectField forces $value to be one of the options in the select
2169 # field, which is not useful here. But we do want the validation further up
2170 # the chain
2171 $p = parent::validate( $value[1], $alldata );
2172
2173 if ( $p !== true ) {
2174 return $p;
2175 }
2176
2177 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2178 return $this->msg( 'htmlform-required' )->parse();
2179 }
2180
2181 return true;
2182 }
2183 }
2184
2185 /**
2186 * Radio checkbox fields.
2187 */
2188 class HTMLRadioField extends HTMLFormField {
2189
2190
2191 function validate( $value, $alldata ) {
2192 $p = parent::validate( $value, $alldata );
2193
2194 if ( $p !== true ) {
2195 return $p;
2196 }
2197
2198 if ( !is_string( $value ) && !is_int( $value ) ) {
2199 return false;
2200 }
2201
2202 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2203
2204 if ( in_array( $value, $validOptions ) ) {
2205 return true;
2206 } else {
2207 return $this->msg( 'htmlform-select-badoption' )->parse();
2208 }
2209 }
2210
2211 /**
2212 * This returns a block of all the radio options, in one cell.
2213 * @see includes/HTMLFormField#getInputHTML()
2214 * @param $value String
2215 * @return String
2216 */
2217 function getInputHTML( $value ) {
2218 $html = $this->formatOptions( $this->mParams['options'], $value );
2219
2220 return $html;
2221 }
2222
2223 function formatOptions( $options, $value ) {
2224 $html = '';
2225
2226 $attribs = array();
2227 if ( !empty( $this->mParams['disabled'] ) ) {
2228 $attribs['disabled'] = 'disabled';
2229 }
2230
2231 # TODO: should this produce an unordered list perhaps?
2232 foreach ( $options as $label => $info ) {
2233 if ( is_array( $info ) ) {
2234 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2235 $html .= $this->formatOptions( $info, $value );
2236 } else {
2237 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2238 $radio = Xml::radio(
2239 $this->mName,
2240 $info,
2241 $info == $value,
2242 $attribs + array( 'id' => $id )
2243 );
2244 $radio .= '&#160;' .
2245 Html::rawElement( 'label', array( 'for' => $id ), $label );
2246
2247 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2248 }
2249 }
2250
2251 return $html;
2252 }
2253
2254 protected function needsLabel() {
2255 return false;
2256 }
2257 }
2258
2259 /**
2260 * An information field (text blob), not a proper input.
2261 */
2262 class HTMLInfoField extends HTMLFormField {
2263 public function __construct( $info ) {
2264 $info['nodata'] = true;
2265
2266 parent::__construct( $info );
2267 }
2268
2269 public function getInputHTML( $value ) {
2270 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2271 }
2272
2273 public function getTableRow( $value ) {
2274 if ( !empty( $this->mParams['rawrow'] ) ) {
2275 return $value;
2276 }
2277
2278 return parent::getTableRow( $value );
2279 }
2280
2281 /**
2282 * @since 1.20
2283 */
2284 public function getDiv( $value ) {
2285 if ( !empty( $this->mParams['rawrow'] ) ) {
2286 return $value;
2287 }
2288
2289 return parent::getDiv( $value );
2290 }
2291
2292 /**
2293 * @since 1.20
2294 */
2295 public function getRaw( $value ) {
2296 if ( !empty( $this->mParams['rawrow'] ) ) {
2297 return $value;
2298 }
2299
2300 return parent::getRaw( $value );
2301 }
2302
2303 protected function needsLabel() {
2304 return false;
2305 }
2306 }
2307
2308 class HTMLHiddenField extends HTMLFormField {
2309 public function __construct( $params ) {
2310 parent::__construct( $params );
2311
2312 # Per HTML5 spec, hidden fields cannot be 'required'
2313 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2314 unset( $this->mParams['required'] );
2315 }
2316
2317 public function getTableRow( $value ) {
2318 $params = array();
2319 if ( $this->mID ) {
2320 $params['id'] = $this->mID;
2321 }
2322
2323 $this->mParent->addHiddenField(
2324 $this->mName,
2325 $this->mDefault,
2326 $params
2327 );
2328
2329 return '';
2330 }
2331
2332 /**
2333 * @since 1.20
2334 */
2335 public function getDiv( $value ) {
2336 return $this->getTableRow( $value );
2337 }
2338
2339 /**
2340 * @since 1.20
2341 */
2342 public function getRaw( $value ) {
2343 return $this->getTableRow( $value );
2344 }
2345
2346 public function getInputHTML( $value ) { return ''; }
2347 }
2348
2349 /**
2350 * Add a submit button inline in the form (as opposed to
2351 * HTMLForm::addButton(), which will add it at the end).
2352 */
2353 class HTMLSubmitField extends HTMLFormField {
2354
2355 public function __construct( $info ) {
2356 $info['nodata'] = true;
2357 parent::__construct( $info );
2358 }
2359
2360 public function getInputHTML( $value ) {
2361 return Xml::submitButton(
2362 $value,
2363 array(
2364 'class' => 'mw-htmlform-submit ' . $this->mClass,
2365 'name' => $this->mName,
2366 'id' => $this->mID,
2367 )
2368 );
2369 }
2370
2371 protected function needsLabel() {
2372 return false;
2373 }
2374
2375 /**
2376 * Button cannot be invalid
2377 * @param $value String
2378 * @param $alldata Array
2379 * @return Bool
2380 */
2381 public function validate( $value, $alldata ) {
2382 return true;
2383 }
2384 }
2385
2386 class HTMLEditTools extends HTMLFormField {
2387 public function getInputHTML( $value ) {
2388 return '';
2389 }
2390
2391 public function getTableRow( $value ) {
2392 $msg = $this->formatMsg();
2393
2394 return '<tr><td></td><td class="mw-input">'
2395 . '<div class="mw-editTools">'
2396 . $msg->parseAsBlock()
2397 . "</div></td></tr>\n";
2398 }
2399
2400 /**
2401 * @since 1.20
2402 */
2403 public function getDiv( $value ) {
2404 $msg = $this->formatMsg();
2405 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2406 }
2407
2408 /**
2409 * @since 1.20
2410 */
2411 public function getRaw( $value ) {
2412 return $this->getDiv( $value );
2413 }
2414
2415 protected function formatMsg() {
2416 if ( empty( $this->mParams['message'] ) ) {
2417 $msg = $this->msg( 'edittools' );
2418 } else {
2419 $msg = $this->msg( $this->mParams['message'] );
2420 if ( $msg->isDisabled() ) {
2421 $msg = $this->msg( 'edittools' );
2422 }
2423 }
2424 $msg->inContentLanguage();
2425 return $msg;
2426 }
2427 }