Merge "Include action in permission error messages"
[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 global $wgHTMLFormAllowTableFormat;
304 $format = $this->displayFormat;
305 if ( !$wgHTMLFormAllowTableFormat && $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->validate(
477 $this->mFieldData[$fieldname],
478 $this->mFieldData )
479 !== true
480 ) {
481 return isset( $this->mValidationErrorMessage )
482 ? $this->mValidationErrorMessage
483 : array( 'htmlform-invalid-input' );
484 }
485 }
486
487 $callback = $this->mSubmitCallback;
488 if ( !is_callable( $callback ) ) {
489 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
490 'setSubmitCallback() to set one.' );
491 }
492
493 $data = $this->filterDataForSubmit( $this->mFieldData );
494
495 $res = call_user_func( $callback, $data, $this );
496 if ( $res === false ) {
497 $this->mWasSubmitted = false;
498 }
499
500 return $res;
501 }
502
503 /**
504 * Test whether the form was considered to have been submitted or not, i.e.
505 * whether the last call to tryAuthorizedSubmit or trySubmit returned
506 * non-false.
507 *
508 * This will return false until HTMLForm::tryAuthorizedSubmit or
509 * HTMLForm::trySubmit is called.
510 *
511 * @since 1.23
512 * @return bool
513 */
514 function wasSubmitted() {
515 return $this->mWasSubmitted;
516 }
517
518 /**
519 * Set a callback to a function to do something with the form
520 * once it's been successfully validated.
521 *
522 * @param callable $cb The function will be passed the output from
523 * HTMLForm::filterDataForSubmit and this HTMLForm object, and must
524 * return as documented for HTMLForm::trySubmit
525 *
526 * @return HTMLForm $this for chaining calls (since 1.20)
527 */
528 function setSubmitCallback( $cb ) {
529 $this->mSubmitCallback = $cb;
530
531 return $this;
532 }
533
534 /**
535 * Set a message to display on a validation error.
536 *
537 * @param string|array $msg String or Array of valid inputs to wfMessage()
538 * (so each entry can be either a String or Array)
539 *
540 * @return HTMLForm $this for chaining calls (since 1.20)
541 */
542 function setValidationErrorMessage( $msg ) {
543 $this->mValidationErrorMessage = $msg;
544
545 return $this;
546 }
547
548 /**
549 * Set the introductory message, overwriting any existing message.
550 *
551 * @param string $msg Complete text of message to display
552 *
553 * @return HTMLForm $this for chaining calls (since 1.20)
554 */
555 function setIntro( $msg ) {
556 $this->setPreText( $msg );
557
558 return $this;
559 }
560
561 /**
562 * Set the introductory message, overwriting any existing message.
563 * @since 1.19
564 *
565 * @param string $msg Complete text of message to display
566 *
567 * @return HTMLForm $this for chaining calls (since 1.20)
568 */
569 function setPreText( $msg ) {
570 $this->mPre = $msg;
571
572 return $this;
573 }
574
575 /**
576 * Add introductory text.
577 *
578 * @param string $msg Complete text of message to display
579 *
580 * @return HTMLForm $this for chaining calls (since 1.20)
581 */
582 function addPreText( $msg ) {
583 $this->mPre .= $msg;
584
585 return $this;
586 }
587
588 /**
589 * Add header text, inside the form.
590 *
591 * @param string $msg Complete text of message to display
592 * @param string|null $section The section to add the header to
593 *
594 * @return HTMLForm $this for chaining calls (since 1.20)
595 */
596 function addHeaderText( $msg, $section = null ) {
597 if ( is_null( $section ) ) {
598 $this->mHeader .= $msg;
599 } else {
600 if ( !isset( $this->mSectionHeaders[$section] ) ) {
601 $this->mSectionHeaders[$section] = '';
602 }
603 $this->mSectionHeaders[$section] .= $msg;
604 }
605
606 return $this;
607 }
608
609 /**
610 * Set header text, inside the form.
611 * @since 1.19
612 *
613 * @param string $msg Complete text of message to display
614 * @param string|null $section The section to add the header to
615 *
616 * @return HTMLForm $this for chaining calls (since 1.20)
617 */
618 function setHeaderText( $msg, $section = null ) {
619 if ( is_null( $section ) ) {
620 $this->mHeader = $msg;
621 } else {
622 $this->mSectionHeaders[$section] = $msg;
623 }
624
625 return $this;
626 }
627
628 /**
629 * Add footer text, inside the form.
630 *
631 * @param string $msg Complete text of message to display
632 * @param string|null $section The section to add the footer text to
633 *
634 * @return HTMLForm $this for chaining calls (since 1.20)
635 */
636 function addFooterText( $msg, $section = null ) {
637 if ( is_null( $section ) ) {
638 $this->mFooter .= $msg;
639 } else {
640 if ( !isset( $this->mSectionFooters[$section] ) ) {
641 $this->mSectionFooters[$section] = '';
642 }
643 $this->mSectionFooters[$section] .= $msg;
644 }
645
646 return $this;
647 }
648
649 /**
650 * Set footer text, inside the form.
651 * @since 1.19
652 *
653 * @param string $msg Complete text of message to display
654 * @param string|null $section The section to add the footer text to
655 *
656 * @return HTMLForm $this for chaining calls (since 1.20)
657 */
658 function setFooterText( $msg, $section = null ) {
659 if ( is_null( $section ) ) {
660 $this->mFooter = $msg;
661 } else {
662 $this->mSectionFooters[$section] = $msg;
663 }
664
665 return $this;
666 }
667
668 /**
669 * Add text to the end of the display.
670 *
671 * @param string $msg Complete text of message to display
672 *
673 * @return HTMLForm $this for chaining calls (since 1.20)
674 */
675 function addPostText( $msg ) {
676 $this->mPost .= $msg;
677
678 return $this;
679 }
680
681 /**
682 * Set text at the end of the display.
683 *
684 * @param string $msg Complete text of message to display
685 *
686 * @return HTMLForm $this for chaining calls (since 1.20)
687 */
688 function setPostText( $msg ) {
689 $this->mPost = $msg;
690
691 return $this;
692 }
693
694 /**
695 * Add a hidden field to the output
696 *
697 * @param string $name Field name. This will be used exactly as entered
698 * @param string $value Field value
699 * @param array $attribs
700 *
701 * @return HTMLForm $this for chaining calls (since 1.20)
702 */
703 public function addHiddenField( $name, $value, $attribs = array() ) {
704 $attribs += array( 'name' => $name );
705 $this->mHiddenFields[] = array( $value, $attribs );
706
707 return $this;
708 }
709
710 /**
711 * Add an array of hidden fields to the output
712 *
713 * @since 1.22
714 *
715 * @param array $fields Associative array of fields to add;
716 * mapping names to their values
717 *
718 * @return HTMLForm $this for chaining calls
719 */
720 public function addHiddenFields( array $fields ) {
721 foreach ( $fields as $name => $value ) {
722 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
723 }
724
725 return $this;
726 }
727
728 /**
729 * Add a button to the form
730 *
731 * @param string $name Field name.
732 * @param string $value Field value
733 * @param string $id DOM id for the button (default: null)
734 * @param array $attribs
735 *
736 * @return HTMLForm $this for chaining calls (since 1.20)
737 */
738 public function addButton( $name, $value, $id = null, $attribs = null ) {
739 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
740
741 return $this;
742 }
743
744 /**
745 * Set the salt for the edit token.
746 *
747 * Only useful when the method is "post".
748 *
749 * @since 1.24
750 * @param string|array $salt Salt to use
751 * @return HTMLForm $this For chaining calls
752 */
753 public function setTokenSalt( $salt ) {
754 $this->mTokenSalt = $salt;
755
756 return $this;
757 }
758
759 /**
760 * Display the form (sending to the context's OutputPage object), with an
761 * appropriate error message or stack of messages, and any validation errors, etc.
762 *
763 * @attention You should call prepareForm() before calling this function.
764 * Moreover, when doing method chaining this should be the very last method
765 * call just after prepareForm().
766 *
767 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
768 *
769 * @return void Nothing, should be last call
770 */
771 function displayForm( $submitResult ) {
772 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
773 }
774
775 /**
776 * Returns the raw HTML generated by the form
777 *
778 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
779 *
780 * @return string
781 */
782 function getHTML( $submitResult ) {
783 # For good measure (it is the default)
784 $this->getOutput()->preventClickjacking();
785 $this->getOutput()->addModules( 'mediawiki.htmlform' );
786 if ( $this->isVForm() ) {
787 $this->getOutput()->addModuleStyles( array(
788 'mediawiki.ui',
789 'mediawiki.ui.button',
790 ) );
791 // @todo Should vertical form set setWrapperLegend( false )
792 // to hide ugly fieldsets?
793 }
794
795 $html = ''
796 . $this->getErrors( $submitResult )
797 . $this->mHeader
798 . $this->getBody()
799 . $this->getHiddenFields()
800 . $this->getButtons()
801 . $this->mFooter;
802
803 $html = $this->wrapForm( $html );
804
805 return '' . $this->mPre . $html . $this->mPost;
806 }
807
808 /**
809 * Wrap the form innards in an actual "<form>" element
810 *
811 * @param string $html HTML contents to wrap.
812 *
813 * @return string Wrapped HTML.
814 */
815 function wrapForm( $html ) {
816
817 # Include a <fieldset> wrapper for style, if requested.
818 if ( $this->mWrapperLegend !== false ) {
819 $html = Xml::fieldset( $this->mWrapperLegend, $html );
820 }
821 # Use multipart/form-data
822 $encType = $this->mUseMultipart
823 ? 'multipart/form-data'
824 : 'application/x-www-form-urlencoded';
825 # Attributes
826 $attribs = array(
827 'action' => $this->getAction(),
828 'method' => $this->getMethod(),
829 'class' => array( 'visualClear' ),
830 'enctype' => $encType,
831 );
832 if ( !empty( $this->mId ) ) {
833 $attribs['id'] = $this->mId;
834 }
835
836 if ( $this->isVForm() ) {
837 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
838 }
839
840 return Html::rawElement( 'form', $attribs, $html );
841 }
842
843 /**
844 * Get the hidden fields that should go inside the form.
845 * @return string HTML.
846 */
847 function getHiddenFields() {
848 global $wgArticlePath;
849
850 $html = '';
851 if ( $this->getMethod() == 'post' ) {
852 $html .= Html::hidden(
853 'wpEditToken',
854 $this->getUser()->getEditToken( $this->mTokenSalt ),
855 array( 'id' => 'wpEditToken' )
856 ) . "\n";
857 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
858 }
859
860 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
861 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
862 }
863
864 foreach ( $this->mHiddenFields as $data ) {
865 list( $value, $attribs ) = $data;
866 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
867 }
868
869 return $html;
870 }
871
872 /**
873 * Get the submit and (potentially) reset buttons.
874 * @return string HTML.
875 */
876 function getButtons() {
877 global $wgUseMediaWikiUIEverywhere;
878 $buttons = '';
879
880 if ( $this->mShowSubmit ) {
881 $attribs = array();
882
883 if ( isset( $this->mSubmitID ) ) {
884 $attribs['id'] = $this->mSubmitID;
885 }
886
887 if ( isset( $this->mSubmitName ) ) {
888 $attribs['name'] = $this->mSubmitName;
889 }
890
891 if ( isset( $this->mSubmitTooltip ) ) {
892 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
893 }
894
895 $attribs['class'] = array( 'mw-htmlform-submit' );
896
897 if ( $this->isVForm() || $wgUseMediaWikiUIEverywhere ) {
898 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-constructive' );
899 }
900
901 if ( $this->isVForm() ) {
902 // mw-ui-block is necessary because the buttons aren't necessarily in an
903 // immediate child div of the vform.
904 // @todo Let client specify if the primary submit button is progressive or destructive
905 array_push(
906 $attribs['class'],
907 'mw-ui-big',
908 'mw-ui-block'
909 );
910 }
911
912 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
913 }
914
915 if ( $this->mShowReset ) {
916 $buttons .= Html::element(
917 'input',
918 array(
919 'type' => 'reset',
920 'value' => $this->msg( 'htmlform-reset' )->text()
921 )
922 ) . "\n";
923 }
924
925 foreach ( $this->mButtons as $button ) {
926 $attrs = array(
927 'type' => 'submit',
928 'name' => $button['name'],
929 'value' => $button['value']
930 );
931
932 if ( $button['attribs'] ) {
933 $attrs += $button['attribs'];
934 }
935
936 if ( isset( $button['id'] ) ) {
937 $attrs['id'] = $button['id'];
938 }
939
940 if ( $wgUseMediaWikiUIEverywhere ) {
941 if ( isset( $attrs['class' ] ) ) {
942 $attrs['class'] .= ' mw-ui-button';
943 } else {
944 $attrs['class'] = 'mw-ui-button';
945 }
946 }
947
948 $buttons .= Html::element( 'input', $attrs ) . "\n";
949 }
950
951 $html = Html::rawElement( 'span',
952 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
953
954 // Buttons are top-level form elements in table and div layouts,
955 // but vform wants all elements inside divs to get spaced-out block
956 // styling.
957 if ( $this->mShowSubmit && $this->isVForm() ) {
958 $html = Html::rawElement( 'div', null, "\n$html" ) . "\n";
959 }
960
961 return $html;
962 }
963
964 /**
965 * Get the whole body of the form.
966 * @return string
967 */
968 function getBody() {
969 return $this->displaySection( $this->mFieldTree, $this->mTableId );
970 }
971
972 /**
973 * Format and display an error message stack.
974 *
975 * @param string|array|Status $errors
976 *
977 * @return string
978 */
979 function getErrors( $errors ) {
980 if ( $errors instanceof Status ) {
981 if ( $errors->isOK() ) {
982 $errorstr = '';
983 } else {
984 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
985 }
986 } elseif ( is_array( $errors ) ) {
987 $errorstr = $this->formatErrors( $errors );
988 } else {
989 $errorstr = $errors;
990 }
991
992 return $errorstr
993 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
994 : '';
995 }
996
997 /**
998 * Format a stack of error messages into a single HTML string
999 *
1000 * @param array $errors Array of message keys/values
1001 *
1002 * @return string HTML, a "<ul>" list of errors
1003 */
1004 public static function formatErrors( $errors ) {
1005 $errorstr = '';
1006
1007 foreach ( $errors as $error ) {
1008 if ( is_array( $error ) ) {
1009 $msg = array_shift( $error );
1010 } else {
1011 $msg = $error;
1012 $error = array();
1013 }
1014
1015 $errorstr .= Html::rawElement(
1016 'li',
1017 array(),
1018 wfMessage( $msg, $error )->parse()
1019 );
1020 }
1021
1022 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1023
1024 return $errorstr;
1025 }
1026
1027 /**
1028 * Set the text for the submit button
1029 *
1030 * @param string $t Plaintext
1031 *
1032 * @return HTMLForm $this for chaining calls (since 1.20)
1033 */
1034 function setSubmitText( $t ) {
1035 $this->mSubmitText = $t;
1036
1037 return $this;
1038 }
1039
1040 /**
1041 * Set the text for the submit button to a message
1042 * @since 1.19
1043 *
1044 * @param string|Message $msg Message key or Message object
1045 *
1046 * @return HTMLForm $this for chaining calls (since 1.20)
1047 */
1048 public function setSubmitTextMsg( $msg ) {
1049 if ( !$msg instanceof Message ) {
1050 $msg = $this->msg( $msg );
1051 }
1052 $this->setSubmitText( $msg->text() );
1053
1054 return $this;
1055 }
1056
1057 /**
1058 * Get the text for the submit button, either customised or a default.
1059 * @return string
1060 */
1061 function getSubmitText() {
1062 return $this->mSubmitText
1063 ? $this->mSubmitText
1064 : $this->msg( 'htmlform-submit' )->text();
1065 }
1066
1067 /**
1068 * @param string $name Submit button name
1069 *
1070 * @return HTMLForm $this for chaining calls (since 1.20)
1071 */
1072 public function setSubmitName( $name ) {
1073 $this->mSubmitName = $name;
1074
1075 return $this;
1076 }
1077
1078 /**
1079 * @param string $name Tooltip for the submit button
1080 *
1081 * @return HTMLForm $this for chaining calls (since 1.20)
1082 */
1083 public function setSubmitTooltip( $name ) {
1084 $this->mSubmitTooltip = $name;
1085
1086 return $this;
1087 }
1088
1089 /**
1090 * Set the id for the submit button.
1091 *
1092 * @param string $t
1093 *
1094 * @todo FIXME: Integrity of $t is *not* validated
1095 * @return HTMLForm $this for chaining calls (since 1.20)
1096 */
1097 function setSubmitID( $t ) {
1098 $this->mSubmitID = $t;
1099
1100 return $this;
1101 }
1102
1103 /**
1104 * Stop a default submit button being shown for this form. This implies that an
1105 * alternate submit method must be provided manually.
1106 *
1107 * @since 1.22
1108 *
1109 * @param bool $suppressSubmit Set to false to re-enable the button again
1110 *
1111 * @return HTMLForm $this for chaining calls
1112 */
1113 function suppressDefaultSubmit( $suppressSubmit = true ) {
1114 $this->mShowSubmit = !$suppressSubmit;
1115
1116 return $this;
1117 }
1118
1119 /**
1120 * Set the id of the \<table\> or outermost \<div\> element.
1121 *
1122 * @since 1.22
1123 *
1124 * @param string $id New value of the id attribute, or "" to remove
1125 *
1126 * @return HTMLForm $this for chaining calls
1127 */
1128 public function setTableId( $id ) {
1129 $this->mTableId = $id;
1130
1131 return $this;
1132 }
1133
1134 /**
1135 * @param string $id DOM id for the form
1136 *
1137 * @return HTMLForm $this for chaining calls (since 1.20)
1138 */
1139 public function setId( $id ) {
1140 $this->mId = $id;
1141
1142 return $this;
1143 }
1144
1145 /**
1146 * Prompt the whole form to be wrapped in a "<fieldset>", with
1147 * this text as its "<legend>" element.
1148 *
1149 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1150 * false for no <legend>
1151 * Will be escaped
1152 *
1153 * @return HTMLForm $this for chaining calls (since 1.20)
1154 */
1155 public function setWrapperLegend( $legend ) {
1156 $this->mWrapperLegend = $legend;
1157
1158 return $this;
1159 }
1160
1161 /**
1162 * Prompt the whole form to be wrapped in a "<fieldset>", with
1163 * this message as its "<legend>" element.
1164 * @since 1.19
1165 *
1166 * @param string|Message $msg Message key or Message object
1167 *
1168 * @return HTMLForm $this for chaining calls (since 1.20)
1169 */
1170 public function setWrapperLegendMsg( $msg ) {
1171 if ( !$msg instanceof Message ) {
1172 $msg = $this->msg( $msg );
1173 }
1174 $this->setWrapperLegend( $msg->text() );
1175
1176 return $this;
1177 }
1178
1179 /**
1180 * Set the prefix for various default messages
1181 * @todo Currently only used for the "<fieldset>" legend on forms
1182 * with multiple sections; should be used elsewhere?
1183 *
1184 * @param string $p
1185 *
1186 * @return HTMLForm $this for chaining calls (since 1.20)
1187 */
1188 function setMessagePrefix( $p ) {
1189 $this->mMessagePrefix = $p;
1190
1191 return $this;
1192 }
1193
1194 /**
1195 * Set the title for form submission
1196 *
1197 * @param Title $t Title of page the form is on/should be posted to
1198 *
1199 * @return HTMLForm $this for chaining calls (since 1.20)
1200 */
1201 function setTitle( $t ) {
1202 $this->mTitle = $t;
1203
1204 return $this;
1205 }
1206
1207 /**
1208 * Get the title
1209 * @return Title
1210 */
1211 function getTitle() {
1212 return $this->mTitle === false
1213 ? $this->getContext()->getTitle()
1214 : $this->mTitle;
1215 }
1216
1217 /**
1218 * Set the method used to submit the form
1219 *
1220 * @param string $method
1221 *
1222 * @return HTMLForm $this for chaining calls (since 1.20)
1223 */
1224 public function setMethod( $method = 'post' ) {
1225 $this->mMethod = $method;
1226
1227 return $this;
1228 }
1229
1230 public function getMethod() {
1231 return $this->mMethod;
1232 }
1233
1234 /**
1235 * @todo Document
1236 *
1237 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1238 * objects).
1239 * @param string $sectionName ID attribute of the "<table>" tag for this
1240 * section, ignored if empty.
1241 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1242 * each subsection, ignored if empty.
1243 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1244 *
1245 * @return string
1246 */
1247 public function displaySection( $fields,
1248 $sectionName = '',
1249 $fieldsetIDPrefix = '',
1250 &$hasUserVisibleFields = false ) {
1251 $displayFormat = $this->getDisplayFormat();
1252
1253 $html = '';
1254 $subsectionHtml = '';
1255 $hasLabel = false;
1256
1257 switch ( $displayFormat ) {
1258 case 'table':
1259 $getFieldHtmlMethod = 'getTableRow';
1260 break;
1261 case 'vform':
1262 // Close enough to a div.
1263 $getFieldHtmlMethod = 'getDiv';
1264 break;
1265 case 'div':
1266 $getFieldHtmlMethod = 'getDiv';
1267 break;
1268 default:
1269 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1270 }
1271
1272 foreach ( $fields as $key => $value ) {
1273 if ( $value instanceof HTMLFormField ) {
1274 $v = empty( $value->mParams['nodata'] )
1275 ? $this->mFieldData[$key]
1276 : $value->getDefault();
1277 $html .= $value->$getFieldHtmlMethod( $v );
1278
1279 $labelValue = trim( $value->getLabel() );
1280 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1281 $hasLabel = true;
1282 }
1283
1284 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1285 get_class( $value ) !== 'HTMLApiField'
1286 ) {
1287 $hasUserVisibleFields = true;
1288 }
1289 } elseif ( is_array( $value ) ) {
1290 $subsectionHasVisibleFields = false;
1291 $section =
1292 $this->displaySection( $value,
1293 "mw-htmlform-$key",
1294 "$fieldsetIDPrefix$key-",
1295 $subsectionHasVisibleFields );
1296 $legend = null;
1297
1298 if ( $subsectionHasVisibleFields === true ) {
1299 // Display the section with various niceties.
1300 $hasUserVisibleFields = true;
1301
1302 $legend = $this->getLegend( $key );
1303
1304 if ( isset( $this->mSectionHeaders[$key] ) ) {
1305 $section = $this->mSectionHeaders[$key] . $section;
1306 }
1307 if ( isset( $this->mSectionFooters[$key] ) ) {
1308 $section .= $this->mSectionFooters[$key];
1309 }
1310
1311 $attributes = array();
1312 if ( $fieldsetIDPrefix ) {
1313 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1314 }
1315 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1316 } else {
1317 // Just return the inputs, nothing fancy.
1318 $subsectionHtml .= $section;
1319 }
1320 }
1321 }
1322
1323 if ( $displayFormat !== 'raw' ) {
1324 $classes = array();
1325
1326 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1327 $classes[] = 'mw-htmlform-nolabel';
1328 }
1329
1330 $attribs = array(
1331 'class' => implode( ' ', $classes ),
1332 );
1333
1334 if ( $sectionName ) {
1335 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1336 }
1337
1338 if ( $displayFormat === 'table' ) {
1339 $html = Html::rawElement( 'table',
1340 $attribs,
1341 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1342 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1343 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1344 }
1345 }
1346
1347 if ( $this->mSubSectionBeforeFields ) {
1348 return $subsectionHtml . "\n" . $html;
1349 } else {
1350 return $html . "\n" . $subsectionHtml;
1351 }
1352 }
1353
1354 /**
1355 * Construct the form fields from the Descriptor array
1356 */
1357 function loadData() {
1358 $fieldData = array();
1359
1360 foreach ( $this->mFlatFields as $fieldname => $field ) {
1361 if ( !empty( $field->mParams['nodata'] ) ) {
1362 continue;
1363 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1364 $fieldData[$fieldname] = $field->getDefault();
1365 } else {
1366 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1367 }
1368 }
1369
1370 # Filter data.
1371 foreach ( $fieldData as $name => &$value ) {
1372 $field = $this->mFlatFields[$name];
1373 $value = $field->filter( $value, $this->mFlatFields );
1374 }
1375
1376 $this->mFieldData = $fieldData;
1377 }
1378
1379 /**
1380 * Stop a reset button being shown for this form
1381 *
1382 * @param bool $suppressReset Set to false to re-enable the button again
1383 *
1384 * @return HTMLForm $this for chaining calls (since 1.20)
1385 */
1386 function suppressReset( $suppressReset = true ) {
1387 $this->mShowReset = !$suppressReset;
1388
1389 return $this;
1390 }
1391
1392 /**
1393 * Overload this if you want to apply special filtration routines
1394 * to the form as a whole, after it's submitted but before it's
1395 * processed.
1396 *
1397 * @param array $data
1398 *
1399 * @return array
1400 */
1401 function filterDataForSubmit( $data ) {
1402 return $data;
1403 }
1404
1405 /**
1406 * Get a string to go in the "<legend>" of a section fieldset.
1407 * Override this if you want something more complicated.
1408 *
1409 * @param string $key
1410 *
1411 * @return string
1412 */
1413 public function getLegend( $key ) {
1414 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1415 }
1416
1417 /**
1418 * Set the value for the action attribute of the form.
1419 * When set to false (which is the default state), the set title is used.
1420 *
1421 * @since 1.19
1422 *
1423 * @param string|bool $action
1424 *
1425 * @return HTMLForm $this for chaining calls (since 1.20)
1426 */
1427 public function setAction( $action ) {
1428 $this->mAction = $action;
1429
1430 return $this;
1431 }
1432
1433 /**
1434 * Get the value for the action attribute of the form.
1435 *
1436 * @since 1.22
1437 *
1438 * @return string
1439 */
1440 public function getAction() {
1441 global $wgScript, $wgArticlePath;
1442
1443 // If an action is alredy provided, return it
1444 if ( $this->mAction !== false ) {
1445 return $this->mAction;
1446 }
1447
1448 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1449 // meaning that getLocalURL() would return something like "index.php?title=...".
1450 // As browser remove the query string before submitting GET forms,
1451 // it means that the title would be lost. In such case use $wgScript instead
1452 // and put title in an hidden field (see getHiddenFields()).
1453 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1454 return $wgScript;
1455 }
1456
1457 return $this->getTitle()->getLocalURL();
1458 }
1459 }