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