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