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