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