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