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