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