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