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