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