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