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