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