Merge "Add more tests for paragraphs and headings with extra spacing"
[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 * 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 bool If true will generate an empty div element with no label
1115 * @since 1.22
1116 */
1117 protected $mShowEmptyLabels = true;
1118
1119 /**
1120 * @var HTMLForm
1121 */
1122 public $mParent;
1123
1124 /**
1125 * This function must be implemented to return the HTML to generate
1126 * the input object itself. It should not implement the surrounding
1127 * table cells/rows, or labels/help messages.
1128 * @param string $value the value to set the input to; eg a default
1129 * text for a text input.
1130 * @return String valid HTML.
1131 */
1132 abstract function getInputHTML( $value );
1133
1134 /**
1135 * Get a translated interface message
1136 *
1137 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1138 * and wfMessage() otherwise.
1139 *
1140 * Parameters are the same as wfMessage().
1141 *
1142 * @return Message object
1143 */
1144 function msg() {
1145 $args = func_get_args();
1146
1147 if ( $this->mParent ) {
1148 $callback = array( $this->mParent, 'msg' );
1149 } else {
1150 $callback = 'wfMessage';
1151 }
1152
1153 return call_user_func_array( $callback, $args );
1154 }
1155
1156 /**
1157 * Override this function to add specific validation checks on the
1158 * field input. Don't forget to call parent::validate() to ensure
1159 * that the user-defined callback mValidationCallback is still run
1160 * @param string $value the value the field was submitted with
1161 * @param array $alldata the data collected from the form
1162 * @return Mixed Bool true on success, or String error to display.
1163 */
1164 function validate( $value, $alldata ) {
1165 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1166 return $this->msg( 'htmlform-required' )->parse();
1167 }
1168
1169 if ( isset( $this->mValidationCallback ) ) {
1170 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1171 }
1172
1173 return true;
1174 }
1175
1176 function filter( $value, $alldata ) {
1177 if ( isset( $this->mFilterCallback ) ) {
1178 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1179 }
1180
1181 return $value;
1182 }
1183
1184 /**
1185 * Should this field have a label, or is there no input element with the
1186 * appropriate id for the label to point to?
1187 *
1188 * @return bool True to output a label, false to suppress
1189 */
1190 protected function needsLabel() {
1191 return true;
1192 }
1193
1194 /**
1195 * Get the value that this input has been set to from a posted form,
1196 * or the input's default value if it has not been set.
1197 * @param $request WebRequest
1198 * @return String the value
1199 */
1200 function loadDataFromRequest( $request ) {
1201 if ( $request->getCheck( $this->mName ) ) {
1202 return $request->getText( $this->mName );
1203 } else {
1204 return $this->getDefault();
1205 }
1206 }
1207
1208 /**
1209 * Initialise the object
1210 * @param array $params Associative Array. See HTMLForm doc for syntax.
1211 *
1212 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
1213 * @throws MWException
1214 */
1215 function __construct( $params ) {
1216 $this->mParams = $params;
1217
1218 # Generate the label from a message, if possible
1219 if ( isset( $params['label-message'] ) ) {
1220 $msgInfo = $params['label-message'];
1221
1222 if ( is_array( $msgInfo ) ) {
1223 $msg = array_shift( $msgInfo );
1224 } else {
1225 $msg = $msgInfo;
1226 $msgInfo = array();
1227 }
1228
1229 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1230 } elseif ( isset( $params['label'] ) ) {
1231 if ( $params['label'] === '&#160;' ) {
1232 // Apparently some things set &nbsp directly and in an odd format
1233 $this->mLabel = '&#160;';
1234 } else {
1235 $this->mLabel = htmlspecialchars( $params['label'] );
1236 }
1237 } elseif ( isset( $params['label-raw'] ) ) {
1238 $this->mLabel = $params['label-raw'];
1239 }
1240
1241 $this->mName = "wp{$params['fieldname']}";
1242 if ( isset( $params['name'] ) ) {
1243 $this->mName = $params['name'];
1244 }
1245
1246 $validName = Sanitizer::escapeId( $this->mName );
1247 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1248 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1249 }
1250
1251 $this->mID = "mw-input-{$this->mName}";
1252
1253 if ( isset( $params['default'] ) ) {
1254 $this->mDefault = $params['default'];
1255 }
1256
1257 if ( isset( $params['id'] ) ) {
1258 $id = $params['id'];
1259 $validId = Sanitizer::escapeId( $id );
1260
1261 if ( $id != $validId ) {
1262 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1263 }
1264
1265 $this->mID = $id;
1266 }
1267
1268 if ( isset( $params['cssclass'] ) ) {
1269 $this->mClass = $params['cssclass'];
1270 }
1271
1272 if ( isset( $params['validation-callback'] ) ) {
1273 $this->mValidationCallback = $params['validation-callback'];
1274 }
1275
1276 if ( isset( $params['filter-callback'] ) ) {
1277 $this->mFilterCallback = $params['filter-callback'];
1278 }
1279
1280 if ( isset( $params['flatlist'] ) ) {
1281 $this->mClass .= ' mw-htmlform-flatlist';
1282 }
1283
1284 if ( isset( $params['hidelabel'] ) ) {
1285 $this->mShowEmptyLabels = false;
1286 }
1287 }
1288
1289 /**
1290 * Get the complete table row for the input, including help text,
1291 * labels, and whatever.
1292 * @param string $value the value to set the input to.
1293 * @return String complete HTML table row.
1294 */
1295 function getTableRow( $value ) {
1296 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1297 $inputHtml = $this->getInputHTML( $value );
1298 $fieldType = get_class( $this );
1299 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1300 $cellAttributes = array();
1301
1302 if ( !empty( $this->mParams['vertical-label'] ) ) {
1303 $cellAttributes['colspan'] = 2;
1304 $verticalLabel = true;
1305 } else {
1306 $verticalLabel = false;
1307 }
1308
1309 $label = $this->getLabelHtml( $cellAttributes );
1310
1311 $field = Html::rawElement(
1312 'td',
1313 array( 'class' => 'mw-input' ) + $cellAttributes,
1314 $inputHtml . "\n$errors"
1315 );
1316
1317 if ( $verticalLabel ) {
1318 $html = Html::rawElement( 'tr',
1319 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1320 $html .= Html::rawElement( 'tr',
1321 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1322 $field );
1323 } else {
1324 $html = Html::rawElement( 'tr',
1325 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1326 $label . $field );
1327 }
1328
1329 return $html . $helptext;
1330 }
1331
1332 /**
1333 * Get the complete div for the input, including help text,
1334 * labels, and whatever.
1335 * @since 1.20
1336 * @param string $value the value to set the input to.
1337 * @return String complete HTML table row.
1338 */
1339 public function getDiv( $value ) {
1340 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1341 $inputHtml = $this->getInputHTML( $value );
1342 $fieldType = get_class( $this );
1343 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1344 $cellAttributes = array();
1345 $label = $this->getLabelHtml( $cellAttributes );
1346
1347 $outerDivClass = array(
1348 'mw-input',
1349 'mw-htmlform-nolabel' => ( $label === '' )
1350 );
1351
1352 $field = Html::rawElement(
1353 'div',
1354 array( 'class' => $outerDivClass ) + $cellAttributes,
1355 $inputHtml . "\n$errors"
1356 );
1357 $html = Html::rawElement( 'div',
1358 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1359 $label . $field );
1360 $html .= $helptext;
1361 return $html;
1362 }
1363
1364 /**
1365 * Get the complete raw fields for the input, including help text,
1366 * labels, and whatever.
1367 * @since 1.20
1368 * @param string $value the value to set the input to.
1369 * @return String complete HTML table row.
1370 */
1371 public function getRaw( $value ) {
1372 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1373 $inputHtml = $this->getInputHTML( $value );
1374 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1375 $cellAttributes = array();
1376 $label = $this->getLabelHtml( $cellAttributes );
1377
1378 $html = "\n$errors";
1379 $html .= $label;
1380 $html .= $inputHtml;
1381 $html .= $helptext;
1382 return $html;
1383 }
1384
1385 /**
1386 * Generate help text HTML in table format
1387 * @since 1.20
1388 * @param $helptext String|null
1389 * @return String
1390 */
1391 public function getHelpTextHtmlTable( $helptext ) {
1392 if ( is_null( $helptext ) ) {
1393 return '';
1394 }
1395
1396 $row = Html::rawElement(
1397 'td',
1398 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1399 $helptext
1400 );
1401 $row = Html::rawElement( 'tr', array(), $row );
1402 return $row;
1403 }
1404
1405 /**
1406 * Generate help text HTML in div format
1407 * @since 1.20
1408 * @param $helptext String|null
1409 * @return String
1410 */
1411 public function getHelpTextHtmlDiv( $helptext ) {
1412 if ( is_null( $helptext ) ) {
1413 return '';
1414 }
1415
1416 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1417 return $div;
1418 }
1419
1420 /**
1421 * Generate help text HTML formatted for raw output
1422 * @since 1.20
1423 * @param $helptext String|null
1424 * @return String
1425 */
1426 public function getHelpTextHtmlRaw( $helptext ) {
1427 return $this->getHelpTextHtmlDiv( $helptext );
1428 }
1429
1430 /**
1431 * Determine the help text to display
1432 * @since 1.20
1433 * @return String
1434 */
1435 public function getHelpText() {
1436 $helptext = null;
1437
1438 if ( isset( $this->mParams['help-message'] ) ) {
1439 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1440 }
1441
1442 if ( isset( $this->mParams['help-messages'] ) ) {
1443 foreach ( $this->mParams['help-messages'] as $name ) {
1444 $helpMessage = (array)$name;
1445 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1446
1447 if ( $msg->exists() ) {
1448 if ( is_null( $helptext ) ) {
1449 $helptext = '';
1450 } else {
1451 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1452 }
1453 $helptext .= $msg->parse(); // Append message
1454 }
1455 }
1456 }
1457 elseif ( isset( $this->mParams['help'] ) ) {
1458 $helptext = $this->mParams['help'];
1459 }
1460 return $helptext;
1461 }
1462
1463 /**
1464 * Determine form errors to display and their classes
1465 * @since 1.20
1466 * @param string $value the value of the input
1467 * @return Array
1468 */
1469 public function getErrorsAndErrorClass( $value ) {
1470 $errors = $this->validate( $value, $this->mParent->mFieldData );
1471
1472 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1473 $errors = '';
1474 $errorClass = '';
1475 } else {
1476 $errors = self::formatErrors( $errors );
1477 $errorClass = 'mw-htmlform-invalid-input';
1478 }
1479 return array( $errors, $errorClass );
1480 }
1481
1482 function getLabel() {
1483 return is_null( $this->mLabel ) ? '' : $this->mLabel;
1484 }
1485
1486 function getLabelHtml( $cellAttributes = array() ) {
1487 # Don't output a for= attribute for labels with no associated input.
1488 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1489 $for = array();
1490
1491 if ( $this->needsLabel() ) {
1492 $for['for'] = $this->mID;
1493 }
1494
1495 $labelValue = trim( $this->getLabel() );
1496 $hasLabel = false;
1497 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
1498 $hasLabel = true;
1499 }
1500
1501 $displayFormat = $this->mParent->getDisplayFormat();
1502 $html = '';
1503
1504 if ( $displayFormat === 'table' ) {
1505 $html = Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1506 Html::rawElement( 'label', $for, $labelValue )
1507 );
1508 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
1509 if ( $displayFormat === 'div' ) {
1510 $html = Html::rawElement(
1511 'div',
1512 array( 'class' => 'mw-label' ) + $cellAttributes,
1513 Html::rawElement( 'label', $for, $labelValue )
1514 );
1515 } else {
1516 $html = Html::rawElement( 'label', $for, $labelValue );
1517 }
1518 }
1519
1520 return $html;
1521 }
1522
1523 function getDefault() {
1524 if ( isset( $this->mDefault ) ) {
1525 return $this->mDefault;
1526 } else {
1527 return null;
1528 }
1529 }
1530
1531 /**
1532 * Returns the attributes required for the tooltip and accesskey.
1533 *
1534 * @return array Attributes
1535 */
1536 public function getTooltipAndAccessKey() {
1537 if ( empty( $this->mParams['tooltip'] ) ) {
1538 return array();
1539 }
1540 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1541 }
1542
1543 /**
1544 * flatten an array of options to a single array, for instance,
1545 * a set of "<options>" inside "<optgroups>".
1546 * @param array $options Associative Array with values either Strings
1547 * or Arrays
1548 * @return Array flattened input
1549 */
1550 public static function flattenOptions( $options ) {
1551 $flatOpts = array();
1552
1553 foreach ( $options as $value ) {
1554 if ( is_array( $value ) ) {
1555 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1556 } else {
1557 $flatOpts[] = $value;
1558 }
1559 }
1560
1561 return $flatOpts;
1562 }
1563
1564 /**
1565 * Formats one or more errors as accepted by field validation-callback.
1566 * @param $errors String|Message|Array of strings or Message instances
1567 * @return String html
1568 * @since 1.18
1569 */
1570 protected static function formatErrors( $errors ) {
1571 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1572 $errors = array_shift( $errors );
1573 }
1574
1575 if ( is_array( $errors ) ) {
1576 $lines = array();
1577 foreach ( $errors as $error ) {
1578 if ( $error instanceof Message ) {
1579 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1580 } else {
1581 $lines[] = Html::rawElement( 'li', array(), $error );
1582 }
1583 }
1584 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1585 } else {
1586 if ( $errors instanceof Message ) {
1587 $errors = $errors->parse();
1588 }
1589 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1590 }
1591 }
1592 }
1593
1594 class HTMLTextField extends HTMLFormField {
1595 function getSize() {
1596 return isset( $this->mParams['size'] )
1597 ? $this->mParams['size']
1598 : 45;
1599 }
1600
1601 function getInputHTML( $value ) {
1602 $attribs = array(
1603 'id' => $this->mID,
1604 'name' => $this->mName,
1605 'size' => $this->getSize(),
1606 'value' => $value,
1607 ) + $this->getTooltipAndAccessKey();
1608
1609 if ( $this->mClass !== '' ) {
1610 $attribs['class'] = $this->mClass;
1611 }
1612
1613 if ( !empty( $this->mParams['disabled'] ) ) {
1614 $attribs['disabled'] = 'disabled';
1615 }
1616
1617 # TODO: Enforce pattern, step, required, readonly on the server side as
1618 # well
1619 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1620 'placeholder', 'list', 'maxlength' );
1621 foreach ( $allowedParams as $param ) {
1622 if ( isset( $this->mParams[$param] ) ) {
1623 $attribs[$param] = $this->mParams[$param];
1624 }
1625 }
1626
1627 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1628 if ( isset( $this->mParams[$param] ) ) {
1629 $attribs[$param] = '';
1630 }
1631 }
1632
1633 # Implement tiny differences between some field variants
1634 # here, rather than creating a new class for each one which
1635 # is essentially just a clone of this one.
1636 if ( isset( $this->mParams['type'] ) ) {
1637 switch ( $this->mParams['type'] ) {
1638 case 'email':
1639 $attribs['type'] = 'email';
1640 break;
1641 case 'int':
1642 $attribs['type'] = 'number';
1643 break;
1644 case 'float':
1645 $attribs['type'] = 'number';
1646 $attribs['step'] = 'any';
1647 break;
1648 # Pass through
1649 case 'password':
1650 case 'file':
1651 $attribs['type'] = $this->mParams['type'];
1652 break;
1653 }
1654 }
1655
1656 return Html::element( 'input', $attribs );
1657 }
1658 }
1659 class HTMLTextAreaField extends HTMLFormField {
1660 const DEFAULT_COLS = 80;
1661 const DEFAULT_ROWS = 25;
1662
1663 function getCols() {
1664 return isset( $this->mParams['cols'] )
1665 ? $this->mParams['cols']
1666 : static::DEFAULT_COLS;
1667 }
1668
1669 function getRows() {
1670 return isset( $this->mParams['rows'] )
1671 ? $this->mParams['rows']
1672 : static::DEFAULT_ROWS;
1673 }
1674
1675 function getInputHTML( $value ) {
1676 $attribs = array(
1677 'id' => $this->mID,
1678 'name' => $this->mName,
1679 'cols' => $this->getCols(),
1680 'rows' => $this->getRows(),
1681 ) + $this->getTooltipAndAccessKey();
1682
1683 if ( $this->mClass !== '' ) {
1684 $attribs['class'] = $this->mClass;
1685 }
1686
1687 if ( !empty( $this->mParams['disabled'] ) ) {
1688 $attribs['disabled'] = 'disabled';
1689 }
1690
1691 if ( !empty( $this->mParams['readonly'] ) ) {
1692 $attribs['readonly'] = 'readonly';
1693 }
1694
1695 if ( isset( $this->mParams['placeholder'] ) ) {
1696 $attribs['placeholder'] = $this->mParams['placeholder'];
1697 }
1698
1699 foreach ( array( 'required', 'autofocus' ) as $param ) {
1700 if ( isset( $this->mParams[$param] ) ) {
1701 $attribs[$param] = '';
1702 }
1703 }
1704
1705 return Html::element( 'textarea', $attribs, $value );
1706 }
1707 }
1708
1709 /**
1710 * A field that will contain a numeric value
1711 */
1712 class HTMLFloatField extends HTMLTextField {
1713 function getSize() {
1714 return isset( $this->mParams['size'] )
1715 ? $this->mParams['size']
1716 : 20;
1717 }
1718
1719 function validate( $value, $alldata ) {
1720 $p = parent::validate( $value, $alldata );
1721
1722 if ( $p !== true ) {
1723 return $p;
1724 }
1725
1726 $value = trim( $value );
1727
1728 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1729 # with the addition that a leading '+' sign is ok.
1730 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1731 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1732 }
1733
1734 # The "int" part of these message names is rather confusing.
1735 # They make equal sense for all numbers.
1736 if ( isset( $this->mParams['min'] ) ) {
1737 $min = $this->mParams['min'];
1738
1739 if ( $min > $value ) {
1740 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1741 }
1742 }
1743
1744 if ( isset( $this->mParams['max'] ) ) {
1745 $max = $this->mParams['max'];
1746
1747 if ( $max < $value ) {
1748 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1749 }
1750 }
1751
1752 return true;
1753 }
1754 }
1755
1756 /**
1757 * A field that must contain a number
1758 */
1759 class HTMLIntField extends HTMLFloatField {
1760 function validate( $value, $alldata ) {
1761 $p = parent::validate( $value, $alldata );
1762
1763 if ( $p !== true ) {
1764 return $p;
1765 }
1766
1767 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1768 # with the addition that a leading '+' sign is ok. Note that leading zeros
1769 # are fine, and will be left in the input, which is useful for things like
1770 # phone numbers when you know that they are integers (the HTML5 type=tel
1771 # input does not require its value to be numeric). If you want a tidier
1772 # value to, eg, save in the DB, clean it up with intval().
1773 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1774 ) {
1775 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1776 }
1777
1778 return true;
1779 }
1780 }
1781
1782 /**
1783 * A checkbox field
1784 */
1785 class HTMLCheckField extends HTMLFormField {
1786 function getInputHTML( $value ) {
1787 if ( !empty( $this->mParams['invert'] ) ) {
1788 $value = !$value;
1789 }
1790
1791 $attr = $this->getTooltipAndAccessKey();
1792 $attr['id'] = $this->mID;
1793
1794 if ( !empty( $this->mParams['disabled'] ) ) {
1795 $attr['disabled'] = 'disabled';
1796 }
1797
1798 if ( $this->mClass !== '' ) {
1799 $attr['class'] = $this->mClass;
1800 }
1801
1802 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1803 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1804 }
1805
1806 /**
1807 * For a checkbox, the label goes on the right hand side, and is
1808 * added in getInputHTML(), rather than HTMLFormField::getRow()
1809 * @return String
1810 */
1811 function getLabel() {
1812 return '&#160;';
1813 }
1814
1815 /**
1816 * @param $request WebRequest
1817 * @return String
1818 */
1819 function loadDataFromRequest( $request ) {
1820 $invert = false;
1821 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1822 $invert = true;
1823 }
1824
1825 // GetCheck won't work like we want for checks.
1826 // Fetch the value in either one of the two following case:
1827 // - we have a valid token (form got posted or GET forged by the user)
1828 // - checkbox name has a value (false or true), ie is not null
1829 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1830 // XOR has the following truth table, which is what we want
1831 // INVERT VALUE | OUTPUT
1832 // true true | false
1833 // false true | true
1834 // false false | false
1835 // true false | true
1836 return $request->getBool( $this->mName ) xor $invert;
1837 } else {
1838 return $this->getDefault();
1839 }
1840 }
1841 }
1842
1843 /**
1844 * A checkbox matrix
1845 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1846 * options, uses an array of rows and an array of columns to dynamically
1847 * construct a matrix of options. The tags used to identify a particular cell
1848 * are of the form "columnName-rowName"
1849 *
1850 * Options:
1851 * columns: Required list of columns in the matrix.
1852 * rows: Required list of rows in the matrix.
1853 * force-options-on: Accepts array of column-row tags to be displayed as enabled
1854 * but unavailable to change
1855 * force-options-off: Accepts array of column-row tags to be displayed as disabled
1856 * but unavailable to change.
1857 */
1858 class HTMLCheckMatrix extends HTMLFormField implements HTMLNestedFilterable {
1859
1860 static private $requiredParams = array(
1861 // Required by underlying HTMLFormField
1862 'fieldname',
1863 // Required by HTMLCheckMatrix
1864 'rows', 'columns'
1865 );
1866
1867 public function __construct( $params ) {
1868 $missing = array_diff( self::$requiredParams, array_keys( $params ) );
1869 if ( $missing ) {
1870 throw HTMLFormFieldRequiredOptionsException::create( $this, $missing );
1871 }
1872 parent::__construct( $params );
1873 }
1874
1875 function validate( $value, $alldata ) {
1876 $rows = $this->mParams['rows'];
1877 $columns = $this->mParams['columns'];
1878
1879 // Make sure user-defined validation callback is run
1880 $p = parent::validate( $value, $alldata );
1881 if ( $p !== true ) {
1882 return $p;
1883 }
1884
1885 // Make sure submitted value is an array
1886 if ( !is_array( $value ) ) {
1887 return false;
1888 }
1889
1890 // If all options are valid, array_intersect of the valid options
1891 // and the provided options will return the provided options.
1892 $validOptions = array();
1893 foreach ( $rows as $rowTag ) {
1894 foreach ( $columns as $columnTag ) {
1895 $validOptions[] = $columnTag . '-' . $rowTag;
1896 }
1897 }
1898 $validValues = array_intersect( $value, $validOptions );
1899 if ( count( $validValues ) == count( $value ) ) {
1900 return true;
1901 } else {
1902 return $this->msg( 'htmlform-select-badoption' )->parse();
1903 }
1904 }
1905
1906 /**
1907 * Build a table containing a matrix of checkbox options.
1908 * The value of each option is a combination of the row tag and column tag.
1909 * mParams['rows'] is an array with row labels as keys and row tags as values.
1910 * mParams['columns'] is an array with column labels as keys and column tags as values.
1911 * @param array $value of the options that should be checked
1912 * @return String
1913 */
1914 function getInputHTML( $value ) {
1915 $html = '';
1916 $tableContents = '';
1917 $attribs = array();
1918 $rows = $this->mParams['rows'];
1919 $columns = $this->mParams['columns'];
1920
1921 // If the disabled param is set, disable all the options
1922 if ( !empty( $this->mParams['disabled'] ) ) {
1923 $attribs['disabled'] = 'disabled';
1924 }
1925
1926 // Build the column headers
1927 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
1928 foreach ( $columns as $columnLabel => $columnTag ) {
1929 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
1930 }
1931 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
1932
1933 // Build the options matrix
1934 foreach ( $rows as $rowLabel => $rowTag ) {
1935 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
1936 foreach ( $columns as $columnTag ) {
1937 $thisTag = "$columnTag-$rowTag";
1938 // Construct the checkbox
1939 $thisAttribs = array(
1940 'id' => "{$this->mID}-$thisTag",
1941 'value' => $thisTag,
1942 );
1943 $checked = in_array( $thisTag, (array)$value, true );
1944 if ( $this->isTagForcedOff( $thisTag ) ) {
1945 $checked = false;
1946 $thisAttribs['disabled'] = 1;
1947 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
1948 $checked = true;
1949 $thisAttribs['disabled'] = 1;
1950 }
1951 $rowContents .= Html::rawElement(
1952 'td',
1953 array(),
1954 Xml::check( "{$this->mName}[]", $checked, $attribs + $thisAttribs )
1955 );
1956 }
1957 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
1958 }
1959
1960 // Put it all in a table
1961 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
1962 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
1963
1964 return $html;
1965 }
1966
1967 protected function isTagForcedOff( $tag ) {
1968 return isset( $this->mParams['force-options-off'] )
1969 && in_array( $tag, $this->mParams['force-options-off'] );
1970 }
1971
1972 protected function isTagForcedOn( $tag ) {
1973 return isset( $this->mParams['force-options-on'] )
1974 && in_array( $tag, $this->mParams['force-options-on'] );
1975 }
1976
1977 /**
1978 * Get the complete table row for the input, including help text,
1979 * labels, and whatever.
1980 * We override this function since the label should always be on a separate
1981 * line above the options in the case of a checkbox matrix, i.e. it's always
1982 * a "vertical-label".
1983 * @param string $value the value to set the input to
1984 * @return String complete HTML table row
1985 */
1986 function getTableRow( $value ) {
1987 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1988 $inputHtml = $this->getInputHTML( $value );
1989 $fieldType = get_class( $this );
1990 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1991 $cellAttributes = array( 'colspan' => 2 );
1992
1993 $label = $this->getLabelHtml( $cellAttributes );
1994
1995 $field = Html::rawElement(
1996 'td',
1997 array( 'class' => 'mw-input' ) + $cellAttributes,
1998 $inputHtml . "\n$errors"
1999 );
2000
2001 $html = Html::rawElement( 'tr',
2002 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
2003 $html .= Html::rawElement( 'tr',
2004 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
2005 $field );
2006
2007 return $html . $helptext;
2008 }
2009
2010 /**
2011 * @param $request WebRequest
2012 * @return Array
2013 */
2014 function loadDataFromRequest( $request ) {
2015 if ( $this->mParent->getMethod() == 'post' ) {
2016 if ( $request->wasPosted() ) {
2017 // Checkboxes are not added to the request arrays if they're not checked,
2018 // so it's perfectly possible for there not to be an entry at all
2019 return $request->getArray( $this->mName, array() );
2020 } else {
2021 // That's ok, the user has not yet submitted the form, so show the defaults
2022 return $this->getDefault();
2023 }
2024 } else {
2025 // This is the impossible case: if we look at $_GET and see no data for our
2026 // field, is it because the user has not yet submitted the form, or that they
2027 // have submitted it with all the options unchecked. We will have to assume the
2028 // latter, which basically means that you can't specify 'positive' defaults
2029 // for GET forms.
2030 return $request->getArray( $this->mName, array() );
2031 }
2032 }
2033
2034 function getDefault() {
2035 if ( isset( $this->mDefault ) ) {
2036 return $this->mDefault;
2037 } else {
2038 return array();
2039 }
2040 }
2041
2042 function filterDataForSubmit( $data ) {
2043 $columns = HTMLFormField::flattenOptions( $this->mParams['columns'] );
2044 $rows = HTMLFormField::flattenOptions( $this->mParams['rows'] );
2045 $res = array();
2046 foreach ( $columns as $column ) {
2047 foreach ( $rows as $row ) {
2048 // Make sure option hasn't been forced
2049 $thisTag = "$column-$row";
2050 if ( $this->isTagForcedOff( $thisTag ) ) {
2051 $res[$thisTag] = false;
2052 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2053 $res[$thisTag] = true;
2054 } else {
2055 $res[$thisTag] = in_array( $thisTag, $data );
2056 }
2057 }
2058 }
2059
2060 return $res;
2061 }
2062 }
2063
2064 /**
2065 * A select dropdown field. Basically a wrapper for Xmlselect class
2066 */
2067 class HTMLSelectField extends HTMLFormField {
2068 function validate( $value, $alldata ) {
2069 $p = parent::validate( $value, $alldata );
2070
2071 if ( $p !== true ) {
2072 return $p;
2073 }
2074
2075 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2076
2077 if ( in_array( $value, $validOptions ) ) {
2078 return true;
2079 } else {
2080 return $this->msg( 'htmlform-select-badoption' )->parse();
2081 }
2082 }
2083
2084 function getInputHTML( $value ) {
2085 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
2086
2087 # If one of the options' 'name' is int(0), it is automatically selected.
2088 # because PHP sucks and thinks int(0) == 'some string'.
2089 # Working around this by forcing all of them to strings.
2090 foreach ( $this->mParams['options'] as &$opt ) {
2091 if ( is_int( $opt ) ) {
2092 $opt = strval( $opt );
2093 }
2094 }
2095 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2096
2097 if ( !empty( $this->mParams['disabled'] ) ) {
2098 $select->setAttribute( 'disabled', 'disabled' );
2099 }
2100
2101 if ( $this->mClass !== '' ) {
2102 $select->setAttribute( 'class', $this->mClass );
2103 }
2104
2105 $select->addOptions( $this->mParams['options'] );
2106
2107 return $select->getHTML();
2108 }
2109 }
2110
2111 /**
2112 * Select dropdown field, with an additional "other" textbox.
2113 */
2114 class HTMLSelectOrOtherField extends HTMLTextField {
2115
2116 function __construct( $params ) {
2117 if ( !in_array( 'other', $params['options'], true ) ) {
2118 $msg = isset( $params['other'] ) ?
2119 $params['other'] :
2120 wfMessage( 'htmlform-selectorother-other' )->text();
2121 $params['options'][$msg] = 'other';
2122 }
2123
2124 parent::__construct( $params );
2125 }
2126
2127 static function forceToStringRecursive( $array ) {
2128 if ( is_array( $array ) ) {
2129 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2130 } else {
2131 return strval( $array );
2132 }
2133 }
2134
2135 function getInputHTML( $value ) {
2136 $valInSelect = false;
2137
2138 if ( $value !== false ) {
2139 $valInSelect = in_array(
2140 $value,
2141 HTMLFormField::flattenOptions( $this->mParams['options'] )
2142 );
2143 }
2144
2145 $selected = $valInSelect ? $value : 'other';
2146
2147 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2148
2149 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2150 $select->addOptions( $opts );
2151
2152 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2153
2154 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2155
2156 if ( !empty( $this->mParams['disabled'] ) ) {
2157 $select->setAttribute( 'disabled', 'disabled' );
2158 $tbAttribs['disabled'] = 'disabled';
2159 }
2160
2161 $select = $select->getHTML();
2162
2163 if ( isset( $this->mParams['maxlength'] ) ) {
2164 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2165 }
2166
2167 if ( $this->mClass !== '' ) {
2168 $tbAttribs['class'] = $this->mClass;
2169 }
2170
2171 $textbox = Html::input(
2172 $this->mName . '-other',
2173 $valInSelect ? '' : $value,
2174 'text',
2175 $tbAttribs
2176 );
2177
2178 return "$select<br />\n$textbox";
2179 }
2180
2181 /**
2182 * @param $request WebRequest
2183 * @return String
2184 */
2185 function loadDataFromRequest( $request ) {
2186 if ( $request->getCheck( $this->mName ) ) {
2187 $val = $request->getText( $this->mName );
2188
2189 if ( $val == 'other' ) {
2190 $val = $request->getText( $this->mName . '-other' );
2191 }
2192
2193 return $val;
2194 } else {
2195 return $this->getDefault();
2196 }
2197 }
2198 }
2199
2200 /**
2201 * Multi-select field
2202 */
2203 class HTMLMultiSelectField extends HTMLFormField implements HTMLNestedFilterable {
2204
2205 function validate( $value, $alldata ) {
2206 $p = parent::validate( $value, $alldata );
2207
2208 if ( $p !== true ) {
2209 return $p;
2210 }
2211
2212 if ( !is_array( $value ) ) {
2213 return false;
2214 }
2215
2216 # If all options are valid, array_intersect of the valid options
2217 # and the provided options will return the provided options.
2218 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2219
2220 $validValues = array_intersect( $value, $validOptions );
2221 if ( count( $validValues ) == count( $value ) ) {
2222 return true;
2223 } else {
2224 return $this->msg( 'htmlform-select-badoption' )->parse();
2225 }
2226 }
2227
2228 function getInputHTML( $value ) {
2229 $html = $this->formatOptions( $this->mParams['options'], $value );
2230
2231 return $html;
2232 }
2233
2234 function formatOptions( $options, $value ) {
2235 $html = '';
2236
2237 $attribs = array();
2238
2239 if ( !empty( $this->mParams['disabled'] ) ) {
2240 $attribs['disabled'] = 'disabled';
2241 }
2242
2243 foreach ( $options as $label => $info ) {
2244 if ( is_array( $info ) ) {
2245 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2246 $html .= $this->formatOptions( $info, $value );
2247 } else {
2248 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2249
2250 $checkbox = Xml::check(
2251 $this->mName . '[]',
2252 in_array( $info, $value, true ),
2253 $attribs + $thisAttribs );
2254 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2255
2256 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2257 }
2258 }
2259
2260 return $html;
2261 }
2262
2263 /**
2264 * @param $request WebRequest
2265 * @return String
2266 */
2267 function loadDataFromRequest( $request ) {
2268 if ( $this->mParent->getMethod() == 'post' ) {
2269 if ( $request->wasPosted() ) {
2270 # Checkboxes are just not added to the request arrays if they're not checked,
2271 # so it's perfectly possible for there not to be an entry at all
2272 return $request->getArray( $this->mName, array() );
2273 } else {
2274 # That's ok, the user has not yet submitted the form, so show the defaults
2275 return $this->getDefault();
2276 }
2277 } else {
2278 # This is the impossible case: if we look at $_GET and see no data for our
2279 # field, is it because the user has not yet submitted the form, or that they
2280 # have submitted it with all the options unchecked? We will have to assume the
2281 # latter, which basically means that you can't specify 'positive' defaults
2282 # for GET forms.
2283 # @todo FIXME...
2284 return $request->getArray( $this->mName, array() );
2285 }
2286 }
2287
2288 function getDefault() {
2289 if ( isset( $this->mDefault ) ) {
2290 return $this->mDefault;
2291 } else {
2292 return array();
2293 }
2294 }
2295
2296 function filterDataForSubmit( $data ) {
2297 $options = HTMLFormField::flattenOptions( $this->mParams['options'] );
2298
2299 $res = array();
2300 foreach ( $options as $opt ) {
2301 $res["$opt"] = in_array( $opt, $data );
2302 }
2303
2304 return $res;
2305 }
2306
2307 protected function needsLabel() {
2308 return false;
2309 }
2310 }
2311
2312 /**
2313 * Double field with a dropdown list constructed from a system message in the format
2314 * * Optgroup header
2315 * ** <option value>
2316 * * New Optgroup header
2317 * Plus a text field underneath for an additional reason. The 'value' of the field is
2318 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2319 * select dropdown.
2320 * @todo FIXME: If made 'required', only the text field should be compulsory.
2321 */
2322 class HTMLSelectAndOtherField extends HTMLSelectField {
2323
2324 function __construct( $params ) {
2325 if ( array_key_exists( 'other', $params ) ) {
2326 } elseif ( array_key_exists( 'other-message', $params ) ) {
2327 $params['other'] = wfMessage( $params['other-message'] )->plain();
2328 } else {
2329 $params['other'] = null;
2330 }
2331
2332 if ( array_key_exists( 'options', $params ) ) {
2333 # Options array already specified
2334 } elseif ( array_key_exists( 'options-message', $params ) ) {
2335 # Generate options array from a system message
2336 $params['options'] = self::parseMessage(
2337 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2338 $params['other']
2339 );
2340 } else {
2341 # Sulk
2342 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2343 }
2344 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2345
2346 parent::__construct( $params );
2347 }
2348
2349 /**
2350 * Build a drop-down box from a textual list.
2351 * @param string $string message text
2352 * @param string $otherName name of "other reason" option
2353 * @return Array
2354 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2355 */
2356 public static function parseMessage( $string, $otherName = null ) {
2357 if ( $otherName === null ) {
2358 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2359 }
2360
2361 $optgroup = false;
2362 $options = array( $otherName => 'other' );
2363
2364 foreach ( explode( "\n", $string ) as $option ) {
2365 $value = trim( $option );
2366 if ( $value == '' ) {
2367 continue;
2368 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2369 # A new group is starting...
2370 $value = trim( substr( $value, 1 ) );
2371 $optgroup = $value;
2372 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2373 # groupmember
2374 $opt = trim( substr( $value, 2 ) );
2375 if ( $optgroup === false ) {
2376 $options[$opt] = $opt;
2377 } else {
2378 $options[$optgroup][$opt] = $opt;
2379 }
2380 } else {
2381 # groupless reason list
2382 $optgroup = false;
2383 $options[$option] = $option;
2384 }
2385 }
2386
2387 return $options;
2388 }
2389
2390 function getInputHTML( $value ) {
2391 $select = parent::getInputHTML( $value[1] );
2392
2393 $textAttribs = array(
2394 'id' => $this->mID . '-other',
2395 'size' => $this->getSize(),
2396 );
2397
2398 if ( $this->mClass !== '' ) {
2399 $textAttribs['class'] = $this->mClass;
2400 }
2401
2402 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2403 if ( isset( $this->mParams[$param] ) ) {
2404 $textAttribs[$param] = '';
2405 }
2406 }
2407
2408 $textbox = Html::input(
2409 $this->mName . '-other',
2410 $value[2],
2411 'text',
2412 $textAttribs
2413 );
2414
2415 return "$select<br />\n$textbox";
2416 }
2417
2418 /**
2419 * @param $request WebRequest
2420 * @return Array("<overall message>","<select value>","<text field value>")
2421 */
2422 function loadDataFromRequest( $request ) {
2423 if ( $request->getCheck( $this->mName ) ) {
2424
2425 $list = $request->getText( $this->mName );
2426 $text = $request->getText( $this->mName . '-other' );
2427
2428 if ( $list == 'other' ) {
2429 $final = $text;
2430 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2431 # User has spoofed the select form to give an option which wasn't
2432 # in the original offer. Sulk...
2433 $final = $text;
2434 } elseif ( $text == '' ) {
2435 $final = $list;
2436 } else {
2437 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2438 }
2439
2440 } else {
2441 $final = $this->getDefault();
2442
2443 $list = 'other';
2444 $text = $final;
2445 foreach ( $this->mFlatOptions as $option ) {
2446 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2447 if ( strpos( $text, $match ) === 0 ) {
2448 $list = $option;
2449 $text = substr( $text, strlen( $match ) );
2450 break;
2451 }
2452 }
2453 }
2454 return array( $final, $list, $text );
2455 }
2456
2457 function getSize() {
2458 return isset( $this->mParams['size'] )
2459 ? $this->mParams['size']
2460 : 45;
2461 }
2462
2463 function validate( $value, $alldata ) {
2464 # HTMLSelectField forces $value to be one of the options in the select
2465 # field, which is not useful here. But we do want the validation further up
2466 # the chain
2467 $p = parent::validate( $value[1], $alldata );
2468
2469 if ( $p !== true ) {
2470 return $p;
2471 }
2472
2473 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2474 return $this->msg( 'htmlform-required' )->parse();
2475 }
2476
2477 return true;
2478 }
2479 }
2480
2481 /**
2482 * Radio checkbox fields.
2483 */
2484 class HTMLRadioField extends HTMLFormField {
2485
2486 function validate( $value, $alldata ) {
2487 $p = parent::validate( $value, $alldata );
2488
2489 if ( $p !== true ) {
2490 return $p;
2491 }
2492
2493 if ( !is_string( $value ) && !is_int( $value ) ) {
2494 return false;
2495 }
2496
2497 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2498
2499 if ( in_array( $value, $validOptions ) ) {
2500 return true;
2501 } else {
2502 return $this->msg( 'htmlform-select-badoption' )->parse();
2503 }
2504 }
2505
2506 /**
2507 * This returns a block of all the radio options, in one cell.
2508 * @see includes/HTMLFormField#getInputHTML()
2509 * @param $value String
2510 * @return String
2511 */
2512 function getInputHTML( $value ) {
2513 $html = $this->formatOptions( $this->mParams['options'], $value );
2514
2515 return $html;
2516 }
2517
2518 function formatOptions( $options, $value ) {
2519 $html = '';
2520
2521 $attribs = array();
2522 if ( !empty( $this->mParams['disabled'] ) ) {
2523 $attribs['disabled'] = 'disabled';
2524 }
2525
2526 # TODO: should this produce an unordered list perhaps?
2527 foreach ( $options as $label => $info ) {
2528 if ( is_array( $info ) ) {
2529 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2530 $html .= $this->formatOptions( $info, $value );
2531 } else {
2532 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2533 $radio = Xml::radio(
2534 $this->mName,
2535 $info,
2536 $info == $value,
2537 $attribs + array( 'id' => $id )
2538 );
2539 $radio .= '&#160;' .
2540 Html::rawElement( 'label', array( 'for' => $id ), $label );
2541
2542 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2543 }
2544 }
2545
2546 return $html;
2547 }
2548
2549 protected function needsLabel() {
2550 return false;
2551 }
2552 }
2553
2554 /**
2555 * An information field (text blob), not a proper input.
2556 */
2557 class HTMLInfoField extends HTMLFormField {
2558 public function __construct( $info ) {
2559 $info['nodata'] = true;
2560
2561 parent::__construct( $info );
2562 }
2563
2564 public function getInputHTML( $value ) {
2565 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2566 }
2567
2568 public function getTableRow( $value ) {
2569 if ( !empty( $this->mParams['rawrow'] ) ) {
2570 return $value;
2571 }
2572
2573 return parent::getTableRow( $value );
2574 }
2575
2576 /**
2577 * @since 1.20
2578 */
2579 public function getDiv( $value ) {
2580 if ( !empty( $this->mParams['rawrow'] ) ) {
2581 return $value;
2582 }
2583
2584 return parent::getDiv( $value );
2585 }
2586
2587 /**
2588 * @since 1.20
2589 */
2590 public function getRaw( $value ) {
2591 if ( !empty( $this->mParams['rawrow'] ) ) {
2592 return $value;
2593 }
2594
2595 return parent::getRaw( $value );
2596 }
2597
2598 protected function needsLabel() {
2599 return false;
2600 }
2601 }
2602
2603 class HTMLHiddenField extends HTMLFormField {
2604 public function __construct( $params ) {
2605 parent::__construct( $params );
2606
2607 # Per HTML5 spec, hidden fields cannot be 'required'
2608 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2609 unset( $this->mParams['required'] );
2610 }
2611
2612 public function getTableRow( $value ) {
2613 $params = array();
2614 if ( $this->mID ) {
2615 $params['id'] = $this->mID;
2616 }
2617
2618 $this->mParent->addHiddenField(
2619 $this->mName,
2620 $this->mDefault,
2621 $params
2622 );
2623
2624 return '';
2625 }
2626
2627 /**
2628 * @since 1.20
2629 */
2630 public function getDiv( $value ) {
2631 return $this->getTableRow( $value );
2632 }
2633
2634 /**
2635 * @since 1.20
2636 */
2637 public function getRaw( $value ) {
2638 return $this->getTableRow( $value );
2639 }
2640
2641 public function getInputHTML( $value ) {
2642 return '';
2643 }
2644 }
2645
2646 /**
2647 * Add a submit button inline in the form (as opposed to
2648 * HTMLForm::addButton(), which will add it at the end).
2649 */
2650 class HTMLSubmitField extends HTMLButtonField {
2651 protected $buttonType = 'submit';
2652 }
2653
2654 /**
2655 * Adds a generic button inline to the form. Does not do anything, you must add
2656 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2657 * wish to add a submit button to a form.
2658 *
2659 * @since 1.22
2660 */
2661 class HTMLButtonField extends HTMLFormField {
2662 protected $buttonType = 'button';
2663
2664 public function __construct( $info ) {
2665 $info['nodata'] = true;
2666 parent::__construct( $info );
2667 }
2668
2669 public function getInputHTML( $value ) {
2670 $attr = array(
2671 'class' => 'mw-htmlform-submit ' . $this->mClass,
2672 'id' => $this->mID,
2673 );
2674
2675 if ( !empty( $this->mParams['disabled'] ) ) {
2676 $attr['disabled'] = 'disabled';
2677 }
2678
2679 return Html::input(
2680 $this->mName,
2681 $value,
2682 $this->buttonType,
2683 $attr
2684 );
2685 }
2686
2687 protected function needsLabel() {
2688 return false;
2689 }
2690
2691 /**
2692 * Button cannot be invalid
2693 * @param $value String
2694 * @param $alldata Array
2695 * @return Bool
2696 */
2697 public function validate( $value, $alldata ) {
2698 return true;
2699 }
2700 }
2701
2702 class HTMLEditTools extends HTMLFormField {
2703 public function getInputHTML( $value ) {
2704 return '';
2705 }
2706
2707 public function getTableRow( $value ) {
2708 $msg = $this->formatMsg();
2709
2710 return '<tr><td></td><td class="mw-input">'
2711 . '<div class="mw-editTools">'
2712 . $msg->parseAsBlock()
2713 . "</div></td></tr>\n";
2714 }
2715
2716 /**
2717 * @since 1.20
2718 */
2719 public function getDiv( $value ) {
2720 $msg = $this->formatMsg();
2721 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2722 }
2723
2724 /**
2725 * @since 1.20
2726 */
2727 public function getRaw( $value ) {
2728 return $this->getDiv( $value );
2729 }
2730
2731 protected function formatMsg() {
2732 if ( empty( $this->mParams['message'] ) ) {
2733 $msg = $this->msg( 'edittools' );
2734 } else {
2735 $msg = $this->msg( $this->mParams['message'] );
2736 if ( $msg->isDisabled() ) {
2737 $msg = $this->msg( 'edittools' );
2738 }
2739 }
2740 $msg->inContentLanguage();
2741 return $msg;
2742 }
2743 }
2744
2745 class HTMLApiField extends HTMLFormField {
2746 public function getTableRow( $value ) {
2747 return '';
2748 }
2749
2750 public function getDiv( $value ) {
2751 return $this->getTableRow( $value );
2752 }
2753
2754 public function getRaw( $value ) {
2755 return $this->getTableRow( $value );
2756 }
2757
2758 public function getInputHTML( $value ) {
2759 return '';
2760 }
2761 }
2762
2763 interface HTMLNestedFilterable {
2764 /**
2765 * Support for seperating multi-option preferences into multiple preferences
2766 * Due to lack of array support.
2767 * @param $data array
2768 */
2769 function filterDataForSubmit( $data );
2770 }
2771
2772 class HTMLFormFieldRequiredOptionsException extends MWException {
2773 static public function create( HTMLFormField $field, array $missing ) {
2774 return new self( sprintf(
2775 "Form type `%s` expected the following parameters to be set: %s",
2776 get_class( $field ),
2777 implode( ', ', $missing )
2778 ) );
2779 }
2780 }