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