Merge "Merge namespace aliases like we merge namespace names"
[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 * @param string $name Field name.
859 * @param string $value Field value
860 * @param string $id DOM id for the button (default: null)
861 * @param array $attribs
862 *
863 * @return HTMLForm $this for chaining calls (since 1.20)
864 */
865 public function addButton( $name, $value, $id = null, $attribs = null ) {
866 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
867
868 return $this;
869 }
870
871 /**
872 * Set the salt for the edit token.
873 *
874 * Only useful when the method is "post".
875 *
876 * @since 1.24
877 * @param string|array $salt Salt to use
878 * @return HTMLForm $this For chaining calls
879 */
880 public function setTokenSalt( $salt ) {
881 $this->mTokenSalt = $salt;
882
883 return $this;
884 }
885
886 /**
887 * Display the form (sending to the context's OutputPage object), with an
888 * appropriate error message or stack of messages, and any validation errors, etc.
889 *
890 * @attention You should call prepareForm() before calling this function.
891 * Moreover, when doing method chaining this should be the very last method
892 * call just after prepareForm().
893 *
894 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
895 *
896 * @return void Nothing, should be last call
897 */
898 function displayForm( $submitResult ) {
899 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
900 }
901
902 /**
903 * Returns the raw HTML generated by the form
904 *
905 * @param bool|string|array|Status $submitResult Output from HTMLForm::trySubmit()
906 *
907 * @return string
908 */
909 function getHTML( $submitResult ) {
910 # For good measure (it is the default)
911 $this->getOutput()->preventClickjacking();
912 $this->getOutput()->addModules( 'mediawiki.htmlform' );
913 $this->getOutput()->addModuleStyles( 'mediawiki.htmlform.styles' );
914
915 $html = ''
916 . $this->getErrors( $submitResult )
917 . $this->getHeaderText()
918 . $this->getBody()
919 . $this->getHiddenFields()
920 . $this->getButtons()
921 . $this->getFooterText();
922
923 $html = $this->wrapForm( $html );
924
925 return '' . $this->mPre . $html . $this->mPost;
926 }
927
928 /**
929 * Get HTML attributes for the `<form>` tag.
930 * @return array
931 */
932 protected function getFormAttributes() {
933 # Use multipart/form-data
934 $encType = $this->mUseMultipart
935 ? 'multipart/form-data'
936 : 'application/x-www-form-urlencoded';
937 # Attributes
938 $attribs = array(
939 'action' => $this->getAction(),
940 'method' => $this->getMethod(),
941 'enctype' => $encType,
942 );
943 if ( !empty( $this->mId ) ) {
944 $attribs['id'] = $this->mId;
945 }
946 return $attribs;
947 }
948
949 /**
950 * Wrap the form innards in an actual "<form>" element
951 *
952 * @param string $html HTML contents to wrap.
953 *
954 * @return string Wrapped HTML.
955 */
956 function wrapForm( $html ) {
957 # Include a <fieldset> wrapper for style, if requested.
958 if ( $this->mWrapperLegend !== false ) {
959 $legend = is_string( $this->mWrapperLegend ) ? $this->mWrapperLegend : false;
960 $html = Xml::fieldset( $legend, $html );
961 }
962
963 return Html::rawElement(
964 'form',
965 $this->getFormAttributes() + array( 'class' => 'visualClear' ),
966 $html
967 );
968 }
969
970 /**
971 * Get the hidden fields that should go inside the form.
972 * @return string HTML.
973 */
974 function getHiddenFields() {
975 $html = '';
976 if ( $this->getMethod() == 'post' ) {
977 $html .= Html::hidden(
978 'wpEditToken',
979 $this->getUser()->getEditToken( $this->mTokenSalt ),
980 array( 'id' => 'wpEditToken' )
981 ) . "\n";
982 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
983 }
984
985 $articlePath = $this->getConfig()->get( 'ArticlePath' );
986 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
987 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
988 }
989
990 foreach ( $this->mHiddenFields as $data ) {
991 list( $value, $attribs ) = $data;
992 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
993 }
994
995 return $html;
996 }
997
998 /**
999 * Get the submit and (potentially) reset buttons.
1000 * @return string HTML.
1001 */
1002 function getButtons() {
1003 $buttons = '';
1004 $useMediaWikiUIEverywhere = $this->getConfig()->get( 'UseMediaWikiUIEverywhere' );
1005
1006 if ( $this->mShowSubmit ) {
1007 $attribs = array();
1008
1009 if ( isset( $this->mSubmitID ) ) {
1010 $attribs['id'] = $this->mSubmitID;
1011 }
1012
1013 if ( isset( $this->mSubmitName ) ) {
1014 $attribs['name'] = $this->mSubmitName;
1015 }
1016
1017 if ( isset( $this->mSubmitTooltip ) ) {
1018 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
1019 }
1020
1021 $attribs['class'] = array( 'mw-htmlform-submit' );
1022
1023 if ( $useMediaWikiUIEverywhere ) {
1024 foreach ( $this->mSubmitFlags as $flag ) {
1025 array_push( $attribs['class'], 'mw-ui-' . $flag );
1026 }
1027 array_push( $attribs['class'], 'mw-ui-button' );
1028 }
1029
1030 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
1031 }
1032
1033 if ( $this->mShowReset ) {
1034 $buttons .= Html::element(
1035 'input',
1036 array(
1037 'type' => 'reset',
1038 'value' => $this->msg( 'htmlform-reset' )->text(),
1039 'class' => ( $useMediaWikiUIEverywhere ? 'mw-ui-button' : null ),
1040 )
1041 ) . "\n";
1042 }
1043
1044 foreach ( $this->mButtons as $button ) {
1045 $attrs = array(
1046 'type' => 'submit',
1047 'name' => $button['name'],
1048 'value' => $button['value']
1049 );
1050
1051 if ( $button['attribs'] ) {
1052 $attrs += $button['attribs'];
1053 }
1054
1055 if ( isset( $button['id'] ) ) {
1056 $attrs['id'] = $button['id'];
1057 }
1058
1059 if ( $useMediaWikiUIEverywhere ) {
1060 $attrs['class'] = isset( $attrs['class'] ) ? (array)$attrs['class'] : array();
1061 $attrs['class'][] = 'mw-ui-button';
1062 }
1063
1064 $buttons .= Html::element( 'input', $attrs ) . "\n";
1065 }
1066
1067 $html = Html::rawElement( 'span',
1068 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
1069
1070 return $html;
1071 }
1072
1073 /**
1074 * Get the whole body of the form.
1075 * @return string
1076 */
1077 function getBody() {
1078 return $this->displaySection( $this->mFieldTree, $this->mTableId );
1079 }
1080
1081 /**
1082 * Format and display an error message stack.
1083 *
1084 * @param string|array|Status $errors
1085 *
1086 * @return string
1087 */
1088 function getErrors( $errors ) {
1089 if ( $errors instanceof Status ) {
1090 if ( $errors->isOK() ) {
1091 $errorstr = '';
1092 } else {
1093 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
1094 }
1095 } elseif ( is_array( $errors ) ) {
1096 $errorstr = $this->formatErrors( $errors );
1097 } else {
1098 $errorstr = $errors;
1099 }
1100
1101 return $errorstr
1102 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
1103 : '';
1104 }
1105
1106 /**
1107 * Format a stack of error messages into a single HTML string
1108 *
1109 * @param array $errors Array of message keys/values
1110 *
1111 * @return string HTML, a "<ul>" list of errors
1112 */
1113 public function formatErrors( $errors ) {
1114 $errorstr = '';
1115
1116 foreach ( $errors as $error ) {
1117 if ( is_array( $error ) ) {
1118 $msg = array_shift( $error );
1119 } else {
1120 $msg = $error;
1121 $error = array();
1122 }
1123
1124 $errorstr .= Html::rawElement(
1125 'li',
1126 array(),
1127 $this->msg( $msg, $error )->parse()
1128 );
1129 }
1130
1131 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
1132
1133 return $errorstr;
1134 }
1135
1136 /**
1137 * Set the text for the submit button
1138 *
1139 * @param string $t Plaintext
1140 *
1141 * @return HTMLForm $this for chaining calls (since 1.20)
1142 */
1143 function setSubmitText( $t ) {
1144 $this->mSubmitText = $t;
1145
1146 return $this;
1147 }
1148
1149 /**
1150 * Identify that the submit button in the form has a destructive action
1151 * @since 1.24
1152 */
1153 public function setSubmitDestructive() {
1154 $this->mSubmitFlags = array( 'destructive', 'primary' );
1155 }
1156
1157 /**
1158 * Identify that the submit button in the form has a progressive action
1159 * @since 1.25
1160 */
1161 public function setSubmitProgressive() {
1162 $this->mSubmitFlags = array( 'progressive', 'primary' );
1163 }
1164
1165 /**
1166 * Set the text for the submit button to a message
1167 * @since 1.19
1168 *
1169 * @param string|Message $msg Message key or Message object
1170 *
1171 * @return HTMLForm $this for chaining calls (since 1.20)
1172 */
1173 public function setSubmitTextMsg( $msg ) {
1174 if ( !$msg instanceof Message ) {
1175 $msg = $this->msg( $msg );
1176 }
1177 $this->setSubmitText( $msg->text() );
1178
1179 return $this;
1180 }
1181
1182 /**
1183 * Get the text for the submit button, either customised or a default.
1184 * @return string
1185 */
1186 function getSubmitText() {
1187 return $this->mSubmitText
1188 ? $this->mSubmitText
1189 : $this->msg( 'htmlform-submit' )->text();
1190 }
1191
1192 /**
1193 * @param string $name Submit button name
1194 *
1195 * @return HTMLForm $this for chaining calls (since 1.20)
1196 */
1197 public function setSubmitName( $name ) {
1198 $this->mSubmitName = $name;
1199
1200 return $this;
1201 }
1202
1203 /**
1204 * @param string $name Tooltip for the submit button
1205 *
1206 * @return HTMLForm $this for chaining calls (since 1.20)
1207 */
1208 public function setSubmitTooltip( $name ) {
1209 $this->mSubmitTooltip = $name;
1210
1211 return $this;
1212 }
1213
1214 /**
1215 * Set the id for the submit button.
1216 *
1217 * @param string $t
1218 *
1219 * @todo FIXME: Integrity of $t is *not* validated
1220 * @return HTMLForm $this for chaining calls (since 1.20)
1221 */
1222 function setSubmitID( $t ) {
1223 $this->mSubmitID = $t;
1224
1225 return $this;
1226 }
1227
1228 /**
1229 * Stop a default submit button being shown for this form. This implies that an
1230 * alternate submit method must be provided manually.
1231 *
1232 * @since 1.22
1233 *
1234 * @param bool $suppressSubmit Set to false to re-enable the button again
1235 *
1236 * @return HTMLForm $this for chaining calls
1237 */
1238 function suppressDefaultSubmit( $suppressSubmit = true ) {
1239 $this->mShowSubmit = !$suppressSubmit;
1240
1241 return $this;
1242 }
1243
1244 /**
1245 * Set the id of the \<table\> or outermost \<div\> element.
1246 *
1247 * @since 1.22
1248 *
1249 * @param string $id New value of the id attribute, or "" to remove
1250 *
1251 * @return HTMLForm $this for chaining calls
1252 */
1253 public function setTableId( $id ) {
1254 $this->mTableId = $id;
1255
1256 return $this;
1257 }
1258
1259 /**
1260 * @param string $id DOM id for the form
1261 *
1262 * @return HTMLForm $this for chaining calls (since 1.20)
1263 */
1264 public function setId( $id ) {
1265 $this->mId = $id;
1266
1267 return $this;
1268 }
1269
1270 /**
1271 * Prompt the whole form to be wrapped in a "<fieldset>", with
1272 * this text as its "<legend>" element.
1273 *
1274 * @param string|bool $legend If false, no wrapper or legend will be displayed.
1275 * If true, a wrapper will be displayed, but no legend.
1276 * If a string, a wrapper will be displayed with that string as a legend.
1277 * The string will be escaped before being output (this doesn't support HTML).
1278 *
1279 * @return HTMLForm $this for chaining calls (since 1.20)
1280 */
1281 public function setWrapperLegend( $legend ) {
1282 $this->mWrapperLegend = $legend;
1283
1284 return $this;
1285 }
1286
1287 /**
1288 * Prompt the whole form to be wrapped in a "<fieldset>", with
1289 * this message as its "<legend>" element.
1290 * @since 1.19
1291 *
1292 * @param string|Message $msg Message key or Message object
1293 *
1294 * @return HTMLForm $this for chaining calls (since 1.20)
1295 */
1296 public function setWrapperLegendMsg( $msg ) {
1297 if ( !$msg instanceof Message ) {
1298 $msg = $this->msg( $msg );
1299 }
1300 $this->setWrapperLegend( $msg->text() );
1301
1302 return $this;
1303 }
1304
1305 /**
1306 * Set the prefix for various default messages
1307 * @todo Currently only used for the "<fieldset>" legend on forms
1308 * with multiple sections; should be used elsewhere?
1309 *
1310 * @param string $p
1311 *
1312 * @return HTMLForm $this for chaining calls (since 1.20)
1313 */
1314 function setMessagePrefix( $p ) {
1315 $this->mMessagePrefix = $p;
1316
1317 return $this;
1318 }
1319
1320 /**
1321 * Set the title for form submission
1322 *
1323 * @param Title $t Title of page the form is on/should be posted to
1324 *
1325 * @return HTMLForm $this for chaining calls (since 1.20)
1326 */
1327 function setTitle( $t ) {
1328 $this->mTitle = $t;
1329
1330 return $this;
1331 }
1332
1333 /**
1334 * Get the title
1335 * @return Title
1336 */
1337 function getTitle() {
1338 return $this->mTitle === false
1339 ? $this->getContext()->getTitle()
1340 : $this->mTitle;
1341 }
1342
1343 /**
1344 * Set the method used to submit the form
1345 *
1346 * @param string $method
1347 *
1348 * @return HTMLForm $this for chaining calls (since 1.20)
1349 */
1350 public function setMethod( $method = 'post' ) {
1351 $this->mMethod = strtolower( $method );
1352
1353 return $this;
1354 }
1355
1356 /**
1357 * @return string Always lowercase
1358 */
1359 public function getMethod() {
1360 return $this->mMethod;
1361 }
1362
1363 /**
1364 * Wraps the given $section into an user-visible fieldset.
1365 *
1366 * @param string $legend Legend text for the fieldset
1367 * @param string $section The section content in plain Html
1368 * @param array $attributes Additional attributes for the fieldset
1369 * @return string The fieldset's Html
1370 */
1371 protected function wrapFieldSetSection( $legend, $section, $attributes ) {
1372 return Xml::fieldset( $legend, $section, $attributes ) . "\n";
1373 }
1374
1375 /**
1376 * @todo Document
1377 *
1378 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1379 * objects).
1380 * @param string $sectionName ID attribute of the "<table>" tag for this
1381 * section, ignored if empty.
1382 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1383 * each subsection, ignored if empty.
1384 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1385 *
1386 * @return string
1387 */
1388 public function displaySection( $fields,
1389 $sectionName = '',
1390 $fieldsetIDPrefix = '',
1391 &$hasUserVisibleFields = false ) {
1392 $displayFormat = $this->getDisplayFormat();
1393
1394 $html = array();
1395 $subsectionHtml = '';
1396 $hasLabel = false;
1397
1398 // Conveniently, PHP method names are case-insensitive.
1399 $getFieldHtmlMethod = $displayFormat == 'table' ? 'getTableRow' : ( 'get' . $displayFormat );
1400
1401 foreach ( $fields as $key => $value ) {
1402 if ( $value instanceof HTMLFormField ) {
1403 $v = empty( $value->mParams['nodata'] )
1404 ? $this->mFieldData[$key]
1405 : $value->getDefault();
1406
1407 $retval = $value->$getFieldHtmlMethod( $v );
1408
1409 // check, if the form field should be added to
1410 // the output.
1411 if ( $value->hasVisibleOutput() ) {
1412 $html[] = $retval;
1413
1414 $labelValue = trim( $value->getLabel() );
1415 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1416 $hasLabel = true;
1417 }
1418
1419 $hasUserVisibleFields = true;
1420 }
1421 } elseif ( is_array( $value ) ) {
1422 $subsectionHasVisibleFields = false;
1423 $section =
1424 $this->displaySection( $value,
1425 "mw-htmlform-$key",
1426 "$fieldsetIDPrefix$key-",
1427 $subsectionHasVisibleFields );
1428 $legend = null;
1429
1430 if ( $subsectionHasVisibleFields === true ) {
1431 // Display the section with various niceties.
1432 $hasUserVisibleFields = true;
1433
1434 $legend = $this->getLegend( $key );
1435
1436 $section = $this->getHeaderText( $key ) .
1437 $section .
1438 $this->getFooterText( $key );
1439
1440 $attributes = array();
1441 if ( $fieldsetIDPrefix ) {
1442 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1443 }
1444 $subsectionHtml .= $this->wrapFieldSetSection( $legend, $section, $attributes );
1445 } else {
1446 // Just return the inputs, nothing fancy.
1447 $subsectionHtml .= $section;
1448 }
1449 }
1450 }
1451
1452 $html = $this->formatSection( $html, $sectionName, $hasLabel );
1453
1454 if ( $subsectionHtml ) {
1455 if ( $this->mSubSectionBeforeFields ) {
1456 return $subsectionHtml . "\n" . $html;
1457 } else {
1458 return $html . "\n" . $subsectionHtml;
1459 }
1460 } else {
1461 return $html;
1462 }
1463 }
1464
1465 /**
1466 * Put a form section together from the individual fields' HTML, merging it and wrapping.
1467 * @param array $fieldsHtml
1468 * @param string $sectionName
1469 * @param bool $anyFieldHasLabel
1470 * @return string HTML
1471 */
1472 protected function formatSection( array $fieldsHtml, $sectionName, $anyFieldHasLabel ) {
1473 $displayFormat = $this->getDisplayFormat();
1474 $html = implode( '', $fieldsHtml );
1475
1476 if ( $displayFormat === 'raw' ) {
1477 return $html;
1478 }
1479
1480 $classes = array();
1481
1482 if ( !$anyFieldHasLabel ) { // Avoid strange spacing when no labels exist
1483 $classes[] = 'mw-htmlform-nolabel';
1484 }
1485
1486 $attribs = array(
1487 'class' => implode( ' ', $classes ),
1488 );
1489
1490 if ( $sectionName ) {
1491 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1492 }
1493
1494 if ( $displayFormat === 'table' ) {
1495 return Html::rawElement( 'table',
1496 $attribs,
1497 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1498 } elseif ( $displayFormat === 'inline' ) {
1499 return Html::rawElement( 'span', $attribs, "\n$html\n" );
1500 } else {
1501 return Html::rawElement( 'div', $attribs, "\n$html\n" );
1502 }
1503 }
1504
1505 /**
1506 * Construct the form fields from the Descriptor array
1507 */
1508 function loadData() {
1509 $fieldData = array();
1510
1511 foreach ( $this->mFlatFields as $fieldname => $field ) {
1512 if ( !empty( $field->mParams['nodata'] ) ) {
1513 continue;
1514 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1515 $fieldData[$fieldname] = $field->getDefault();
1516 } else {
1517 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1518 }
1519 }
1520
1521 # Filter data.
1522 foreach ( $fieldData as $name => &$value ) {
1523 $field = $this->mFlatFields[$name];
1524 $value = $field->filter( $value, $this->mFlatFields );
1525 }
1526
1527 $this->mFieldData = $fieldData;
1528 }
1529
1530 /**
1531 * Stop a reset button being shown for this form
1532 *
1533 * @param bool $suppressReset Set to false to re-enable the button again
1534 *
1535 * @return HTMLForm $this for chaining calls (since 1.20)
1536 */
1537 function suppressReset( $suppressReset = true ) {
1538 $this->mShowReset = !$suppressReset;
1539
1540 return $this;
1541 }
1542
1543 /**
1544 * Overload this if you want to apply special filtration routines
1545 * to the form as a whole, after it's submitted but before it's
1546 * processed.
1547 *
1548 * @param array $data
1549 *
1550 * @return array
1551 */
1552 function filterDataForSubmit( $data ) {
1553 return $data;
1554 }
1555
1556 /**
1557 * Get a string to go in the "<legend>" of a section fieldset.
1558 * Override this if you want something more complicated.
1559 *
1560 * @param string $key
1561 *
1562 * @return string
1563 */
1564 public function getLegend( $key ) {
1565 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1566 }
1567
1568 /**
1569 * Set the value for the action attribute of the form.
1570 * When set to false (which is the default state), the set title is used.
1571 *
1572 * @since 1.19
1573 *
1574 * @param string|bool $action
1575 *
1576 * @return HTMLForm $this for chaining calls (since 1.20)
1577 */
1578 public function setAction( $action ) {
1579 $this->mAction = $action;
1580
1581 return $this;
1582 }
1583
1584 /**
1585 * Get the value for the action attribute of the form.
1586 *
1587 * @since 1.22
1588 *
1589 * @return string
1590 */
1591 public function getAction() {
1592 // If an action is alredy provided, return it
1593 if ( $this->mAction !== false ) {
1594 return $this->mAction;
1595 }
1596
1597 $articlePath = $this->getConfig()->get( 'ArticlePath' );
1598 // Check whether we are in GET mode and the ArticlePath contains a "?"
1599 // meaning that getLocalURL() would return something like "index.php?title=...".
1600 // As browser remove the query string before submitting GET forms,
1601 // it means that the title would be lost. In such case use wfScript() instead
1602 // and put title in an hidden field (see getHiddenFields()).
1603 if ( strpos( $articlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1604 return wfScript();
1605 }
1606
1607 return $this->getTitle()->getLocalURL();
1608 }
1609 }