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