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