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