Merge "jquery.tablesorter: Support genitive month names"
[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 = '<span class="mw-htmlform-submit-buttons">';
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 $html .= '</span>';
754
755 return $html;
756 }
757
758 /**
759 * Get the whole body of the form.
760 * @return String
761 */
762 function getBody() {
763 return $this->displaySection( $this->mFieldTree, $this->mTableId );
764 }
765
766 /**
767 * Format and display an error message stack.
768 * @param $errors String|Array|Status
769 * @return String
770 */
771 function getErrors( $errors ) {
772 if ( $errors instanceof Status ) {
773 if ( $errors->isOK() ) {
774 $errorstr = '';
775 } else {
776 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
777 }
778 } elseif ( is_array( $errors ) ) {
779 $errorstr = $this->formatErrors( $errors );
780 } else {
781 $errorstr = $errors;
782 }
783
784 return $errorstr
785 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
786 : '';
787 }
788
789 /**
790 * Format a stack of error messages into a single HTML string
791 * @param array $errors of message keys/values
792 * @return String HTML, a "<ul>" list of errors
793 */
794 public static function formatErrors( $errors ) {
795 $errorstr = '';
796
797 foreach ( $errors as $error ) {
798 if ( is_array( $error ) ) {
799 $msg = array_shift( $error );
800 } else {
801 $msg = $error;
802 $error = array();
803 }
804
805 $errorstr .= Html::rawElement(
806 'li',
807 array(),
808 wfMessage( $msg, $error )->parse()
809 );
810 }
811
812 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
813
814 return $errorstr;
815 }
816
817 /**
818 * Set the text for the submit button
819 * @param string $t plaintext.
820 * @return HTMLForm $this for chaining calls (since 1.20)
821 */
822 function setSubmitText( $t ) {
823 $this->mSubmitText = $t;
824 return $this;
825 }
826
827 /**
828 * Set the text for the submit button to a message
829 * @since 1.19
830 * @param string $msg message key
831 * @return HTMLForm $this for chaining calls (since 1.20)
832 */
833 public function setSubmitTextMsg( $msg ) {
834 $this->setSubmitText( $this->msg( $msg )->text() );
835 return $this;
836 }
837
838 /**
839 * Get the text for the submit button, either customised or a default.
840 * @return string
841 */
842 function getSubmitText() {
843 return $this->mSubmitText
844 ? $this->mSubmitText
845 : $this->msg( 'htmlform-submit' )->text();
846 }
847
848 /**
849 * @param string $name Submit button name
850 * @return HTMLForm $this for chaining calls (since 1.20)
851 */
852 public function setSubmitName( $name ) {
853 $this->mSubmitName = $name;
854 return $this;
855 }
856
857 /**
858 * @param string $name Tooltip for the submit button
859 * @return HTMLForm $this for chaining calls (since 1.20)
860 */
861 public function setSubmitTooltip( $name ) {
862 $this->mSubmitTooltip = $name;
863 return $this;
864 }
865
866 /**
867 * Set the id for the submit button.
868 * @param $t String.
869 * @todo FIXME: Integrity of $t is *not* validated
870 * @return HTMLForm $this for chaining calls (since 1.20)
871 */
872 function setSubmitID( $t ) {
873 $this->mSubmitID = $t;
874 return $this;
875 }
876
877 /**
878 * Stop a default submit button being shown for this form. This implies that an
879 * alternate submit method must be provided manually.
880 *
881 * @since 1.22
882 *
883 * @param bool $suppressSubmit Set to false to re-enable the button again
884 *
885 * @return HTMLForm $this for chaining calls
886 */
887 function suppressDefaultSubmit( $suppressSubmit = true ) {
888 $this->mShowSubmit = !$suppressSubmit;
889 return $this;
890 }
891
892 /**
893 * Set the id of the \<table\> or outermost \<div\> element.
894 *
895 * @since 1.22
896 * @param string $id new value of the id attribute, or "" to remove
897 * @return HTMLForm $this for chaining calls
898 */
899 public function setTableId( $id ) {
900 $this->mTableId = $id;
901 return $this;
902 }
903
904 /**
905 * @param string $id DOM id for the form
906 * @return HTMLForm $this for chaining calls (since 1.20)
907 */
908 public function setId( $id ) {
909 $this->mId = $id;
910 return $this;
911 }
912
913 /**
914 * Prompt the whole form to be wrapped in a "<fieldset>", with
915 * this text as its "<legend>" element.
916 * @param string $legend HTML to go inside the "<legend>" element.
917 * Will be escaped
918 * @return HTMLForm $this for chaining calls (since 1.20)
919 */
920 public function setWrapperLegend( $legend ) {
921 $this->mWrapperLegend = $legend;
922 return $this;
923 }
924
925 /**
926 * Prompt the whole form to be wrapped in a "<fieldset>", with
927 * this message as its "<legend>" element.
928 * @since 1.19
929 * @param string $msg message key
930 * @return HTMLForm $this for chaining calls (since 1.20)
931 */
932 public function setWrapperLegendMsg( $msg ) {
933 $this->setWrapperLegend( $this->msg( $msg )->text() );
934 return $this;
935 }
936
937 /**
938 * Set the prefix for various default messages
939 * @todo currently only used for the "<fieldset>" legend on forms
940 * with multiple sections; should be used elsewhere?
941 * @param $p String
942 * @return HTMLForm $this for chaining calls (since 1.20)
943 */
944 function setMessagePrefix( $p ) {
945 $this->mMessagePrefix = $p;
946 return $this;
947 }
948
949 /**
950 * Set the title for form submission
951 * @param $t Title of page the form is on/should be posted to
952 * @return HTMLForm $this for chaining calls (since 1.20)
953 */
954 function setTitle( $t ) {
955 $this->mTitle = $t;
956 return $this;
957 }
958
959 /**
960 * Get the title
961 * @return Title
962 */
963 function getTitle() {
964 return $this->mTitle === false
965 ? $this->getContext()->getTitle()
966 : $this->mTitle;
967 }
968
969 /**
970 * Set the method used to submit the form
971 * @param $method String
972 * @return HTMLForm $this for chaining calls (since 1.20)
973 */
974 public function setMethod( $method = 'post' ) {
975 $this->mMethod = $method;
976 return $this;
977 }
978
979 public function getMethod() {
980 return $this->mMethod;
981 }
982
983 /**
984 * @todo Document
985 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
986 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
987 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
988 * @param boolean &$hasUserVisibleFields Whether the section had user-visible fields
989 * @return String
990 */
991 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '', &$hasUserVisibleFields = false ) {
992 $displayFormat = $this->getDisplayFormat();
993
994 $html = '';
995 $subsectionHtml = '';
996 $hasLabel = false;
997
998 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ? 'getTableRow' : 'get' . ucfirst( $displayFormat );
999
1000 foreach ( $fields as $key => $value ) {
1001 if ( $value instanceof HTMLFormField ) {
1002 $v = empty( $value->mParams['nodata'] )
1003 ? $this->mFieldData[$key]
1004 : $value->getDefault();
1005 $html .= $value->$getFieldHtmlMethod( $v );
1006
1007 $labelValue = trim( $value->getLabel() );
1008 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1009 $hasLabel = true;
1010 }
1011
1012 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1013 get_class( $value ) !== 'HTMLApiField' ) {
1014 $hasUserVisibleFields = true;
1015 }
1016 } elseif ( is_array( $value ) ) {
1017 $subsectionHasVisibleFields = false;
1018 $section = $this->displaySection( $value, "mw-htmlform-$key", "$fieldsetIDPrefix$key-", $subsectionHasVisibleFields );
1019 $legend = null;
1020
1021 if ( $subsectionHasVisibleFields === true ) {
1022 // Display the section with various niceties.
1023 $hasUserVisibleFields = true;
1024
1025 $legend = $this->getLegend( $key );
1026
1027 if ( isset( $this->mSectionHeaders[$key] ) ) {
1028 $section = $this->mSectionHeaders[$key] . $section;
1029 }
1030 if ( isset( $this->mSectionFooters[$key] ) ) {
1031 $section .= $this->mSectionFooters[$key];
1032 }
1033
1034 $attributes = array();
1035 if ( $fieldsetIDPrefix ) {
1036 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1037 }
1038 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1039 } else {
1040 // Just return the inputs, nothing fancy.
1041 $subsectionHtml .= $section;
1042 }
1043 }
1044 }
1045
1046 if ( $displayFormat !== 'raw' ) {
1047 $classes = array();
1048
1049 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1050 $classes[] = 'mw-htmlform-nolabel';
1051 }
1052
1053 $attribs = array(
1054 'class' => implode( ' ', $classes ),
1055 );
1056
1057 if ( $sectionName ) {
1058 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1059 }
1060
1061 if ( $displayFormat === 'table' ) {
1062 $html = Html::rawElement( 'table', $attribs,
1063 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1064 } elseif ( $displayFormat === 'div' ) {
1065 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1066 }
1067 }
1068
1069 if ( $this->mSubSectionBeforeFields ) {
1070 return $subsectionHtml . "\n" . $html;
1071 } else {
1072 return $html . "\n" . $subsectionHtml;
1073 }
1074 }
1075
1076 /**
1077 * Construct the form fields from the Descriptor array
1078 */
1079 function loadData() {
1080 $fieldData = array();
1081
1082 foreach ( $this->mFlatFields as $fieldname => $field ) {
1083 if ( !empty( $field->mParams['nodata'] ) ) {
1084 continue;
1085 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1086 $fieldData[$fieldname] = $field->getDefault();
1087 } else {
1088 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1089 }
1090 }
1091
1092 # Filter data.
1093 foreach ( $fieldData as $name => &$value ) {
1094 $field = $this->mFlatFields[$name];
1095 $value = $field->filter( $value, $this->mFlatFields );
1096 }
1097
1098 $this->mFieldData = $fieldData;
1099 }
1100
1101 /**
1102 * Stop a reset button being shown for this form
1103 * @param bool $suppressReset set to false to re-enable the
1104 * button again
1105 * @return HTMLForm $this for chaining calls (since 1.20)
1106 */
1107 function suppressReset( $suppressReset = true ) {
1108 $this->mShowReset = !$suppressReset;
1109 return $this;
1110 }
1111
1112 /**
1113 * Overload this if you want to apply special filtration routines
1114 * to the form as a whole, after it's submitted but before it's
1115 * processed.
1116 * @param $data
1117 * @return
1118 */
1119 function filterDataForSubmit( $data ) {
1120 return $data;
1121 }
1122
1123 /**
1124 * Get a string to go in the "<legend>" of a section fieldset.
1125 * Override this if you want something more complicated.
1126 * @param $key String
1127 * @return String
1128 */
1129 public function getLegend( $key ) {
1130 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1131 }
1132
1133 /**
1134 * Set the value for the action attribute of the form.
1135 * When set to false (which is the default state), the set title is used.
1136 *
1137 * @since 1.19
1138 *
1139 * @param string|bool $action
1140 * @return HTMLForm $this for chaining calls (since 1.20)
1141 */
1142 public function setAction( $action ) {
1143 $this->mAction = $action;
1144 return $this;
1145 }
1146
1147 /**
1148 * Get the value for the action attribute of the form.
1149 *
1150 * @since 1.22
1151 *
1152 * @return string
1153 */
1154 public function getAction() {
1155 global $wgScript, $wgArticlePath;
1156
1157 // If an action is alredy provided, return it
1158 if ( $this->mAction !== false ) {
1159 return $this->mAction;
1160 }
1161
1162 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1163 // meaning that getLocalURL() would return something like "index.php?title=...".
1164 // As browser remove the query string before submitting GET forms,
1165 // it means that the title would be lost. In such case use $wgScript instead
1166 // and put title in an hidden field (see getHiddenFields()).
1167 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1168 return $wgScript;
1169 }
1170
1171 return $this->getTitle()->getLocalURL();
1172 }
1173 }
1174
1175 /**
1176 * The parent class to generate form fields. Any field type should
1177 * be a subclass of this.
1178 */
1179 abstract class HTMLFormField {
1180
1181 protected $mValidationCallback;
1182 protected $mFilterCallback;
1183 protected $mName;
1184 public $mParams;
1185 protected $mLabel; # String label. Set on construction
1186 protected $mID;
1187 protected $mClass = '';
1188 protected $mDefault;
1189
1190 /**
1191 * @var bool If true will generate an empty div element with no label
1192 * @since 1.22
1193 */
1194 protected $mShowEmptyLabels = true;
1195
1196 /**
1197 * @var HTMLForm
1198 */
1199 public $mParent;
1200
1201 /**
1202 * This function must be implemented to return the HTML to generate
1203 * the input object itself. It should not implement the surrounding
1204 * table cells/rows, or labels/help messages.
1205 * @param string $value the value to set the input to; eg a default
1206 * text for a text input.
1207 * @return String valid HTML.
1208 */
1209 abstract function getInputHTML( $value );
1210
1211 /**
1212 * Get a translated interface message
1213 *
1214 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1215 * and wfMessage() otherwise.
1216 *
1217 * Parameters are the same as wfMessage().
1218 *
1219 * @return Message object
1220 */
1221 function msg() {
1222 $args = func_get_args();
1223
1224 if ( $this->mParent ) {
1225 $callback = array( $this->mParent, 'msg' );
1226 } else {
1227 $callback = 'wfMessage';
1228 }
1229
1230 return call_user_func_array( $callback, $args );
1231 }
1232
1233 /**
1234 * Override this function to add specific validation checks on the
1235 * field input. Don't forget to call parent::validate() to ensure
1236 * that the user-defined callback mValidationCallback is still run
1237 * @param string $value the value the field was submitted with
1238 * @param array $alldata the data collected from the form
1239 * @return Mixed Bool true on success, or String error to display.
1240 */
1241 function validate( $value, $alldata ) {
1242 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1243 return $this->msg( 'htmlform-required' )->parse();
1244 }
1245
1246 if ( isset( $this->mValidationCallback ) ) {
1247 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1248 }
1249
1250 return true;
1251 }
1252
1253 function filter( $value, $alldata ) {
1254 if ( isset( $this->mFilterCallback ) ) {
1255 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1256 }
1257
1258 return $value;
1259 }
1260
1261 /**
1262 * Should this field have a label, or is there no input element with the
1263 * appropriate id for the label to point to?
1264 *
1265 * @return bool True to output a label, false to suppress
1266 */
1267 protected function needsLabel() {
1268 return true;
1269 }
1270
1271 /**
1272 * Get the value that this input has been set to from a posted form,
1273 * or the input's default value if it has not been set.
1274 * @param $request WebRequest
1275 * @return String the value
1276 */
1277 function loadDataFromRequest( $request ) {
1278 if ( $request->getCheck( $this->mName ) ) {
1279 return $request->getText( $this->mName );
1280 } else {
1281 return $this->getDefault();
1282 }
1283 }
1284
1285 /**
1286 * Initialise the object
1287 * @param array $params Associative Array. See HTMLForm doc for syntax.
1288 *
1289 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
1290 * @throws MWException
1291 */
1292 function __construct( $params ) {
1293 $this->mParams = $params;
1294
1295 # Generate the label from a message, if possible
1296 if ( isset( $params['label-message'] ) ) {
1297 $msgInfo = $params['label-message'];
1298
1299 if ( is_array( $msgInfo ) ) {
1300 $msg = array_shift( $msgInfo );
1301 } else {
1302 $msg = $msgInfo;
1303 $msgInfo = array();
1304 }
1305
1306 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1307 } elseif ( isset( $params['label'] ) ) {
1308 if ( $params['label'] === '&#160;' ) {
1309 // Apparently some things set &nbsp directly and in an odd format
1310 $this->mLabel = '&#160;';
1311 } else {
1312 $this->mLabel = htmlspecialchars( $params['label'] );
1313 }
1314 } elseif ( isset( $params['label-raw'] ) ) {
1315 $this->mLabel = $params['label-raw'];
1316 }
1317
1318 $this->mName = "wp{$params['fieldname']}";
1319 if ( isset( $params['name'] ) ) {
1320 $this->mName = $params['name'];
1321 }
1322
1323 $validName = Sanitizer::escapeId( $this->mName );
1324 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1325 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1326 }
1327
1328 $this->mID = "mw-input-{$this->mName}";
1329
1330 if ( isset( $params['default'] ) ) {
1331 $this->mDefault = $params['default'];
1332 }
1333
1334 if ( isset( $params['id'] ) ) {
1335 $id = $params['id'];
1336 $validId = Sanitizer::escapeId( $id );
1337
1338 if ( $id != $validId ) {
1339 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1340 }
1341
1342 $this->mID = $id;
1343 }
1344
1345 if ( isset( $params['cssclass'] ) ) {
1346 $this->mClass = $params['cssclass'];
1347 }
1348
1349 if ( isset( $params['validation-callback'] ) ) {
1350 $this->mValidationCallback = $params['validation-callback'];
1351 }
1352
1353 if ( isset( $params['filter-callback'] ) ) {
1354 $this->mFilterCallback = $params['filter-callback'];
1355 }
1356
1357 if ( isset( $params['flatlist'] ) ) {
1358 $this->mClass .= ' mw-htmlform-flatlist';
1359 }
1360
1361 if ( isset( $params['hidelabel'] ) ) {
1362 $this->mShowEmptyLabels = false;
1363 }
1364 }
1365
1366 /**
1367 * Get the complete table row for the input, including help text,
1368 * labels, and whatever.
1369 * @param string $value the value to set the input to.
1370 * @return String complete HTML table row.
1371 */
1372 function getTableRow( $value ) {
1373 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1374 $inputHtml = $this->getInputHTML( $value );
1375 $fieldType = get_class( $this );
1376 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1377 $cellAttributes = array();
1378
1379 if ( !empty( $this->mParams['vertical-label'] ) ) {
1380 $cellAttributes['colspan'] = 2;
1381 $verticalLabel = true;
1382 } else {
1383 $verticalLabel = false;
1384 }
1385
1386 $label = $this->getLabelHtml( $cellAttributes );
1387
1388 $field = Html::rawElement(
1389 'td',
1390 array( 'class' => 'mw-input' ) + $cellAttributes,
1391 $inputHtml . "\n$errors"
1392 );
1393
1394 if ( $verticalLabel ) {
1395 $html = Html::rawElement( 'tr',
1396 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1397 $html .= Html::rawElement( 'tr',
1398 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1399 $field );
1400 } else {
1401 $html = Html::rawElement( 'tr',
1402 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1403 $label . $field );
1404 }
1405
1406 return $html . $helptext;
1407 }
1408
1409 /**
1410 * Get the complete div for the input, including help text,
1411 * labels, and whatever.
1412 * @since 1.20
1413 * @param string $value the value to set the input to.
1414 * @return String complete HTML table row.
1415 */
1416 public function getDiv( $value ) {
1417 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1418 $inputHtml = $this->getInputHTML( $value );
1419 $fieldType = get_class( $this );
1420 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1421 $cellAttributes = array();
1422 $label = $this->getLabelHtml( $cellAttributes );
1423
1424 $outerDivClass = array(
1425 'mw-input',
1426 'mw-htmlform-nolabel' => ( $label === '' )
1427 );
1428
1429 $field = Html::rawElement(
1430 'div',
1431 array( 'class' => $outerDivClass ) + $cellAttributes,
1432 $inputHtml . "\n$errors"
1433 );
1434 $html = Html::rawElement( 'div',
1435 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1436 $label . $field );
1437 $html .= $helptext;
1438 return $html;
1439 }
1440
1441 /**
1442 * Get the complete raw fields for the input, including help text,
1443 * labels, and whatever.
1444 * @since 1.20
1445 * @param string $value the value to set the input to.
1446 * @return String complete HTML table row.
1447 */
1448 public function getRaw( $value ) {
1449 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1450 $inputHtml = $this->getInputHTML( $value );
1451 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1452 $cellAttributes = array();
1453 $label = $this->getLabelHtml( $cellAttributes );
1454
1455 $html = "\n$errors";
1456 $html .= $label;
1457 $html .= $inputHtml;
1458 $html .= $helptext;
1459 return $html;
1460 }
1461
1462 /**
1463 * Generate help text HTML in table format
1464 * @since 1.20
1465 * @param $helptext String|null
1466 * @return String
1467 */
1468 public function getHelpTextHtmlTable( $helptext ) {
1469 if ( is_null( $helptext ) ) {
1470 return '';
1471 }
1472
1473 $row = Html::rawElement(
1474 'td',
1475 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1476 $helptext
1477 );
1478 $row = Html::rawElement( 'tr', array(), $row );
1479 return $row;
1480 }
1481
1482 /**
1483 * Generate help text HTML in div format
1484 * @since 1.20
1485 * @param $helptext String|null
1486 * @return String
1487 */
1488 public function getHelpTextHtmlDiv( $helptext ) {
1489 if ( is_null( $helptext ) ) {
1490 return '';
1491 }
1492
1493 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1494 return $div;
1495 }
1496
1497 /**
1498 * Generate help text HTML formatted for raw output
1499 * @since 1.20
1500 * @param $helptext String|null
1501 * @return String
1502 */
1503 public function getHelpTextHtmlRaw( $helptext ) {
1504 return $this->getHelpTextHtmlDiv( $helptext );
1505 }
1506
1507 /**
1508 * Determine the help text to display
1509 * @since 1.20
1510 * @return String
1511 */
1512 public function getHelpText() {
1513 $helptext = null;
1514
1515 if ( isset( $this->mParams['help-message'] ) ) {
1516 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1517 }
1518
1519 if ( isset( $this->mParams['help-messages'] ) ) {
1520 foreach ( $this->mParams['help-messages'] as $name ) {
1521 $helpMessage = (array)$name;
1522 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1523
1524 if ( $msg->exists() ) {
1525 if ( is_null( $helptext ) ) {
1526 $helptext = '';
1527 } else {
1528 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1529 }
1530 $helptext .= $msg->parse(); // Append message
1531 }
1532 }
1533 }
1534 elseif ( isset( $this->mParams['help'] ) ) {
1535 $helptext = $this->mParams['help'];
1536 }
1537 return $helptext;
1538 }
1539
1540 /**
1541 * Determine form errors to display and their classes
1542 * @since 1.20
1543 * @param string $value the value of the input
1544 * @return Array
1545 */
1546 public function getErrorsAndErrorClass( $value ) {
1547 $errors = $this->validate( $value, $this->mParent->mFieldData );
1548
1549 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1550 $errors = '';
1551 $errorClass = '';
1552 } else {
1553 $errors = self::formatErrors( $errors );
1554 $errorClass = 'mw-htmlform-invalid-input';
1555 }
1556 return array( $errors, $errorClass );
1557 }
1558
1559 function getLabel() {
1560 return is_null( $this->mLabel ) ? '' : $this->mLabel;
1561 }
1562
1563 function getLabelHtml( $cellAttributes = array() ) {
1564 # Don't output a for= attribute for labels with no associated input.
1565 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1566 $for = array();
1567
1568 if ( $this->needsLabel() ) {
1569 $for['for'] = $this->mID;
1570 }
1571
1572 $labelValue = trim( $this->getLabel() );
1573 $hasLabel = false;
1574 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
1575 $hasLabel = true;
1576 }
1577
1578 $displayFormat = $this->mParent->getDisplayFormat();
1579 $html = '';
1580
1581 if ( $displayFormat === 'table' ) {
1582 $html = Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1583 Html::rawElement( 'label', $for, $labelValue )
1584 );
1585 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
1586 if ( $displayFormat === 'div' ) {
1587 $html = Html::rawElement(
1588 'div',
1589 array( 'class' => 'mw-label' ) + $cellAttributes,
1590 Html::rawElement( 'label', $for, $labelValue )
1591 );
1592 } else {
1593 $html = Html::rawElement( 'label', $for, $labelValue );
1594 }
1595 }
1596
1597 return $html;
1598 }
1599
1600 function getDefault() {
1601 if ( isset( $this->mDefault ) ) {
1602 return $this->mDefault;
1603 } else {
1604 return null;
1605 }
1606 }
1607
1608 /**
1609 * Returns the attributes required for the tooltip and accesskey.
1610 *
1611 * @return array Attributes
1612 */
1613 public function getTooltipAndAccessKey() {
1614 if ( empty( $this->mParams['tooltip'] ) ) {
1615 return array();
1616 }
1617 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1618 }
1619
1620 /**
1621 * flatten an array of options to a single array, for instance,
1622 * a set of "<options>" inside "<optgroups>".
1623 * @param array $options Associative Array with values either Strings
1624 * or Arrays
1625 * @return Array flattened input
1626 */
1627 public static function flattenOptions( $options ) {
1628 $flatOpts = array();
1629
1630 foreach ( $options as $value ) {
1631 if ( is_array( $value ) ) {
1632 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1633 } else {
1634 $flatOpts[] = $value;
1635 }
1636 }
1637
1638 return $flatOpts;
1639 }
1640
1641 /**
1642 * Formats one or more errors as accepted by field validation-callback.
1643 * @param $errors String|Message|Array of strings or Message instances
1644 * @return String html
1645 * @since 1.18
1646 */
1647 protected static function formatErrors( $errors ) {
1648 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1649 $errors = array_shift( $errors );
1650 }
1651
1652 if ( is_array( $errors ) ) {
1653 $lines = array();
1654 foreach ( $errors as $error ) {
1655 if ( $error instanceof Message ) {
1656 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1657 } else {
1658 $lines[] = Html::rawElement( 'li', array(), $error );
1659 }
1660 }
1661 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1662 } else {
1663 if ( $errors instanceof Message ) {
1664 $errors = $errors->parse();
1665 }
1666 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1667 }
1668 }
1669 }
1670
1671 class HTMLTextField extends HTMLFormField {
1672 function getSize() {
1673 return isset( $this->mParams['size'] )
1674 ? $this->mParams['size']
1675 : 45;
1676 }
1677
1678 function getInputHTML( $value ) {
1679 $attribs = array(
1680 'id' => $this->mID,
1681 'name' => $this->mName,
1682 'size' => $this->getSize(),
1683 'value' => $value,
1684 ) + $this->getTooltipAndAccessKey();
1685
1686 if ( $this->mClass !== '' ) {
1687 $attribs['class'] = $this->mClass;
1688 }
1689
1690 if ( !empty( $this->mParams['disabled'] ) ) {
1691 $attribs['disabled'] = 'disabled';
1692 }
1693
1694 # TODO: Enforce pattern, step, required, readonly on the server side as
1695 # well
1696 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1697 'placeholder', 'list', 'maxlength' );
1698 foreach ( $allowedParams as $param ) {
1699 if ( isset( $this->mParams[$param] ) ) {
1700 $attribs[$param] = $this->mParams[$param];
1701 }
1702 }
1703
1704 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1705 if ( isset( $this->mParams[$param] ) ) {
1706 $attribs[$param] = '';
1707 }
1708 }
1709
1710 # Implement tiny differences between some field variants
1711 # here, rather than creating a new class for each one which
1712 # is essentially just a clone of this one.
1713 if ( isset( $this->mParams['type'] ) ) {
1714 switch ( $this->mParams['type'] ) {
1715 case 'email':
1716 $attribs['type'] = 'email';
1717 break;
1718 case 'int':
1719 $attribs['type'] = 'number';
1720 break;
1721 case 'float':
1722 $attribs['type'] = 'number';
1723 $attribs['step'] = 'any';
1724 break;
1725 # Pass through
1726 case 'password':
1727 case 'file':
1728 $attribs['type'] = $this->mParams['type'];
1729 break;
1730 }
1731 }
1732
1733 return Html::element( 'input', $attribs );
1734 }
1735 }
1736 class HTMLTextAreaField extends HTMLFormField {
1737 const DEFAULT_COLS = 80;
1738 const DEFAULT_ROWS = 25;
1739
1740 function getCols() {
1741 return isset( $this->mParams['cols'] )
1742 ? $this->mParams['cols']
1743 : static::DEFAULT_COLS;
1744 }
1745
1746 function getRows() {
1747 return isset( $this->mParams['rows'] )
1748 ? $this->mParams['rows']
1749 : static::DEFAULT_ROWS;
1750 }
1751
1752 function getInputHTML( $value ) {
1753 $attribs = array(
1754 'id' => $this->mID,
1755 'name' => $this->mName,
1756 'cols' => $this->getCols(),
1757 'rows' => $this->getRows(),
1758 ) + $this->getTooltipAndAccessKey();
1759
1760 if ( $this->mClass !== '' ) {
1761 $attribs['class'] = $this->mClass;
1762 }
1763
1764 if ( !empty( $this->mParams['disabled'] ) ) {
1765 $attribs['disabled'] = 'disabled';
1766 }
1767
1768 if ( !empty( $this->mParams['readonly'] ) ) {
1769 $attribs['readonly'] = 'readonly';
1770 }
1771
1772 if ( isset( $this->mParams['placeholder'] ) ) {
1773 $attribs['placeholder'] = $this->mParams['placeholder'];
1774 }
1775
1776 foreach ( array( 'required', 'autofocus' ) as $param ) {
1777 if ( isset( $this->mParams[$param] ) ) {
1778 $attribs[$param] = '';
1779 }
1780 }
1781
1782 return Html::element( 'textarea', $attribs, $value );
1783 }
1784 }
1785
1786 /**
1787 * A field that will contain a numeric value
1788 */
1789 class HTMLFloatField extends HTMLTextField {
1790 function getSize() {
1791 return isset( $this->mParams['size'] )
1792 ? $this->mParams['size']
1793 : 20;
1794 }
1795
1796 function validate( $value, $alldata ) {
1797 $p = parent::validate( $value, $alldata );
1798
1799 if ( $p !== true ) {
1800 return $p;
1801 }
1802
1803 $value = trim( $value );
1804
1805 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1806 # with the addition that a leading '+' sign is ok.
1807 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1808 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1809 }
1810
1811 # The "int" part of these message names is rather confusing.
1812 # They make equal sense for all numbers.
1813 if ( isset( $this->mParams['min'] ) ) {
1814 $min = $this->mParams['min'];
1815
1816 if ( $min > $value ) {
1817 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1818 }
1819 }
1820
1821 if ( isset( $this->mParams['max'] ) ) {
1822 $max = $this->mParams['max'];
1823
1824 if ( $max < $value ) {
1825 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1826 }
1827 }
1828
1829 return true;
1830 }
1831 }
1832
1833 /**
1834 * A field that must contain a number
1835 */
1836 class HTMLIntField extends HTMLFloatField {
1837 function validate( $value, $alldata ) {
1838 $p = parent::validate( $value, $alldata );
1839
1840 if ( $p !== true ) {
1841 return $p;
1842 }
1843
1844 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1845 # with the addition that a leading '+' sign is ok. Note that leading zeros
1846 # are fine, and will be left in the input, which is useful for things like
1847 # phone numbers when you know that they are integers (the HTML5 type=tel
1848 # input does not require its value to be numeric). If you want a tidier
1849 # value to, eg, save in the DB, clean it up with intval().
1850 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1851 ) {
1852 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1853 }
1854
1855 return true;
1856 }
1857 }
1858
1859 /**
1860 * A checkbox field
1861 */
1862 class HTMLCheckField extends HTMLFormField {
1863 function getInputHTML( $value ) {
1864 if ( !empty( $this->mParams['invert'] ) ) {
1865 $value = !$value;
1866 }
1867
1868 $attr = $this->getTooltipAndAccessKey();
1869 $attr['id'] = $this->mID;
1870
1871 if ( !empty( $this->mParams['disabled'] ) ) {
1872 $attr['disabled'] = 'disabled';
1873 }
1874
1875 if ( $this->mClass !== '' ) {
1876 $attr['class'] = $this->mClass;
1877 }
1878
1879 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1880 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1881 }
1882
1883 /**
1884 * For a checkbox, the label goes on the right hand side, and is
1885 * added in getInputHTML(), rather than HTMLFormField::getRow()
1886 * @return String
1887 */
1888 function getLabel() {
1889 return '&#160;';
1890 }
1891
1892 /**
1893 * @param $request WebRequest
1894 * @return String
1895 */
1896 function loadDataFromRequest( $request ) {
1897 $invert = false;
1898 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1899 $invert = true;
1900 }
1901
1902 // GetCheck won't work like we want for checks.
1903 // Fetch the value in either one of the two following case:
1904 // - we have a valid token (form got posted or GET forged by the user)
1905 // - checkbox name has a value (false or true), ie is not null
1906 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1907 // XOR has the following truth table, which is what we want
1908 // INVERT VALUE | OUTPUT
1909 // true true | false
1910 // false true | true
1911 // false false | false
1912 // true false | true
1913 return $request->getBool( $this->mName ) xor $invert;
1914 } else {
1915 return $this->getDefault();
1916 }
1917 }
1918 }
1919
1920 /**
1921 * A checkbox matrix
1922 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1923 * options, uses an array of rows and an array of columns to dynamically
1924 * construct a matrix of options. The tags used to identify a particular cell
1925 * are of the form "columnName-rowName"
1926 *
1927 * Options:
1928 * - columns
1929 * - Required list of columns in the matrix.
1930 * - rows
1931 * - Required list of rows in the matrix.
1932 * - force-options-on
1933 * - Accepts array of column-row tags to be displayed as enabled but unavailable to change
1934 * - force-options-off
1935 * - Accepts array of column-row tags to be displayed as disabled but unavailable to change.
1936 * - tooltips
1937 * - Optional array mapping row label to tooltip content
1938 * - tooltip-class
1939 * - Optional CSS class used on tooltip container span. Defaults to mw-icon-question.
1940 */
1941 class HTMLCheckMatrix extends HTMLFormField implements HTMLNestedFilterable {
1942
1943 static private $requiredParams = array(
1944 // Required by underlying HTMLFormField
1945 'fieldname',
1946 // Required by HTMLCheckMatrix
1947 'rows', 'columns'
1948 );
1949
1950 public function __construct( $params ) {
1951 $missing = array_diff( self::$requiredParams, array_keys( $params ) );
1952 if ( $missing ) {
1953 throw new HTMLFormFieldRequiredOptionsException( $this, $missing );
1954 }
1955 parent::__construct( $params );
1956 }
1957
1958 function validate( $value, $alldata ) {
1959 $rows = $this->mParams['rows'];
1960 $columns = $this->mParams['columns'];
1961
1962 // Make sure user-defined validation callback is run
1963 $p = parent::validate( $value, $alldata );
1964 if ( $p !== true ) {
1965 return $p;
1966 }
1967
1968 // Make sure submitted value is an array
1969 if ( !is_array( $value ) ) {
1970 return false;
1971 }
1972
1973 // If all options are valid, array_intersect of the valid options
1974 // and the provided options will return the provided options.
1975 $validOptions = array();
1976 foreach ( $rows as $rowTag ) {
1977 foreach ( $columns as $columnTag ) {
1978 $validOptions[] = $columnTag . '-' . $rowTag;
1979 }
1980 }
1981 $validValues = array_intersect( $value, $validOptions );
1982 if ( count( $validValues ) == count( $value ) ) {
1983 return true;
1984 } else {
1985 return $this->msg( 'htmlform-select-badoption' )->parse();
1986 }
1987 }
1988
1989 /**
1990 * Build a table containing a matrix of checkbox options.
1991 * The value of each option is a combination of the row tag and column tag.
1992 * mParams['rows'] is an array with row labels as keys and row tags as values.
1993 * mParams['columns'] is an array with column labels as keys and column tags as values.
1994 * @param array $value of the options that should be checked
1995 * @return String
1996 */
1997 function getInputHTML( $value ) {
1998 $html = '';
1999 $tableContents = '';
2000 $attribs = array();
2001 $rows = $this->mParams['rows'];
2002 $columns = $this->mParams['columns'];
2003
2004 // If the disabled param is set, disable all the options
2005 if ( !empty( $this->mParams['disabled'] ) ) {
2006 $attribs['disabled'] = 'disabled';
2007 }
2008
2009 // Build the column headers
2010 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
2011 foreach ( $columns as $columnLabel => $columnTag ) {
2012 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
2013 }
2014 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
2015
2016 $tooltipClass = 'mw-icon-question';
2017 if ( isset( $this->mParams['tooltip-class'] ) ) {
2018 $tooltipClass = $this->mParams['tooltip-class'];
2019 }
2020
2021 // Build the options matrix
2022 foreach ( $rows as $rowLabel => $rowTag ) {
2023 // Append tooltip if configured
2024 if ( isset( $this->mParams['tooltips'][$rowLabel] ) ) {
2025 $tooltipAttribs = array(
2026 'class' => "mw-htmlform-tooltip $tooltipClass",
2027 'title' => $this->mParams['tooltips'][$rowLabel],
2028 );
2029 $rowLabel .= ' ' . Html::element( 'span', $tooltipAttribs, '' );
2030 }
2031 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
2032 foreach ( $columns as $columnTag ) {
2033 $thisTag = "$columnTag-$rowTag";
2034 // Construct the checkbox
2035 $thisAttribs = array(
2036 'id' => "{$this->mID}-$thisTag",
2037 'value' => $thisTag,
2038 );
2039 $checked = in_array( $thisTag, (array)$value, true );
2040 if ( $this->isTagForcedOff( $thisTag ) ) {
2041 $checked = false;
2042 $thisAttribs['disabled'] = 1;
2043 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2044 $checked = true;
2045 $thisAttribs['disabled'] = 1;
2046 }
2047 $rowContents .= Html::rawElement(
2048 'td',
2049 array(),
2050 Xml::check( "{$this->mName}[]", $checked, $attribs + $thisAttribs )
2051 );
2052 }
2053 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
2054 }
2055
2056 // Put it all in a table
2057 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
2058 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
2059
2060 return $html;
2061 }
2062
2063 protected function isTagForcedOff( $tag ) {
2064 return isset( $this->mParams['force-options-off'] )
2065 && in_array( $tag, $this->mParams['force-options-off'] );
2066 }
2067
2068 protected function isTagForcedOn( $tag ) {
2069 return isset( $this->mParams['force-options-on'] )
2070 && in_array( $tag, $this->mParams['force-options-on'] );
2071 }
2072
2073 /**
2074 * Get the complete table row for the input, including help text,
2075 * labels, and whatever.
2076 * We override this function since the label should always be on a separate
2077 * line above the options in the case of a checkbox matrix, i.e. it's always
2078 * a "vertical-label".
2079 * @param string $value the value to set the input to
2080 * @return String complete HTML table row
2081 */
2082 function getTableRow( $value ) {
2083 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
2084 $inputHtml = $this->getInputHTML( $value );
2085 $fieldType = get_class( $this );
2086 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
2087 $cellAttributes = array( 'colspan' => 2 );
2088
2089 $label = $this->getLabelHtml( $cellAttributes );
2090
2091 $field = Html::rawElement(
2092 'td',
2093 array( 'class' => 'mw-input' ) + $cellAttributes,
2094 $inputHtml . "\n$errors"
2095 );
2096
2097 $html = Html::rawElement( 'tr',
2098 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
2099 $html .= Html::rawElement( 'tr',
2100 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
2101 $field );
2102
2103 return $html . $helptext;
2104 }
2105
2106 /**
2107 * @param $request WebRequest
2108 * @return Array
2109 */
2110 function loadDataFromRequest( $request ) {
2111 if ( $this->mParent->getMethod() == 'post' ) {
2112 if ( $request->wasPosted() ) {
2113 // Checkboxes are not added to the request arrays if they're not checked,
2114 // so it's perfectly possible for there not to be an entry at all
2115 return $request->getArray( $this->mName, array() );
2116 } else {
2117 // That's ok, the user has not yet submitted the form, so show the defaults
2118 return $this->getDefault();
2119 }
2120 } else {
2121 // This is the impossible case: if we look at $_GET and see no data for our
2122 // field, is it because the user has not yet submitted the form, or that they
2123 // have submitted it with all the options unchecked. We will have to assume the
2124 // latter, which basically means that you can't specify 'positive' defaults
2125 // for GET forms.
2126 return $request->getArray( $this->mName, array() );
2127 }
2128 }
2129
2130 function getDefault() {
2131 if ( isset( $this->mDefault ) ) {
2132 return $this->mDefault;
2133 } else {
2134 return array();
2135 }
2136 }
2137
2138 function filterDataForSubmit( $data ) {
2139 $columns = HTMLFormField::flattenOptions( $this->mParams['columns'] );
2140 $rows = HTMLFormField::flattenOptions( $this->mParams['rows'] );
2141 $res = array();
2142 foreach ( $columns as $column ) {
2143 foreach ( $rows as $row ) {
2144 // Make sure option hasn't been forced
2145 $thisTag = "$column-$row";
2146 if ( $this->isTagForcedOff( $thisTag ) ) {
2147 $res[$thisTag] = false;
2148 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2149 $res[$thisTag] = true;
2150 } else {
2151 $res[$thisTag] = in_array( $thisTag, $data );
2152 }
2153 }
2154 }
2155
2156 return $res;
2157 }
2158 }
2159
2160 /**
2161 * A select dropdown field. Basically a wrapper for Xmlselect class
2162 */
2163 class HTMLSelectField extends HTMLFormField {
2164 function validate( $value, $alldata ) {
2165 $p = parent::validate( $value, $alldata );
2166
2167 if ( $p !== true ) {
2168 return $p;
2169 }
2170
2171 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2172
2173 if ( in_array( $value, $validOptions ) ) {
2174 return true;
2175 } else {
2176 return $this->msg( 'htmlform-select-badoption' )->parse();
2177 }
2178 }
2179
2180 function getInputHTML( $value ) {
2181 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
2182
2183 # If one of the options' 'name' is int(0), it is automatically selected.
2184 # because PHP sucks and thinks int(0) == 'some string'.
2185 # Working around this by forcing all of them to strings.
2186 foreach ( $this->mParams['options'] as &$opt ) {
2187 if ( is_int( $opt ) ) {
2188 $opt = strval( $opt );
2189 }
2190 }
2191 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2192
2193 if ( !empty( $this->mParams['disabled'] ) ) {
2194 $select->setAttribute( 'disabled', 'disabled' );
2195 }
2196
2197 if ( $this->mClass !== '' ) {
2198 $select->setAttribute( 'class', $this->mClass );
2199 }
2200
2201 $select->addOptions( $this->mParams['options'] );
2202
2203 return $select->getHTML();
2204 }
2205 }
2206
2207 /**
2208 * Select dropdown field, with an additional "other" textbox.
2209 */
2210 class HTMLSelectOrOtherField extends HTMLTextField {
2211
2212 function __construct( $params ) {
2213 if ( !in_array( 'other', $params['options'], true ) ) {
2214 $msg = isset( $params['other'] ) ?
2215 $params['other'] :
2216 wfMessage( 'htmlform-selectorother-other' )->text();
2217 $params['options'][$msg] = 'other';
2218 }
2219
2220 parent::__construct( $params );
2221 }
2222
2223 static function forceToStringRecursive( $array ) {
2224 if ( is_array( $array ) ) {
2225 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2226 } else {
2227 return strval( $array );
2228 }
2229 }
2230
2231 function getInputHTML( $value ) {
2232 $valInSelect = false;
2233
2234 if ( $value !== false ) {
2235 $valInSelect = in_array(
2236 $value,
2237 HTMLFormField::flattenOptions( $this->mParams['options'] )
2238 );
2239 }
2240
2241 $selected = $valInSelect ? $value : 'other';
2242
2243 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2244
2245 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2246 $select->addOptions( $opts );
2247
2248 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2249
2250 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2251
2252 if ( !empty( $this->mParams['disabled'] ) ) {
2253 $select->setAttribute( 'disabled', 'disabled' );
2254 $tbAttribs['disabled'] = 'disabled';
2255 }
2256
2257 $select = $select->getHTML();
2258
2259 if ( isset( $this->mParams['maxlength'] ) ) {
2260 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2261 }
2262
2263 if ( $this->mClass !== '' ) {
2264 $tbAttribs['class'] = $this->mClass;
2265 }
2266
2267 $textbox = Html::input(
2268 $this->mName . '-other',
2269 $valInSelect ? '' : $value,
2270 'text',
2271 $tbAttribs
2272 );
2273
2274 return "$select<br />\n$textbox";
2275 }
2276
2277 /**
2278 * @param $request WebRequest
2279 * @return String
2280 */
2281 function loadDataFromRequest( $request ) {
2282 if ( $request->getCheck( $this->mName ) ) {
2283 $val = $request->getText( $this->mName );
2284
2285 if ( $val == 'other' ) {
2286 $val = $request->getText( $this->mName . '-other' );
2287 }
2288
2289 return $val;
2290 } else {
2291 return $this->getDefault();
2292 }
2293 }
2294 }
2295
2296 /**
2297 * Multi-select field
2298 */
2299 class HTMLMultiSelectField extends HTMLFormField implements HTMLNestedFilterable {
2300
2301 function validate( $value, $alldata ) {
2302 $p = parent::validate( $value, $alldata );
2303
2304 if ( $p !== true ) {
2305 return $p;
2306 }
2307
2308 if ( !is_array( $value ) ) {
2309 return false;
2310 }
2311
2312 # If all options are valid, array_intersect of the valid options
2313 # and the provided options will return the provided options.
2314 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2315
2316 $validValues = array_intersect( $value, $validOptions );
2317 if ( count( $validValues ) == count( $value ) ) {
2318 return true;
2319 } else {
2320 return $this->msg( 'htmlform-select-badoption' )->parse();
2321 }
2322 }
2323
2324 function getInputHTML( $value ) {
2325 $html = $this->formatOptions( $this->mParams['options'], $value );
2326
2327 return $html;
2328 }
2329
2330 function formatOptions( $options, $value ) {
2331 $html = '';
2332
2333 $attribs = array();
2334
2335 if ( !empty( $this->mParams['disabled'] ) ) {
2336 $attribs['disabled'] = 'disabled';
2337 }
2338
2339 foreach ( $options as $label => $info ) {
2340 if ( is_array( $info ) ) {
2341 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2342 $html .= $this->formatOptions( $info, $value );
2343 } else {
2344 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2345
2346 $checkbox = Xml::check(
2347 $this->mName . '[]',
2348 in_array( $info, $value, true ),
2349 $attribs + $thisAttribs );
2350 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2351
2352 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2353 }
2354 }
2355
2356 return $html;
2357 }
2358
2359 /**
2360 * @param $request WebRequest
2361 * @return String
2362 */
2363 function loadDataFromRequest( $request ) {
2364 if ( $this->mParent->getMethod() == 'post' ) {
2365 if ( $request->wasPosted() ) {
2366 # Checkboxes are just not added to the request arrays if they're not checked,
2367 # so it's perfectly possible for there not to be an entry at all
2368 return $request->getArray( $this->mName, array() );
2369 } else {
2370 # That's ok, the user has not yet submitted the form, so show the defaults
2371 return $this->getDefault();
2372 }
2373 } else {
2374 # This is the impossible case: if we look at $_GET and see no data for our
2375 # field, is it because the user has not yet submitted the form, or that they
2376 # have submitted it with all the options unchecked? We will have to assume the
2377 # latter, which basically means that you can't specify 'positive' defaults
2378 # for GET forms.
2379 # @todo FIXME...
2380 return $request->getArray( $this->mName, array() );
2381 }
2382 }
2383
2384 function getDefault() {
2385 if ( isset( $this->mDefault ) ) {
2386 return $this->mDefault;
2387 } else {
2388 return array();
2389 }
2390 }
2391
2392 function filterDataForSubmit( $data ) {
2393 $options = HTMLFormField::flattenOptions( $this->mParams['options'] );
2394
2395 $res = array();
2396 foreach ( $options as $opt ) {
2397 $res["$opt"] = in_array( $opt, $data );
2398 }
2399
2400 return $res;
2401 }
2402
2403 protected function needsLabel() {
2404 return false;
2405 }
2406 }
2407
2408 /**
2409 * Double field with a dropdown list constructed from a system message in the format
2410 * * Optgroup header
2411 * ** <option value>
2412 * * New Optgroup header
2413 * Plus a text field underneath for an additional reason. The 'value' of the field is
2414 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2415 * select dropdown.
2416 * @todo FIXME: If made 'required', only the text field should be compulsory.
2417 */
2418 class HTMLSelectAndOtherField extends HTMLSelectField {
2419
2420 function __construct( $params ) {
2421 if ( array_key_exists( 'other', $params ) ) {
2422 } elseif ( array_key_exists( 'other-message', $params ) ) {
2423 $params['other'] = wfMessage( $params['other-message'] )->plain();
2424 } else {
2425 $params['other'] = null;
2426 }
2427
2428 if ( array_key_exists( 'options', $params ) ) {
2429 # Options array already specified
2430 } elseif ( array_key_exists( 'options-message', $params ) ) {
2431 # Generate options array from a system message
2432 $params['options'] = self::parseMessage(
2433 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2434 $params['other']
2435 );
2436 } else {
2437 # Sulk
2438 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2439 }
2440 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2441
2442 parent::__construct( $params );
2443 }
2444
2445 /**
2446 * Build a drop-down box from a textual list.
2447 * @param string $string message text
2448 * @param string $otherName name of "other reason" option
2449 * @return Array
2450 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2451 */
2452 public static function parseMessage( $string, $otherName = null ) {
2453 if ( $otherName === null ) {
2454 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2455 }
2456
2457 $optgroup = false;
2458 $options = array( $otherName => 'other' );
2459
2460 foreach ( explode( "\n", $string ) as $option ) {
2461 $value = trim( $option );
2462 if ( $value == '' ) {
2463 continue;
2464 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2465 # A new group is starting...
2466 $value = trim( substr( $value, 1 ) );
2467 $optgroup = $value;
2468 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2469 # groupmember
2470 $opt = trim( substr( $value, 2 ) );
2471 if ( $optgroup === false ) {
2472 $options[$opt] = $opt;
2473 } else {
2474 $options[$optgroup][$opt] = $opt;
2475 }
2476 } else {
2477 # groupless reason list
2478 $optgroup = false;
2479 $options[$option] = $option;
2480 }
2481 }
2482
2483 return $options;
2484 }
2485
2486 function getInputHTML( $value ) {
2487 $select = parent::getInputHTML( $value[1] );
2488
2489 $textAttribs = array(
2490 'id' => $this->mID . '-other',
2491 'size' => $this->getSize(),
2492 );
2493
2494 if ( $this->mClass !== '' ) {
2495 $textAttribs['class'] = $this->mClass;
2496 }
2497
2498 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2499 if ( isset( $this->mParams[$param] ) ) {
2500 $textAttribs[$param] = '';
2501 }
2502 }
2503
2504 $textbox = Html::input(
2505 $this->mName . '-other',
2506 $value[2],
2507 'text',
2508 $textAttribs
2509 );
2510
2511 return "$select<br />\n$textbox";
2512 }
2513
2514 /**
2515 * @param $request WebRequest
2516 * @return Array("<overall message>","<select value>","<text field value>")
2517 */
2518 function loadDataFromRequest( $request ) {
2519 if ( $request->getCheck( $this->mName ) ) {
2520
2521 $list = $request->getText( $this->mName );
2522 $text = $request->getText( $this->mName . '-other' );
2523
2524 if ( $list == 'other' ) {
2525 $final = $text;
2526 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2527 # User has spoofed the select form to give an option which wasn't
2528 # in the original offer. Sulk...
2529 $final = $text;
2530 } elseif ( $text == '' ) {
2531 $final = $list;
2532 } else {
2533 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2534 }
2535
2536 } else {
2537 $final = $this->getDefault();
2538
2539 $list = 'other';
2540 $text = $final;
2541 foreach ( $this->mFlatOptions as $option ) {
2542 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2543 if ( strpos( $text, $match ) === 0 ) {
2544 $list = $option;
2545 $text = substr( $text, strlen( $match ) );
2546 break;
2547 }
2548 }
2549 }
2550 return array( $final, $list, $text );
2551 }
2552
2553 function getSize() {
2554 return isset( $this->mParams['size'] )
2555 ? $this->mParams['size']
2556 : 45;
2557 }
2558
2559 function validate( $value, $alldata ) {
2560 # HTMLSelectField forces $value to be one of the options in the select
2561 # field, which is not useful here. But we do want the validation further up
2562 # the chain
2563 $p = parent::validate( $value[1], $alldata );
2564
2565 if ( $p !== true ) {
2566 return $p;
2567 }
2568
2569 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2570 return $this->msg( 'htmlform-required' )->parse();
2571 }
2572
2573 return true;
2574 }
2575 }
2576
2577 /**
2578 * Radio checkbox fields.
2579 */
2580 class HTMLRadioField extends HTMLFormField {
2581
2582 function validate( $value, $alldata ) {
2583 $p = parent::validate( $value, $alldata );
2584
2585 if ( $p !== true ) {
2586 return $p;
2587 }
2588
2589 if ( !is_string( $value ) && !is_int( $value ) ) {
2590 return false;
2591 }
2592
2593 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2594
2595 if ( in_array( $value, $validOptions ) ) {
2596 return true;
2597 } else {
2598 return $this->msg( 'htmlform-select-badoption' )->parse();
2599 }
2600 }
2601
2602 /**
2603 * This returns a block of all the radio options, in one cell.
2604 * @see includes/HTMLFormField#getInputHTML()
2605 * @param $value String
2606 * @return String
2607 */
2608 function getInputHTML( $value ) {
2609 $html = $this->formatOptions( $this->mParams['options'], $value );
2610
2611 return $html;
2612 }
2613
2614 function formatOptions( $options, $value ) {
2615 $html = '';
2616
2617 $attribs = array();
2618 if ( !empty( $this->mParams['disabled'] ) ) {
2619 $attribs['disabled'] = 'disabled';
2620 }
2621
2622 # TODO: should this produce an unordered list perhaps?
2623 foreach ( $options as $label => $info ) {
2624 if ( is_array( $info ) ) {
2625 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2626 $html .= $this->formatOptions( $info, $value );
2627 } else {
2628 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2629 $radio = Xml::radio(
2630 $this->mName,
2631 $info,
2632 $info == $value,
2633 $attribs + array( 'id' => $id )
2634 );
2635 $radio .= '&#160;' .
2636 Html::rawElement( 'label', array( 'for' => $id ), $label );
2637
2638 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2639 }
2640 }
2641
2642 return $html;
2643 }
2644
2645 protected function needsLabel() {
2646 return false;
2647 }
2648 }
2649
2650 /**
2651 * An information field (text blob), not a proper input.
2652 */
2653 class HTMLInfoField extends HTMLFormField {
2654 public function __construct( $info ) {
2655 $info['nodata'] = true;
2656
2657 parent::__construct( $info );
2658 }
2659
2660 public function getInputHTML( $value ) {
2661 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2662 }
2663
2664 public function getTableRow( $value ) {
2665 if ( !empty( $this->mParams['rawrow'] ) ) {
2666 return $value;
2667 }
2668
2669 return parent::getTableRow( $value );
2670 }
2671
2672 /**
2673 * @since 1.20
2674 */
2675 public function getDiv( $value ) {
2676 if ( !empty( $this->mParams['rawrow'] ) ) {
2677 return $value;
2678 }
2679
2680 return parent::getDiv( $value );
2681 }
2682
2683 /**
2684 * @since 1.20
2685 */
2686 public function getRaw( $value ) {
2687 if ( !empty( $this->mParams['rawrow'] ) ) {
2688 return $value;
2689 }
2690
2691 return parent::getRaw( $value );
2692 }
2693
2694 protected function needsLabel() {
2695 return false;
2696 }
2697 }
2698
2699 class HTMLHiddenField extends HTMLFormField {
2700 public function __construct( $params ) {
2701 parent::__construct( $params );
2702
2703 # Per HTML5 spec, hidden fields cannot be 'required'
2704 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2705 unset( $this->mParams['required'] );
2706 }
2707
2708 public function getTableRow( $value ) {
2709 $params = array();
2710 if ( $this->mID ) {
2711 $params['id'] = $this->mID;
2712 }
2713
2714 $this->mParent->addHiddenField(
2715 $this->mName,
2716 $this->mDefault,
2717 $params
2718 );
2719
2720 return '';
2721 }
2722
2723 /**
2724 * @since 1.20
2725 */
2726 public function getDiv( $value ) {
2727 return $this->getTableRow( $value );
2728 }
2729
2730 /**
2731 * @since 1.20
2732 */
2733 public function getRaw( $value ) {
2734 return $this->getTableRow( $value );
2735 }
2736
2737 public function getInputHTML( $value ) {
2738 return '';
2739 }
2740 }
2741
2742 /**
2743 * Add a submit button inline in the form (as opposed to
2744 * HTMLForm::addButton(), which will add it at the end).
2745 */
2746 class HTMLSubmitField extends HTMLButtonField {
2747 protected $buttonType = 'submit';
2748 }
2749
2750 /**
2751 * Adds a generic button inline to the form. Does not do anything, you must add
2752 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2753 * wish to add a submit button to a form.
2754 *
2755 * @since 1.22
2756 */
2757 class HTMLButtonField extends HTMLFormField {
2758 protected $buttonType = 'button';
2759
2760 public function __construct( $info ) {
2761 $info['nodata'] = true;
2762 parent::__construct( $info );
2763 }
2764
2765 public function getInputHTML( $value ) {
2766 $attr = array(
2767 'class' => 'mw-htmlform-submit ' . $this->mClass,
2768 'id' => $this->mID,
2769 );
2770
2771 if ( !empty( $this->mParams['disabled'] ) ) {
2772 $attr['disabled'] = 'disabled';
2773 }
2774
2775 return Html::input(
2776 $this->mName,
2777 $value,
2778 $this->buttonType,
2779 $attr
2780 );
2781 }
2782
2783 protected function needsLabel() {
2784 return false;
2785 }
2786
2787 /**
2788 * Button cannot be invalid
2789 * @param $value String
2790 * @param $alldata Array
2791 * @return Bool
2792 */
2793 public function validate( $value, $alldata ) {
2794 return true;
2795 }
2796 }
2797
2798 class HTMLEditTools extends HTMLFormField {
2799 public function getInputHTML( $value ) {
2800 return '';
2801 }
2802
2803 public function getTableRow( $value ) {
2804 $msg = $this->formatMsg();
2805
2806 return '<tr><td></td><td class="mw-input">'
2807 . '<div class="mw-editTools">'
2808 . $msg->parseAsBlock()
2809 . "</div></td></tr>\n";
2810 }
2811
2812 /**
2813 * @since 1.20
2814 */
2815 public function getDiv( $value ) {
2816 $msg = $this->formatMsg();
2817 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2818 }
2819
2820 /**
2821 * @since 1.20
2822 */
2823 public function getRaw( $value ) {
2824 return $this->getDiv( $value );
2825 }
2826
2827 protected function formatMsg() {
2828 if ( empty( $this->mParams['message'] ) ) {
2829 $msg = $this->msg( 'edittools' );
2830 } else {
2831 $msg = $this->msg( $this->mParams['message'] );
2832 if ( $msg->isDisabled() ) {
2833 $msg = $this->msg( 'edittools' );
2834 }
2835 }
2836 $msg->inContentLanguage();
2837 return $msg;
2838 }
2839 }
2840
2841 class HTMLApiField extends HTMLFormField {
2842 public function getTableRow( $value ) {
2843 return '';
2844 }
2845
2846 public function getDiv( $value ) {
2847 return $this->getTableRow( $value );
2848 }
2849
2850 public function getRaw( $value ) {
2851 return $this->getTableRow( $value );
2852 }
2853
2854 public function getInputHTML( $value ) {
2855 return '';
2856 }
2857 }
2858
2859 interface HTMLNestedFilterable {
2860 /**
2861 * Support for seperating multi-option preferences into multiple preferences
2862 * Due to lack of array support.
2863 * @param $data array
2864 */
2865 function filterDataForSubmit( $data );
2866 }
2867
2868 class HTMLFormFieldRequiredOptionsException extends MWException {
2869 public function __construct( HTMLFormField $field, array $missing ) {
2870 parent::__construct( sprintf(
2871 "Form type `%s` expected the following parameters to be set: %s",
2872 get_class( $field ),
2873 implode( ', ', $missing )
2874 ) );
2875 }
2876 }