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