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