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