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