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