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