Merge "ApiHelp: Make 'toc' parameter work"
[lhc/web/wiklou.git] / includes / htmlform / HTMLForm.php
1 <?php
2
3 /**
4 * HTML form generation and submission handling.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 */
23
24 /**
25 * Object handling generic submission, CSRF protection, layout and
26 * other logic for UI forms. in a reusable manner.
27 *
28 * In order to generate the form, the HTMLForm object takes an array
29 * structure detailing the form fields available. Each element of the
30 * array is a basic property-list, including the type of field, the
31 * label it is to be given in the form, callbacks for validation and
32 * 'filtering', and other pertinent information.
33 *
34 * Field types are implemented as subclasses of the generic HTMLFormField
35 * object, and typically implement at least getInputHTML, which generates
36 * the HTML for the input field to be placed in the table.
37 *
38 * You can find extensive documentation on the www.mediawiki.org wiki:
39 * - https://www.mediawiki.org/wiki/HTMLForm
40 * - https://www.mediawiki.org/wiki/HTMLForm/tutorial
41 *
42 * The constructor input is an associative array of $fieldname => $info,
43 * where $info is an Associative Array with any of the following:
44 *
45 * 'class' -- the subclass of HTMLFormField that will be used
46 * to create the object. *NOT* the CSS class!
47 * 'type' -- roughly translates into the <select> type attribute.
48 * if 'class' is not specified, this is used as a map
49 * through HTMLForm::$typeMappings to get the class name.
50 * 'default' -- default value when the form is displayed
51 * 'id' -- HTML id attribute
52 * 'cssclass' -- CSS class
53 * 'csshelpclass' -- CSS class used to style help text
54 * 'dir' -- Direction of the element.
55 * 'options' -- associative array mapping labels to values.
56 * Some field types support multi-level arrays.
57 * 'options-messages' -- associative array mapping message keys to values.
58 * Some field types support multi-level arrays.
59 * 'options-message' -- message key to be parsed to extract the list of
60 * options (like 'ipbreason-dropdown').
61 * 'label-message' -- message key for a message to use as the label.
62 * can be an array of msg key and then parameters to
63 * the message.
64 * 'label' -- alternatively, a raw text message. Overridden by
65 * label-message
66 * 'help' -- message text for a message to use as a help text.
67 * 'help-message' -- message key for a message to use as a help text.
68 * can be an array of msg key and then parameters to
69 * the message.
70 * Overwrites 'help-messages' and 'help'.
71 * 'help-messages' -- array of message key. As above, each item can
72 * be an array of msg key and then parameters.
73 * Overwrites 'help'.
74 * 'required' -- passed through to the object, indicating that it
75 * is a required field.
76 * 'size' -- the length of text fields
77 * 'filter-callback -- a function name to give you the chance to
78 * massage the inputted value before it's processed.
79 * @see HTMLForm::filter()
80 * 'validation-callback' -- a function name to give you the chance
81 * to impose extra validation on the field input.
82 * @see HTMLForm::validate()
83 * 'name' -- By default, the 'name' attribute of the input field
84 * is "wp{$fieldname}". If you want a different name
85 * (eg one without the "wp" prefix), specify it here and
86 * it will be used without modification.
87 *
88 * Since 1.20, you can chain mutators to ease the form generation:
89 * @par Example:
90 * @code
91 * $form = new HTMLForm( $someFields );
92 * $form->setMethod( 'get' )
93 * ->setWrapperLegendMsg( 'message-key' )
94 * ->prepareForm()
95 * ->displayForm( '' );
96 * @endcode
97 * Note that you will have prepareForm and displayForm at the end. Other
98 * methods call done after that would simply not be part of the form :(
99 *
100 * @todo Document 'section' / 'subsection' stuff
101 */
102 class HTMLForm extends ContextSource {
103 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
104 public static $typeMappings = array(
105 'api' => 'HTMLApiField',
106 'text' => 'HTMLTextField',
107 'textarea' => 'HTMLTextAreaField',
108 'select' => 'HTMLSelectField',
109 'radio' => 'HTMLRadioField',
110 'multiselect' => 'HTMLMultiSelectField',
111 'limitselect' => 'HTMLSelectLimitField',
112 'check' => 'HTMLCheckField',
113 'toggle' => 'HTMLCheckField',
114 'int' => 'HTMLIntField',
115 'float' => 'HTMLFloatField',
116 'info' => 'HTMLInfoField',
117 'selectorother' => 'HTMLSelectOrOtherField',
118 'selectandother' => 'HTMLSelectAndOtherField',
119 'namespaceselect' => 'HTMLSelectNamespace',
120 'tagfilter' => 'HTMLTagFilter',
121 'submit' => 'HTMLSubmitField',
122 'hidden' => 'HTMLHiddenField',
123 'edittools' => 'HTMLEditTools',
124 'checkmatrix' => 'HTMLCheckMatrix',
125 'cloner' => 'HTMLFormFieldCloner',
126 'autocompleteselect' => 'HTMLAutoCompleteSelectField',
127 // HTMLTextField will output the correct type="" attribute automagically.
128 // There are about four zillion other HTML5 input types, like range, but
129 // we don't use those at the moment, so no point in adding all of them.
130 'email' => 'HTMLTextField',
131 'password' => 'HTMLTextField',
132 'url' => 'HTMLTextField',
133 );
134
135 public $mFieldData;
136
137 protected $mMessagePrefix;
138
139 /** @var HTMLFormField[] */
140 protected $mFlatFields;
141
142 protected $mFieldTree;
143 protected $mShowReset = false;
144 protected $mShowSubmit = true;
145 protected $mSubmitModifierClass = 'mw-ui-constructive';
146
147 protected $mSubmitCallback;
148 protected $mValidationErrorMessage;
149
150 protected $mPre = '';
151 protected $mHeader = '';
152 protected $mFooter = '';
153 protected $mSectionHeaders = array();
154 protected $mSectionFooters = array();
155 protected $mPost = '';
156 protected $mId;
157 protected $mTableId = '';
158
159 protected $mSubmitID;
160 protected $mSubmitName;
161 protected $mSubmitText;
162 protected $mSubmitTooltip;
163
164 protected $mTitle;
165 protected $mMethod = 'post';
166 protected $mWasSubmitted = false;
167
168 /**
169 * Form action URL. false means we will use the URL to set Title
170 * @since 1.19
171 * @var bool|string
172 */
173 protected $mAction = false;
174
175 protected $mUseMultipart = false;
176 protected $mHiddenFields = array();
177 protected $mButtons = array();
178
179 protected $mWrapperLegend = false;
180
181 /**
182 * Salt for the edit token.
183 * @var string|array
184 */
185 protected $mTokenSalt = '';
186
187 /**
188 * If true, sections that contain both fields and subsections will
189 * render their subsections before their fields.
190 *
191 * Subclasses may set this to false to render subsections after fields
192 * instead.
193 */
194 protected $mSubSectionBeforeFields = true;
195
196 /**
197 * Format in which to display form. For viable options,
198 * @see $availableDisplayFormats
199 * @var string
200 */
201 protected $displayFormat = 'table';
202
203 /**
204 * Available formats in which to display the form
205 * @var array
206 */
207 protected $availableDisplayFormats = array(
208 'table',
209 'div',
210 'raw',
211 'inline',
212 );
213
214 /**
215 * Available formats in which to display the form
216 * @var array
217 */
218 protected $availableSubclassDisplayFormats = array(
219 'vform',
220 );
221
222 /**
223 * Construct a HTMLForm object for given display type. May return a HTMLForm subclass.
224 *
225 * @throws MWException When the display format requested is not known
226 * @param string $displayFormat
227 * @param mixed $arguments... Additional arguments to pass to the constructor.
228 * @return HTMLForm
229 */
230 public static function factory( $displayFormat/*, $arguments...*/ ) {
231 $arguments = func_get_args();
232 array_shift( $arguments );
233
234 switch ( $displayFormat ) {
235 case 'vform':
236 $reflector = new ReflectionClass( 'VFormHTMLForm' );
237 return $reflector->newInstanceArgs( $arguments );
238 default:
239 $reflector = new ReflectionClass( 'HTMLForm' );
240 $form = $reflector->newInstanceArgs( $arguments );
241 $form->setDisplayFormat( $displayFormat );
242 return $form;
243 }
244 }
245
246 /**
247 * Build a new HTMLForm from an array of field attributes
248 *
249 * @param array $descriptor Array of Field constructs, as described above
250 * @param IContextSource $context Available since 1.18, will become compulsory in 1.18.
251 * Obviates the need to call $form->setTitle()
252 * @param string $messagePrefix A prefix to go in front of default messages
253 */
254 public function __construct( $descriptor, /*IContextSource*/ $context = null,
255 $messagePrefix = ''
256 ) {
257 if ( $context instanceof IContextSource ) {
258 $this->setContext( $context );
259 $this->mTitle = false; // We don't need them to set a title
260 $this->mMessagePrefix = $messagePrefix;
261 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
262 $this->mMessagePrefix = $messagePrefix;
263 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
264 // B/C since 1.18
265 // it's actually $messagePrefix
266 $this->mMessagePrefix = $context;
267 }
268
269 // Evil hack for mobile :(
270 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $this->displayFormat === 'table' ) {
271 $this->displayFormat = 'div';
272 }
273
274 // Expand out into a tree.
275 $loadedDescriptor = array();
276 $this->mFlatFields = array();
277
278 foreach ( $descriptor as $fieldname => $info ) {
279 $section = isset( $info['section'] )
280 ? $info['section']
281 : '';
282
283 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
284 $this->mUseMultipart = true;
285 }
286
287 $field = static::loadInputFromParameters( $fieldname, $info, $this );
288
289 $setSection =& $loadedDescriptor;
290 if ( $section ) {
291 $sectionParts = explode( '/', $section );
292
293 while ( count( $sectionParts ) ) {
294 $newName = array_shift( $sectionParts );
295
296 if ( !isset( $setSection[$newName] ) ) {
297 $setSection[$newName] = array();
298 }
299
300 $setSection =& $setSection[$newName];
301 }
302 }
303
304 $setSection[$fieldname] = $field;
305 $this->mFlatFields[$fieldname] = $field;
306 }
307
308 $this->mFieldTree = $loadedDescriptor;
309 }
310
311 /**
312 * Set format in which to display the form
313 *
314 * @param string $format The name of the format to use, must be one of
315 * $this->availableDisplayFormats
316 *
317 * @throws MWException
318 * @since 1.20
319 * @return HTMLForm $this for chaining calls (since 1.20)
320 */
321 public function setDisplayFormat( $format ) {
322 if (
323 in_array( $format, $this->availableSubclassDisplayFormats ) ||
324 in_array( $this->displayFormat, $this->availableSubclassDisplayFormats )
325 ) {
326 throw new MWException( 'Cannot change display format after creation, ' .
327 'use HTMLForm::factory() instead' );
328 }
329
330 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
331 throw new MWException( 'Display format must be one of ' .
332 print_r( $this->availableDisplayFormats, true ) );
333 }
334
335 // Evil hack for mobile :(
336 if ( !$this->getConfig()->get( 'HTMLFormAllowTableFormat' ) && $format === 'table' ) {
337 $format = 'div';
338 }
339
340 $this->displayFormat = $format;
341
342 return $this;
343 }
344
345 /**
346 * Getter for displayFormat
347 * @since 1.20
348 * @return string
349 */
350 public function getDisplayFormat() {
351 return $this->displayFormat;
352 }
353
354 /**
355 * Test if displayFormat is 'vform'
356 * @since 1.22
357 * @deprecated since 1.25
358 * @return bool
359 */
360 public function isVForm() {
361 wfDeprecated( __METHOD__, '1.25' );
362 return false;
363 }
364
365 /**
366 * Get the HTMLFormField subclass for this descriptor.
367 *
368 * The descriptor can be passed either 'class' which is the name of
369 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
370 * This makes sure the 'class' is always set, and also is returned by
371 * this function for ease.
372 *
373 * @since 1.23
374 *
375 * @param string $fieldname Name of the field
376 * @param array $descriptor Input Descriptor, as described above
377 *
378 * @throws MWException
379 * @return string Name of a HTMLFormField subclass
380 */
381 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
382 if ( isset( $descriptor['class'] ) ) {
383 $class = $descriptor['class'];
384 } elseif ( isset( $descriptor['type'] ) ) {
385 $class = static::$typeMappings[$descriptor['type']];
386 $descriptor['class'] = $class;
387 } else {
388 $class = null;
389 }
390
391 if ( !$class ) {
392 throw new MWException( "Descriptor with no class for $fieldname: "
393 . print_r( $descriptor, true ) );
394 }
395
396 return $class;
397 }
398
399 /**
400 * Initialise a new Object for the field
401 *
402 * @param string $fieldname Name of the field
403 * @param array $descriptor Input Descriptor, as described above
404 * @param HTMLForm|null $parent Parent instance of HTMLForm
405 *
406 * @throws MWException
407 * @return HTMLFormField Instance of a subclass of HTMLFormField
408 */
409 public static function loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent = null ) {
410 $class = static::getClassFromDescriptor( $fieldname, $descriptor );
411
412 $descriptor['fieldname'] = $fieldname;
413 if ( $parent ) {
414 $descriptor['parent'] = $parent;
415 }
416
417 # @todo This will throw a fatal error whenever someone try to use
418 # 'class' to feed a CSS class instead of 'cssclass'. Would be
419 # great to avoid the fatal error and show a nice error.
420 $obj = new $class( $descriptor );
421
422 return $obj;
423 }
424
425 /**
426 * Prepare form for submission.
427 *
428 * @attention When doing method chaining, that should be the very last
429 * method call before displayForm().
430 *
431 * @throws MWException
432 * @return HTMLForm $this for chaining calls (since 1.20)
433 */
434 function prepareForm() {
435 # Check if we have the info we need
436 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
437 throw new MWException( "You must call setTitle() on an HTMLForm" );
438 }
439
440 # Load data from the request.
441 $this->loadData();
442
443 return $this;
444 }
445
446 /**
447 * Try submitting, with edit token check first
448 * @return Status|bool
449 */
450 function tryAuthorizedSubmit() {
451 $result = false;
452
453 $submit = false;
454 if ( $this->getMethod() != 'post' ) {
455 $submit = true; // no session check needed
456 } elseif ( $this->getRequest()->wasPosted() ) {
457 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
458 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
459 // Session tokens for logged-out users have no security value.
460 // However, if the user gave one, check it in order to give a nice
461 // "session expired" error instead of "permission denied" or such.
462 $submit = $this->getUser()->matchEditToken( $editToken, $this->mTokenSalt );
463 } else {
464 $submit = true;
465 }
466 }
467
468 if ( $submit ) {
469 $this->mWasSubmitted = true;
470 $result = $this->trySubmit();
471 }
472
473 return $result;
474 }
475
476 /**
477 * The here's-one-I-made-earlier option: do the submission if
478 * posted, or display the form with or without funky validation
479 * errors
480 * @return bool|Status Whether submission was successful.
481 */
482 function show() {
483 $this->prepareForm();
484
485 $result = $this->tryAuthorizedSubmit();
486 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
487 return $result;
488 }
489
490 $this->displayForm( $result );
491
492 return false;
493 }
494
495 /**
496 * Validate all the fields, and call the submission callback
497 * function if everything is kosher.
498 * @throws MWException
499 * @return bool|string|array|Status
500 * - Bool true or a good Status object indicates success,
501 * - Bool false indicates no submission was attempted,
502 * - Anything else indicates failure. The value may be a fatal Status
503 * object, an HTML string, or an array of arrays (message keys and
504 * params) or strings (message keys)
505 */
506 function trySubmit() {
507 $this->mWasSubmitted = true;
508
509 # Check for cancelled submission
510 foreach ( $this->mFlatFields as $fieldname => $field ) {
511 if ( !empty( $field->mParams['nodata'] ) ) {
512 continue;
513 }
514 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
515 $this->mWasSubmitted = false;
516 return false;
517 }
518 }
519
520 # Check for validation
521 foreach ( $this->mFlatFields as $fieldname => $field ) {
522 if ( !empty( $field->mParams['nodata'] ) ) {
523 continue;
524 }
525 if ( $field->isHidden( $this->mFieldData ) ) {
526 continue;
527 }
528 if ( $field->validate(
529 $this->mFieldData[$fieldname],
530 $this->mFieldData )
531 !== true
532 ) {
533 return isset( $this->mValidationErrorMessage )
534 ? $this->mValidationErrorMessage
535 : array( 'htmlform-invalid-input' );
536 }
537 }
538
539 $callback = $this->mSubmitCallback;
540 if ( !is_callable( $callback ) ) {
541 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
542 'setSubmitCallback() to set one.' );
543 }
544
545 $data = $this->filterDataForSubmit( $this->mFieldData );
546
547 $res = call_user_func( $callback, $data, $this );
548 if ( $res === false ) {
549 $this->mWasSubmitted = false;
550 }
551
552 return $res;
553 }
554
555 /**
556 * Test whether the form was considered to have been submitted or not, i.e.
557 * whether the last call to tryAuthorizedSubmit or trySubmit returned
558 * non-false.
559 *
560 * This will return false until HTMLForm::tryAuthorizedSubmit or
561 * HTMLForm::trySubmit is called.
562 *
563 * @since 1.23
564 * @return bool
565 */
566 function wasSubmitted() {
567 return $this->mWasSubmitted;
568 }
569
570 /**
571 * Set a callback to a function to do something with the form
572 * once it's been successfully validated.
573 *
574 * @param callable $cb The function will be passed the output from
575 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
576 * return as documented for HTMLForm::trySubmit
577 *
578 * @return HTMLForm $this for chaining calls (since 1.20)
579 */
580 function setSubmitCallback( $cb ) {
581 $this->mSubmitCallback = $cb;
582
583 return $this;
584 }
585
586 /**
587 * Set a message to display on a validation error.
588 *
589 * @param string|array $msg String or Array of valid inputs to wfMessage()
590 * (so each entry can be either a String or Array)
591 *
592 * @return HTMLForm $this for chaining calls (since 1.20)
593 */
594 function setValidationErrorMessage( $msg ) {
595 $this->mValidationErrorMessage = $msg;
596
597 return $this;
598 }
599
600 /**
601 * Set the introductory message, overwriting any existing message.
602 *
603 * @param string $msg Complete text of message to display
604 *
605 * @return HTMLForm $this for chaining calls (since 1.20)
606 */
607 function setIntro( $msg ) {
608 $this->setPreText( $msg );
609
610 return $this;
611 }
612
613 /**
614 * Set the introductory message, overwriting any existing message.
615 * @since 1.19
616 *
617 * @param string $msg Complete text of message to display
618 *
619 * @return HTMLForm $this for chaining calls (since 1.20)
620 */
621 function setPreText( $msg ) {
622 $this->mPre = $msg;
623
624 return $this;
625 }
626
627 /**
628 * Add introductory text.
629 *
630 * @param string $msg Complete text of message to display
631 *
632 * @return HTMLForm $this for chaining calls (since 1.20)
633 */
634 function addPreText( $msg ) {
635 $this->mPre .= $msg;
636
637 return $this;
638 }
639
640 /**
641 * Add header text, inside the form.
642 *
643 * @param string $msg Complete text of message to display
644 * @param string|null $section The section to add the header to
645 *
646 * @return HTMLForm $this for chaining calls (since 1.20)
647 */
648 function addHeaderText( $msg, $section = null ) {
649 if ( is_null( $section ) ) {
650 $this->mHeader .= $msg;
651 } else {
652 if ( !isset( $this->mSectionHeaders[$section] ) ) {
653 $this->mSectionHeaders[$section] = '';
654 }
655 $this->mSectionHeaders[$section] .= $msg;
656 }
657
658 return $this;
659 }
660
661 /**
662 * Set header text, inside the form.
663 * @since 1.19
664 *
665 * @param string $msg Complete text of message to display
666 * @param string|null $section The section to add the header to
667 *
668 * @return HTMLForm $this for chaining calls (since 1.20)
669 */
670 function setHeaderText( $msg, $section = null ) {
671 if ( is_null( $section ) ) {
672 $this->mHeader = $msg;
673 } else {
674 $this->mSectionHeaders[$section] = $msg;
675 }
676
677 return $this;
678 }
679
680 /**
681 * Add footer text, inside the form.
682 *
683 * @param string $msg Complete text of message to display
684 * @param string|null $section The section to add the footer text to
685 *
686 * @return HTMLForm $this for chaining calls (since 1.20)
687 */
688 function addFooterText( $msg, $section = null ) {
689 if ( is_null( $section ) ) {
690 $this->mFooter .= $msg;
691 } else {
692 if ( !isset( $this->mSectionFooters[$section] ) ) {
693 $this->mSectionFooters[$section] = '';
694 }
695 $this->mSectionFooters[$section] .= $msg;
696 }
697
698 return $this;
699 }
700
701 /**
702 * Set footer text, inside the form.
703 * @since 1.19
704 *
705 * @param string $msg Complete text of message to display
706 * @param string|null $section The section to add the footer text to
707 *
708 * @return HTMLForm $this for chaining calls (since 1.20)
709 */
710 function setFooterText( $msg, $section = null ) {
711 if ( is_null( $section ) ) {
712 $this->mFooter = $msg;
713 } else {
714 $this->mSectionFooters[$section] = $msg;
715 }
716
717 return $this;
718 }
719
720 /**
721 * Add text to the end of the display.
722 *
723 * @param string $msg Complete text of message to display
724 *
725 * @return HTMLForm $this for chaining calls (since 1.20)
726 */
727 function addPostText( $msg ) {
728 $this->mPost .= $msg;
729
730 return $this;
731 }
732
733 /**
734 * Set text at the end of the display.
735 *
736 * @param string $msg Complete text of message to display
737 *
738 * @return HTMLForm $this for chaining calls (since 1.20)
739 */
740 function setPostText( $msg ) {
741 $this->mPost = $msg;
742
743 return $this;
744 }
745
746 /**
747 * Add a hidden field to the output
748 *
749 * @param string $name Field name. This will be used exactly as entered
750 * @param string $value Field value
751 * @param array $attribs
752 *
753 * @return HTMLForm $this for chaining calls (since 1.20)
754 */
755 public function addHiddenField( $name, $value, $attribs = array() ) {
756 $attribs += array( 'name' => $name );
757 $this->mHiddenFields[] = array( $value, $attribs );
758
759 return $this;
760 }
761
762 /**
763 * Add an array of hidden fields to the output
764 *
765 * @since 1.22
766 *
767 * @param array $fields Associative array of fields to add;
768 * mapping names to their values
769 *
770 * @return HTMLForm $this for chaining calls
771 */
772 public function addHiddenFields( array $fields ) {
773 foreach ( $fields as $name => $value ) {
774 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
775 }
776
777 return $this;
778 }
779
780 /**
781 * Add a button to the form
782 *
783 * @param string $name Field name.
784 * @param string $value Field value
785 * @param string $id DOM id for the button (default: null)
786 * @param array $attribs
787 *
788 * @return HTMLForm $this for chaining calls (since 1.20)
789 */
790 public function addButton( $name, $value, $id = null, $attribs = null ) {
791 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
792
793 return $this;
794 }
795
796 /**
797 * Set the salt for the edit token.
798 *
799 * Only useful when the method is "post".
800 *
801 * @since 1.24
802 * @param string|array $salt Salt to use
803 * @return HTMLForm $this For chaining calls
804 */
805 public function setTokenSalt( $salt ) {
806 $this->mTokenSalt = $salt;
807
808 return $this;
809 }
810
811 /**
812 * Display the form (sending to the context's OutputPage object), with an
813 * appropriate error message or stack of messages, and any validation errors, etc.
814 *
815 * @attention You should call prepareForm() before calling this function.
816 * Moreover, when doing method chaining this should be the very last method
817 * call just after prepareForm().
818 *
819 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
820 *
821 * @return void Nothing, should be last call
822 */
823 function displayForm( $submitResult ) {
824 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
825 }
826
827 /**
828 * Returns the raw HTML generated by the form
829 *
830 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
831 *
832 * @return string
833 */
834 function getHTML( $submitResult ) {
835 # For good measure (it is the default)
836 $this->getOutput()->preventClickjacking();
837 $this->getOutput()->addModules( 'mediawiki.htmlform' );
838
839 $html = ''
840 . $this->getErrors( $submitResult )
841 . $this->mHeader
842 . $this->getBody()
843 . $this->getHiddenFields()
844 . $this->getButtons()
845 . $this->mFooter;
846
847 $html = $this->wrapForm( $html );
848
849 return '' . $this->mPre . $html . $this->mPost;
850 }
851
852 /**
853 * Get HTML attributes for the `<form>` tag.
854 * @return array
855 */
856 protected function getFormAttributes() {
857 # Use multipart/form-data
858 $encType = $this->mUseMultipart
859 ? 'multipart/form-data'
860 : 'application/x-www-form-urlencoded';
861 # Attributes
862 $attribs = array(
863 'action' => $this->getAction(),
864 'method' => $this->getMethod(),
865 'class' => array( 'visualClear' ),
866 'enctype' => $encType,
867 );
868 if ( !empty( $this->mId ) ) {
869 $attribs['id'] = $this->mId;
870 }
871 return $attribs;
872 }
873
874 /**
875 * Wrap the form innards in an actual "<form>" element
876 *
877 * @param string $html HTML contents to wrap.
878 *
879 * @return string Wrapped HTML.
880 */
881 function wrapForm( $html ) {
882 # Include a <fieldset> wrapper for style, if requested.
883 if ( $this->mWrapperLegend !== false ) {
884 $html = Xml::fieldset( $this->mWrapperLegend, $html );
885 }
886
887 return Html::rawElement( 'form', $this->getFormAttributes(), $html );
888 }
889
890 /**
891 * Get the hidden fields that should go inside the form.
892 * @return string HTML.
893 */
894 function getHiddenFields() {
895 $html = '';
896 if ( $this->getMethod() == 'post' ) {
897 $html .= Html::hidden(
898 'wpEditToken',
899 $this->getUser()->getEditToken( $this->mTokenSalt ),
900 array( 'id' => 'wpEditToken' )
901 ) . "\n";
902 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
903 }
904
905 $articlePath = $this->getConfig()->get( 'ArticlePath' );
906 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
907 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
908 }
909
910 foreach ( $this->mHiddenFields as $data ) {
911 list( $value, $attribs ) = $data;
912 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
913 }
914
915 return $html;
916 }
917
918 /**
919 * Get the submit and (potentially) reset buttons.
920 * @return string HTML.
921 */
922 function getButtons() {
923 $buttons = '';
924 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
925
926 if ( $this->mShowSubmit ) {
927 $attribs = array();
928
929 if ( isset( $this->mSubmitID ) ) {
930 $attribs['id'] = $this->mSubmitID;
931 }
932
933 if ( isset( $this->mSubmitName ) ) {
934 $attribs['name'] = $this->mSubmitName;
935 }
936
937 if ( isset( $this->mSubmitTooltip ) ) {
938 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
939 }
940
941 $attribs['class'] = array( 'mw-htmlform-submit' );
942
943 if ( $useMediaWikiUIEverywhere ) {
944 array_push( $attribs['class'], 'mw-ui-button', $this->mSubmitModifierClass );
945 }
946
947 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
948 }
949
950 if ( $this->mShowReset ) {
951 $buttons .= Html::element(
952 'input',
953 array(
954 'type' => 'reset',
955 'value' => $this->msg( 'htmlform-reset' )->text(),
956 'class' => ( $useMediaWikiUIEverywhere ? 'mw-ui-button' : null ),
957 )
958 ) . "\n";
959 }
960
961 foreach ( $this->mButtons as $button ) {
962 $attrs = array(
963 'type' => 'submit',
964 'name' => $button['name'],
965 'value' => $button['value']
966 );
967
968 if ( $button['attribs'] ) {
969 $attrs += $button['attribs'];
970 }
971
972 if ( isset( $button['id'] ) ) {
973 $attrs['id'] = $button['id'];
974 }
975
976 if ( $useMediaWikiUIEverywhere ) {
977 $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : array();
978 $attrs['class'][] = 'mw-ui-button';
979 }
980
981 $buttons .= Html::element( 'input', $attrs ) . "\n";
982 }
983
984 $html = Html::rawElement( 'span',
985 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
986
987 return $html;
988 }
989
990 /**
991 * Get the whole body of the form.
992 * @return string
993 */
994 function getBody() {
995 return $this->displaySection( $this->mFieldTree, $this->mTableId );
996 }
997
998 /**
999 * Format and display an error message stack.
1000 *
1001 * @param string|array|Status $errors
1002 *
1003 * @return string
1004 */
1005 function getErrors( $errors ) {
1006 if ( $errors instanceof Status ) {
1007 if ( $errors->isOK() ) {
1008 $errorstr = '';
1009 } else {
1010 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1011 }
1012 } elseif ( is_array( $errors ) ) {
1013 $errorstr = $this->formatErrors( $errors );
1014 } else {
1015 $errorstr = $errors;
1016 }
1017
1018 return $errorstr
1019 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1020 : '';
1021 }
1022
1023 /**
1024 * Format a stack of error messages into a single HTML string
1025 *
1026 * @param array $errors Array of message keys/values
1027 *
1028 * @return string HTML, a "<ul>" list of errors
1029 */
1030 public function formatErrors( $errors ) {
1031 $errorstr = '';
1032
1033 foreach ( $errors as $error ) {
1034 if ( is_array( $error ) ) {
1035 $msg = array_shift( $error );
1036 } else {
1037 $msg = $error;
1038 $error = array();
1039 }
1040
1041 $errorstr .= Html::rawElement(
1042 'li',
1043 array(),
1044 $this->msg( $msg, $error )->parse()
1045 );
1046 }
1047
1048 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1049
1050 return $errorstr;
1051 }
1052
1053 /**
1054 * Set the text for the submit button
1055 *
1056 * @param string $t Plaintext
1057 *
1058 * @return HTMLForm $this for chaining calls (since 1.20)
1059 */
1060 function setSubmitText( $t ) {
1061 $this->mSubmitText = $t;
1062
1063 return $this;
1064 }
1065
1066 /**
1067 * Identify that the submit button in the form has a destructive action
1068 * @since 1.24
1069 */
1070 public function setSubmitDestructive() {
1071 $this->mSubmitModifierClass = 'mw-ui-destructive';
1072 }
1073
1074 /**
1075 * Identify that the submit button in the form has a progressive action
1076 * @since 1.25
1077 */
1078 public function setSubmitProgressive() {
1079 $this->mSubmitModifierClass = 'mw-ui-progressive';
1080 }
1081
1082 /**
1083 * Set the text for the submit button to a message
1084 * @since 1.19
1085 *
1086 * @param string|Message $msg Message key or Message object
1087 *
1088 * @return HTMLForm $this for chaining calls (since 1.20)
1089 */
1090 public function setSubmitTextMsg( $msg ) {
1091 if ( !$msg instanceof Message ) {
1092 $msg = $this->msg( $msg );
1093 }
1094 $this->setSubmitText( $msg->text() );
1095
1096 return $this;
1097 }
1098
1099 /**
1100 * Get the text for the submit button, either customised or a default.
1101 * @return string
1102 */
1103 function getSubmitText() {
1104 return $this->mSubmitText
1105 ? $this->mSubmitText
1106 : $this->msg( 'htmlform-submit' )->text();
1107 }
1108
1109 /**
1110 * @param string $name Submit button name
1111 *
1112 * @return HTMLForm $this for chaining calls (since 1.20)
1113 */
1114 public function setSubmitName( $name ) {
1115 $this->mSubmitName = $name;
1116
1117 return $this;
1118 }
1119
1120 /**
1121 * @param string $name Tooltip for the submit button
1122 *
1123 * @return HTMLForm $this for chaining calls (since 1.20)
1124 */
1125 public function setSubmitTooltip( $name ) {
1126 $this->mSubmitTooltip = $name;
1127
1128 return $this;
1129 }
1130
1131 /**
1132 * Set the id for the submit button.
1133 *
1134 * @param string $t
1135 *
1136 * @todo FIXME: Integrity of $t is *not* validated
1137 * @return HTMLForm $this for chaining calls (since 1.20)
1138 */
1139 function setSubmitID( $t ) {
1140 $this->mSubmitID = $t;
1141
1142 return $this;
1143 }
1144
1145 /**
1146 * Stop a default submit button being shown for this form. This implies that an
1147 * alternate submit method must be provided manually.
1148 *
1149 * @since 1.22
1150 *
1151 * @param bool $suppressSubmit Set to false to re-enable the button again
1152 *
1153 * @return HTMLForm $this for chaining calls
1154 */
1155 function suppressDefaultSubmit( $suppressSubmit = true ) {
1156 $this->mShowSubmit = !$suppressSubmit;
1157
1158 return $this;
1159 }
1160
1161 /**
1162 * Set the id of the \<table\> or outermost \<div\> element.
1163 *
1164 * @since 1.22
1165 *
1166 * @param string $id New value of the id attribute, or "" to remove
1167 *
1168 * @return HTMLForm $this for chaining calls
1169 */
1170 public function setTableId( $id ) {
1171 $this->mTableId = $id;
1172
1173 return $this;
1174 }
1175
1176 /**
1177 * @param string $id DOM id for the form
1178 *
1179 * @return HTMLForm $this for chaining calls (since 1.20)
1180 */
1181 public function setId( $id ) {
1182 $this->mId = $id;
1183
1184 return $this;
1185 }
1186
1187 /**
1188 * Prompt the whole form to be wrapped in a "<fieldset>", with
1189 * this text as its "<legend>" element.
1190 *
1191 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1192 * false for no <legend>
1193 * Will be escaped
1194 *
1195 * @return HTMLForm $this for chaining calls (since 1.20)
1196 */
1197 public function setWrapperLegend( $legend ) {
1198 $this->mWrapperLegend = $legend;
1199
1200 return $this;
1201 }
1202
1203 /**
1204 * Prompt the whole form to be wrapped in a "<fieldset>", with
1205 * this message as its "<legend>" element.
1206 * @since 1.19
1207 *
1208 * @param string|Message $msg Message key or Message object
1209 *
1210 * @return HTMLForm $this for chaining calls (since 1.20)
1211 */
1212 public function setWrapperLegendMsg( $msg ) {
1213 if ( !$msg instanceof Message ) {
1214 $msg = $this->msg( $msg );
1215 }
1216 $this->setWrapperLegend( $msg->text() );
1217
1218 return $this;
1219 }
1220
1221 /**
1222 * Set the prefix for various default messages
1223 * @todo Currently only used for the "<fieldset>" legend on forms
1224 * with multiple sections; should be used elsewhere?
1225 *
1226 * @param string $p
1227 *
1228 * @return HTMLForm $this for chaining calls (since 1.20)
1229 */
1230 function setMessagePrefix( $p ) {
1231 $this->mMessagePrefix = $p;
1232
1233 return $this;
1234 }
1235
1236 /**
1237 * Set the title for form submission
1238 *
1239 * @param Title $t Title of page the form is on/should be posted to
1240 *
1241 * @return HTMLForm $this for chaining calls (since 1.20)
1242 */
1243 function setTitle( $t ) {
1244 $this->mTitle = $t;
1245
1246 return $this;
1247 }
1248
1249 /**
1250 * Get the title
1251 * @return Title
1252 */
1253 function getTitle() {
1254 return $this->mTitle === false
1255 ? $this->getContext()->getTitle()
1256 : $this->mTitle;
1257 }
1258
1259 /**
1260 * Set the method used to submit the form
1261 *
1262 * @param string $method
1263 *
1264 * @return HTMLForm $this for chaining calls (since 1.20)
1265 */
1266 public function setMethod( $method = 'post' ) {
1267 $this->mMethod = $method;
1268
1269 return $this;
1270 }
1271
1272 public function getMethod() {
1273 return $this->mMethod;
1274 }
1275
1276 /**
1277 * @todo Document
1278 *
1279 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1280 * objects).
1281 * @param string $sectionName ID attribute of the "<table>" tag for this
1282 * section, ignored if empty.
1283 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1284 * each subsection, ignored if empty.
1285 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1286 *
1287 * @return string
1288 */
1289 public function displaySection( $fields,
1290 $sectionName = '',
1291 $fieldsetIDPrefix = '',
1292 &$hasUserVisibleFields = false ) {
1293 $displayFormat = $this->getDisplayFormat();
1294
1295 $html = '';
1296 $subsectionHtml = '';
1297 $hasLabel = false;
1298
1299 // Conveniently, PHP method names are case-insensitive.
1300 $getFieldHtmlMethod = $displayFormat == 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1301
1302 foreach ( $fields as $key => $value ) {
1303 if ( $value instanceof HTMLFormField ) {
1304 $v = empty( $value->mParams['nodata'] )
1305 ? $this->mFieldData[$key]
1306 : $value->getDefault();
1307 $html .= $value->$getFieldHtmlMethod( $v );
1308
1309 $labelValue = trim( $value->getLabel() );
1310 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1311 $hasLabel = true;
1312 }
1313
1314 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1315 get_class( $value ) !== 'HTMLApiField'
1316 ) {
1317 $hasUserVisibleFields = true;
1318 }
1319 } elseif ( is_array( $value ) ) {
1320 $subsectionHasVisibleFields = false;
1321 $section =
1322 $this->displaySection( $value,
1323 "mw-htmlform-$key",
1324 "$fieldsetIDPrefix$key-",
1325 $subsectionHasVisibleFields );
1326 $legend = null;
1327
1328 if ( $subsectionHasVisibleFields === true ) {
1329 // Display the section with various niceties.
1330 $hasUserVisibleFields = true;
1331
1332 $legend = $this->getLegend( $key );
1333
1334 if ( isset( $this->mSectionHeaders[$key] ) ) {
1335 $section = $this->mSectionHeaders[$key] . $section;
1336 }
1337 if ( isset( $this->mSectionFooters[$key] ) ) {
1338 $section .= $this->mSectionFooters[$key];
1339 }
1340
1341 $attributes = array();
1342 if ( $fieldsetIDPrefix ) {
1343 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1344 }
1345 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1346 } else {
1347 // Just return the inputs, nothing fancy.
1348 $subsectionHtml .= $section;
1349 }
1350 }
1351 }
1352
1353 if ( $displayFormat !== 'raw' ) {
1354 $classes = array();
1355
1356 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1357 $classes[] = 'mw-htmlform-nolabel';
1358 }
1359
1360 $attribs = array(
1361 'class' => implode( ' ', $classes ),
1362 );
1363
1364 if ( $sectionName ) {
1365 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1366 }
1367
1368 if ( $displayFormat === 'table' ) {
1369 $html = Html::rawElement( 'table',
1370 $attribs,
1371 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1372 } elseif ( $displayFormat === 'inline' ) {
1373 $html = Html::rawElement( 'span', $attribs, "\n$html\n" );
1374 } else {
1375 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1376 }
1377 }
1378
1379 if ( $this->mSubSectionBeforeFields ) {
1380 return $subsectionHtml . "\n" . $html;
1381 } else {
1382 return $html . "\n" . $subsectionHtml;
1383 }
1384 }
1385
1386 /**
1387 * Construct the form fields from the Descriptor array
1388 */
1389 function loadData() {
1390 $fieldData = array();
1391
1392 foreach ( $this->mFlatFields as $fieldname => $field ) {
1393 if ( !empty( $field->mParams['nodata'] ) ) {
1394 continue;
1395 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1396 $fieldData[$fieldname] = $field->getDefault();
1397 } else {
1398 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1399 }
1400 }
1401
1402 # Filter data.
1403 foreach ( $fieldData as $name => &$value ) {
1404 $field = $this->mFlatFields[$name];
1405 $value = $field->filter( $value, $this->mFlatFields );
1406 }
1407
1408 $this->mFieldData = $fieldData;
1409 }
1410
1411 /**
1412 * Stop a reset button being shown for this form
1413 *
1414 * @param bool $suppressReset Set to false to re-enable the button again
1415 *
1416 * @return HTMLForm $this for chaining calls (since 1.20)
1417 */
1418 function suppressReset( $suppressReset = true ) {
1419 $this->mShowReset = !$suppressReset;
1420
1421 return $this;
1422 }
1423
1424 /**
1425 * Overload this if you want to apply special filtration routines
1426 * to the form as a whole, after it's submitted but before it's
1427 * processed.
1428 *
1429 * @param array $data
1430 *
1431 * @return array
1432 */
1433 function filterDataForSubmit( $data ) {
1434 return $data;
1435 }
1436
1437 /**
1438 * Get a string to go in the "<legend>" of a section fieldset.
1439 * Override this if you want something more complicated.
1440 *
1441 * @param string $key
1442 *
1443 * @return string
1444 */
1445 public function getLegend( $key ) {
1446 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1447 }
1448
1449 /**
1450 * Set the value for the action attribute of the form.
1451 * When set to false (which is the default state), the set title is used.
1452 *
1453 * @since 1.19
1454 *
1455 * @param string|bool $action
1456 *
1457 * @return HTMLForm $this for chaining calls (since 1.20)
1458 */
1459 public function setAction( $action ) {
1460 $this->mAction = $action;
1461
1462 return $this;
1463 }
1464
1465 /**
1466 * Get the value for the action attribute of the form.
1467 *
1468 * @since 1.22
1469 *
1470 * @return string
1471 */
1472 public function getAction() {
1473 // If an action is alredy provided, return it
1474 if ( $this->mAction !== false ) {
1475 return $this->mAction;
1476 }
1477
1478 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1479 // Check whether we are in GET mode and the ArticlePath contains a "?"
1480 // meaning that getLocalURL() would return something like "index.php?title=...".
1481 // As browser remove the query string before submitting GET forms,
1482 // it means that the title would be lost. In such case use wfScript() instead
1483 // and put title in an hidden field (see getHiddenFields()).
1484 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1485 return wfScript();
1486 }
1487
1488 return $this->getTitle()->getLocalURL();
1489 }
1490 }