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