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