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