Merge "Update documentation of what a "section" is"
[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 * Add the HTMLForm-specific JavaScript, if it hasn't been
309 * done already.
310 * @deprecated since 1.18 load modules with ResourceLoader instead
311 */
312 static function addJS() {
313 wfDeprecated( __METHOD__, '1.18' );
314 }
315
316 /**
317 * Get the HTMLFormField subclass for this descriptor.
318 *
319 * The descriptor can be passed either 'class' which is the name of
320 * a HTMLFormField subclass, or a shorter 'type' which is an alias.
321 * This makes sure the 'class' is always set, and also is returned by
322 * this function for ease.
323 *
324 * @since 1.23
325 *
326 * @param string $fieldname Name of the field
327 * @param array $descriptor Input Descriptor, as described above
328 *
329 * @throws MWException
330 * @return string Name of a HTMLFormField subclass
331 */
332 public static function getClassFromDescriptor( $fieldname, &$descriptor ) {
333 if ( isset( $descriptor['class'] ) ) {
334 $class = $descriptor['class'];
335 } elseif ( isset( $descriptor['type'] ) ) {
336 $class = self::$typeMappings[$descriptor['type']];
337 $descriptor['class'] = $class;
338 } else {
339 $class = null;
340 }
341
342 if ( !$class ) {
343 throw new MWException( "Descriptor with no class for $fieldname: "
344 . print_r( $descriptor, true ) );
345 }
346
347 return $class;
348 }
349
350 /**
351 * Initialise a new Object for the field
352 *
353 * @param string $fieldname Name of the field
354 * @param array $descriptor Input Descriptor, as described above
355 *
356 * @throws MWException
357 * @return HTMLFormField subclass
358 */
359 public static function loadInputFromParameters( $fieldname, $descriptor ) {
360 $class = self::getClassFromDescriptor( $fieldname, $descriptor );
361
362 $descriptor['fieldname'] = $fieldname;
363
364 # @todo This will throw a fatal error whenever someone try to use
365 # 'class' to feed a CSS class instead of 'cssclass'. Would be
366 # great to avoid the fatal error and show a nice error.
367 $obj = new $class( $descriptor );
368
369 return $obj;
370 }
371
372 /**
373 * Prepare form for submission.
374 *
375 * @attention When doing method chaining, that should be the very last
376 * method call before displayForm().
377 *
378 * @throws MWException
379 * @return HTMLForm $this for chaining calls (since 1.20)
380 */
381 function prepareForm() {
382 # Check if we have the info we need
383 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
384 throw new MWException( "You must call setTitle() on an HTMLForm" );
385 }
386
387 # Load data from the request.
388 $this->loadData();
389
390 return $this;
391 }
392
393 /**
394 * Try submitting, with edit token check first
395 * @return Status|bool
396 */
397 function tryAuthorizedSubmit() {
398 $result = false;
399
400 $submit = false;
401 if ( $this->getMethod() != 'post' ) {
402 $submit = true; // no session check needed
403 } elseif ( $this->getRequest()->wasPosted() ) {
404 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
405 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
406 // Session tokens for logged-out users have no security value.
407 // However, if the user gave one, check it in order to give a nice
408 // "session expired" error instead of "permission denied" or such.
409 $submit = $this->getUser()->matchEditToken( $editToken );
410 } else {
411 $submit = true;
412 }
413 }
414
415 if ( $submit ) {
416 $this->mWasSubmitted = true;
417 $result = $this->trySubmit();
418 }
419
420 return $result;
421 }
422
423 /**
424 * The here's-one-I-made-earlier option: do the submission if
425 * posted, or display the form with or without funky validation
426 * errors
427 * @return bool|Status Whether submission was successful.
428 */
429 function show() {
430 $this->prepareForm();
431
432 $result = $this->tryAuthorizedSubmit();
433 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
434 return $result;
435 }
436
437 $this->displayForm( $result );
438
439 return false;
440 }
441
442 /**
443 * Validate all the fields, and call the submission callback
444 * function if everything is kosher.
445 * @throws MWException
446 * @return mixed Bool true == Successful submission, Bool false
447 * == No submission attempted, anything else == Error to
448 * display.
449 */
450 function trySubmit() {
451 $this->mWasSubmitted = true;
452
453 # Check for cancelled submission
454 foreach ( $this->mFlatFields as $fieldname => $field ) {
455 if ( !empty( $field->mParams['nodata'] ) ) {
456 continue;
457 }
458 if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
459 $this->mWasSubmitted = false;
460 return false;
461 }
462 }
463
464 # Check for validation
465 foreach ( $this->mFlatFields as $fieldname => $field ) {
466 if ( !empty( $field->mParams['nodata'] ) ) {
467 continue;
468 }
469 if ( $field->validate(
470 $this->mFieldData[$fieldname],
471 $this->mFieldData )
472 !== true
473 ) {
474 return isset( $this->mValidationErrorMessage )
475 ? $this->mValidationErrorMessage
476 : array( 'htmlform-invalid-input' );
477 }
478 }
479
480 $callback = $this->mSubmitCallback;
481 if ( !is_callable( $callback ) ) {
482 throw new MWException( 'HTMLForm: no submit callback provided. Use ' .
483 'setSubmitCallback() to set one.' );
484 }
485
486 $data = $this->filterDataForSubmit( $this->mFieldData );
487
488 $res = call_user_func( $callback, $data, $this );
489 if ( $res === false ) {
490 $this->mWasSubmitted = false;
491 }
492
493 return $res;
494 }
495
496 /**
497 * Test whether the form was considered to have been submitted or not, i.e.
498 * whether the last call to tryAuthorizedSubmit or trySubmit returned
499 * non-false.
500 *
501 * This will return false until HTMLForm::tryAuthorizedSubmit or
502 * HTMLForm::trySubmit is called.
503 *
504 * @since 1.23
505 * @return bool
506 */
507 function wasSubmitted() {
508 return $this->mWasSubmitted;
509 }
510
511 /**
512 * Set a callback to a function to do something with the form
513 * once it's been successfully validated.
514 *
515 * @param string $cb Function name. The function will be passed
516 * the output from HTMLForm::filterDataForSubmit, and must
517 * return Bool true on success, Bool false if no submission
518 * was attempted, or String HTML output to display on error.
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 * Display the form (sending to the context's OutputPage object), with an
740 * appropriate error message or stack of messages, and any validation errors, etc.
741 *
742 * @attention You should call prepareForm() before calling this function.
743 * Moreover, when doing method chaining this should be the very last method
744 * call just after prepareForm().
745 *
746 * @param mixed $submitResult Mixed output from HTMLForm::trySubmit()
747 *
748 * @return Nothing, should be last call
749 */
750 function displayForm( $submitResult ) {
751 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
752 }
753
754 /**
755 * Returns the raw HTML generated by the form
756 *
757 * @param mixed $submitResult Mixed output from HTMLForm::trySubmit()
758 *
759 * @return string
760 */
761 function getHTML( $submitResult ) {
762 # For good measure (it is the default)
763 $this->getOutput()->preventClickjacking();
764 $this->getOutput()->addModules( 'mediawiki.htmlform' );
765 if ( $this->isVForm() ) {
766 $this->getOutput()->addModuleStyles( array(
767 'mediawiki.ui',
768 'mediawiki.ui.button',
769 ) );
770 // @todo Should vertical form set setWrapperLegend( false )
771 // to hide ugly fieldsets?
772 }
773
774 $html = ''
775 . $this->getErrors( $submitResult )
776 . $this->mHeader
777 . $this->getBody()
778 . $this->getHiddenFields()
779 . $this->getButtons()
780 . $this->mFooter;
781
782 $html = $this->wrapForm( $html );
783
784 return '' . $this->mPre . $html . $this->mPost;
785 }
786
787 /**
788 * Wrap the form innards in an actual "<form>" element
789 *
790 * @param string $html HTML contents to wrap.
791 *
792 * @return string Wrapped HTML.
793 */
794 function wrapForm( $html ) {
795
796 # Include a <fieldset> wrapper for style, if requested.
797 if ( $this->mWrapperLegend !== false ) {
798 $html = Xml::fieldset( $this->mWrapperLegend, $html );
799 }
800 # Use multipart/form-data
801 $encType = $this->mUseMultipart
802 ? 'multipart/form-data'
803 : 'application/x-www-form-urlencoded';
804 # Attributes
805 $attribs = array(
806 'action' => $this->getAction(),
807 'method' => $this->getMethod(),
808 'class' => array( 'visualClear' ),
809 'enctype' => $encType,
810 );
811 if ( !empty( $this->mId ) ) {
812 $attribs['id'] = $this->mId;
813 }
814
815 if ( $this->isVForm() ) {
816 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
817 }
818
819 return Html::rawElement( 'form', $attribs, $html );
820 }
821
822 /**
823 * Get the hidden fields that should go inside the form.
824 * @return string HTML.
825 */
826 function getHiddenFields() {
827 global $wgArticlePath;
828
829 $html = '';
830 if ( $this->getMethod() == 'post' ) {
831 $html .= Html::hidden(
832 'wpEditToken',
833 $this->getUser()->getEditToken(),
834 array( 'id' => 'wpEditToken' )
835 ) . "\n";
836 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
837 }
838
839 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
840 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
841 }
842
843 foreach ( $this->mHiddenFields as $data ) {
844 list( $value, $attribs ) = $data;
845 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
846 }
847
848 return $html;
849 }
850
851 /**
852 * Get the submit and (potentially) reset buttons.
853 * @return string HTML.
854 */
855 function getButtons() {
856 $buttons = '';
857
858 if ( $this->mShowSubmit ) {
859 $attribs = array();
860
861 if ( isset( $this->mSubmitID ) ) {
862 $attribs['id'] = $this->mSubmitID;
863 }
864
865 if ( isset( $this->mSubmitName ) ) {
866 $attribs['name'] = $this->mSubmitName;
867 }
868
869 if ( isset( $this->mSubmitTooltip ) ) {
870 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
871 }
872
873 $attribs['class'] = array( 'mw-htmlform-submit' );
874
875 if ( $this->isVForm() ) {
876 // mw-ui-block is necessary because the buttons aren't necessarily in an
877 // immediate child div of the vform.
878 // @todo Let client specify if the primary submit button is progressive or destructive
879 array_push(
880 $attribs['class'],
881 'mw-ui-button',
882 'mw-ui-big',
883 'mw-ui-constructive',
884 'mw-ui-block'
885 );
886 }
887
888 $buttons .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
889 }
890
891 if ( $this->mShowReset ) {
892 $buttons .= Html::element(
893 'input',
894 array(
895 'type' => 'reset',
896 'value' => $this->msg( 'htmlform-reset' )->text()
897 )
898 ) . "\n";
899 }
900
901 foreach ( $this->mButtons as $button ) {
902 $attrs = array(
903 'type' => 'submit',
904 'name' => $button['name'],
905 'value' => $button['value']
906 );
907
908 if ( $button['attribs'] ) {
909 $attrs += $button['attribs'];
910 }
911
912 if ( isset( $button['id'] ) ) {
913 $attrs['id'] = $button['id'];
914 }
915
916 $buttons .= Html::element( 'input', $attrs ) . "\n";
917 }
918
919 $html = Html::rawElement( 'span',
920 array( 'class' => 'mw-htmlform-submit-buttons' ), "\n$buttons" ) . "\n";
921
922 // Buttons are top-level form elements in table and div layouts,
923 // but vform wants all elements inside divs to get spaced-out block
924 // styling.
925 if ( $this->mShowSubmit && $this->isVForm() ) {
926 $html = Html::rawElement( 'div', null, "\n$html" ) . "\n";
927 }
928
929 return $html;
930 }
931
932 /**
933 * Get the whole body of the form.
934 * @return string
935 */
936 function getBody() {
937 return $this->displaySection( $this->mFieldTree, $this->mTableId );
938 }
939
940 /**
941 * Format and display an error message stack.
942 *
943 * @param string|array|Status $errors
944 *
945 * @return string
946 */
947 function getErrors( $errors ) {
948 if ( $errors instanceof Status ) {
949 if ( $errors->isOK() ) {
950 $errorstr = '';
951 } else {
952 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
953 }
954 } elseif ( is_array( $errors ) ) {
955 $errorstr = $this->formatErrors( $errors );
956 } else {
957 $errorstr = $errors;
958 }
959
960 return $errorstr
961 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
962 : '';
963 }
964
965 /**
966 * Format a stack of error messages into a single HTML string
967 *
968 * @param array $errors of message keys/values
969 *
970 * @return string HTML, a "<ul>" list of errors
971 */
972 public static function formatErrors( $errors ) {
973 $errorstr = '';
974
975 foreach ( $errors as $error ) {
976 if ( is_array( $error ) ) {
977 $msg = array_shift( $error );
978 } else {
979 $msg = $error;
980 $error = array();
981 }
982
983 $errorstr .= Html::rawElement(
984 'li',
985 array(),
986 wfMessage( $msg, $error )->parse()
987 );
988 }
989
990 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
991
992 return $errorstr;
993 }
994
995 /**
996 * Set the text for the submit button
997 *
998 * @param string $t plaintext.
999 *
1000 * @return HTMLForm $this for chaining calls (since 1.20)
1001 */
1002 function setSubmitText( $t ) {
1003 $this->mSubmitText = $t;
1004
1005 return $this;
1006 }
1007
1008 /**
1009 * Set the text for the submit button to a message
1010 * @since 1.19
1011 *
1012 * @param string $msg Message key
1013 *
1014 * @return HTMLForm $this for chaining calls (since 1.20)
1015 */
1016 public function setSubmitTextMsg( $msg ) {
1017 $this->setSubmitText( $this->msg( $msg )->text() );
1018
1019 return $this;
1020 }
1021
1022 /**
1023 * Get the text for the submit button, either customised or a default.
1024 * @return string
1025 */
1026 function getSubmitText() {
1027 return $this->mSubmitText
1028 ? $this->mSubmitText
1029 : $this->msg( 'htmlform-submit' )->text();
1030 }
1031
1032 /**
1033 * @param string $name Submit button name
1034 *
1035 * @return HTMLForm $this for chaining calls (since 1.20)
1036 */
1037 public function setSubmitName( $name ) {
1038 $this->mSubmitName = $name;
1039
1040 return $this;
1041 }
1042
1043 /**
1044 * @param string $name Tooltip for the submit button
1045 *
1046 * @return HTMLForm $this for chaining calls (since 1.20)
1047 */
1048 public function setSubmitTooltip( $name ) {
1049 $this->mSubmitTooltip = $name;
1050
1051 return $this;
1052 }
1053
1054 /**
1055 * Set the id for the submit button.
1056 *
1057 * @param string $t
1058 *
1059 * @todo FIXME: Integrity of $t is *not* validated
1060 * @return HTMLForm $this for chaining calls (since 1.20)
1061 */
1062 function setSubmitID( $t ) {
1063 $this->mSubmitID = $t;
1064
1065 return $this;
1066 }
1067
1068 /**
1069 * Stop a default submit button being shown for this form. This implies that an
1070 * alternate submit method must be provided manually.
1071 *
1072 * @since 1.22
1073 *
1074 * @param bool $suppressSubmit Set to false to re-enable the button again
1075 *
1076 * @return HTMLForm $this for chaining calls
1077 */
1078 function suppressDefaultSubmit( $suppressSubmit = true ) {
1079 $this->mShowSubmit = !$suppressSubmit;
1080
1081 return $this;
1082 }
1083
1084 /**
1085 * Set the id of the \<table\> or outermost \<div\> element.
1086 *
1087 * @since 1.22
1088 *
1089 * @param string $id New value of the id attribute, or "" to remove
1090 *
1091 * @return HTMLForm $this for chaining calls
1092 */
1093 public function setTableId( $id ) {
1094 $this->mTableId = $id;
1095
1096 return $this;
1097 }
1098
1099 /**
1100 * @param string $id DOM id for the form
1101 *
1102 * @return HTMLForm $this for chaining calls (since 1.20)
1103 */
1104 public function setId( $id ) {
1105 $this->mId = $id;
1106
1107 return $this;
1108 }
1109
1110 /**
1111 * Prompt the whole form to be wrapped in a "<fieldset>", with
1112 * this text as its "<legend>" element.
1113 *
1114 * @param string|bool $legend HTML to go inside the "<legend>" element, or
1115 * false for no <legend>
1116 * Will be escaped
1117 *
1118 * @return HTMLForm $this for chaining calls (since 1.20)
1119 */
1120 public function setWrapperLegend( $legend ) {
1121 $this->mWrapperLegend = $legend;
1122
1123 return $this;
1124 }
1125
1126 /**
1127 * Prompt the whole form to be wrapped in a "<fieldset>", with
1128 * this message as its "<legend>" element.
1129 * @since 1.19
1130 *
1131 * @param string $msg Message key
1132 *
1133 * @return HTMLForm $this for chaining calls (since 1.20)
1134 */
1135 public function setWrapperLegendMsg( $msg ) {
1136 $this->setWrapperLegend( $this->msg( $msg )->text() );
1137
1138 return $this;
1139 }
1140
1141 /**
1142 * Set the prefix for various default messages
1143 * @todo Currently only used for the "<fieldset>" legend on forms
1144 * with multiple sections; should be used elsewhere?
1145 *
1146 * @param string $p
1147 *
1148 * @return HTMLForm $this for chaining calls (since 1.20)
1149 */
1150 function setMessagePrefix( $p ) {
1151 $this->mMessagePrefix = $p;
1152
1153 return $this;
1154 }
1155
1156 /**
1157 * Set the title for form submission
1158 *
1159 * @param Title $t Title of page the form is on/should be posted to
1160 *
1161 * @return HTMLForm $this for chaining calls (since 1.20)
1162 */
1163 function setTitle( $t ) {
1164 $this->mTitle = $t;
1165
1166 return $this;
1167 }
1168
1169 /**
1170 * Get the title
1171 * @return Title
1172 */
1173 function getTitle() {
1174 return $this->mTitle === false
1175 ? $this->getContext()->getTitle()
1176 : $this->mTitle;
1177 }
1178
1179 /**
1180 * Set the method used to submit the form
1181 *
1182 * @param string $method
1183 *
1184 * @return HTMLForm $this for chaining calls (since 1.20)
1185 */
1186 public function setMethod( $method = 'post' ) {
1187 $this->mMethod = $method;
1188
1189 return $this;
1190 }
1191
1192 public function getMethod() {
1193 return $this->mMethod;
1194 }
1195
1196 /**
1197 * @todo Document
1198 *
1199 * @param array[]|HTMLFormField[] $fields Array of fields (either arrays or
1200 * objects).
1201 * @param string $sectionName ID attribute of the "<table>" tag for this
1202 * section, ignored if empty.
1203 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of
1204 * each subsection, ignored if empty.
1205 * @param bool &$hasUserVisibleFields Whether the section had user-visible fields.
1206 *
1207 * @return string
1208 */
1209 public function displaySection( $fields,
1210 $sectionName = '',
1211 $fieldsetIDPrefix = '',
1212 &$hasUserVisibleFields = false ) {
1213 $displayFormat = $this->getDisplayFormat();
1214
1215 $html = '';
1216 $subsectionHtml = '';
1217 $hasLabel = false;
1218
1219 switch ( $displayFormat ) {
1220 case 'table':
1221 $getFieldHtmlMethod = 'getTableRow';
1222 break;
1223 case 'vform':
1224 // Close enough to a div.
1225 $getFieldHtmlMethod = 'getDiv';
1226 break;
1227 default:
1228 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1229 }
1230
1231 foreach ( $fields as $key => $value ) {
1232 if ( $value instanceof HTMLFormField ) {
1233 $v = empty( $value->mParams['nodata'] )
1234 ? $this->mFieldData[$key]
1235 : $value->getDefault();
1236 $html .= $value->$getFieldHtmlMethod( $v );
1237
1238 $labelValue = trim( $value->getLabel() );
1239 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1240 $hasLabel = true;
1241 }
1242
1243 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1244 get_class( $value ) !== 'HTMLApiField'
1245 ) {
1246 $hasUserVisibleFields = true;
1247 }
1248 } elseif ( is_array( $value ) ) {
1249 $subsectionHasVisibleFields = false;
1250 $section =
1251 $this->displaySection( $value,
1252 "mw-htmlform-$key",
1253 "$fieldsetIDPrefix$key-",
1254 $subsectionHasVisibleFields );
1255 $legend = null;
1256
1257 if ( $subsectionHasVisibleFields === true ) {
1258 // Display the section with various niceties.
1259 $hasUserVisibleFields = true;
1260
1261 $legend = $this->getLegend( $key );
1262
1263 if ( isset( $this->mSectionHeaders[$key] ) ) {
1264 $section = $this->mSectionHeaders[$key] . $section;
1265 }
1266 if ( isset( $this->mSectionFooters[$key] ) ) {
1267 $section .= $this->mSectionFooters[$key];
1268 }
1269
1270 $attributes = array();
1271 if ( $fieldsetIDPrefix ) {
1272 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1273 }
1274 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1275 } else {
1276 // Just return the inputs, nothing fancy.
1277 $subsectionHtml .= $section;
1278 }
1279 }
1280 }
1281
1282 if ( $displayFormat !== 'raw' ) {
1283 $classes = array();
1284
1285 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1286 $classes[] = 'mw-htmlform-nolabel';
1287 }
1288
1289 $attribs = array(
1290 'class' => implode( ' ', $classes ),
1291 );
1292
1293 if ( $sectionName ) {
1294 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1295 }
1296
1297 if ( $displayFormat === 'table' ) {
1298 $html = Html::rawElement( 'table',
1299 $attribs,
1300 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1301 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1302 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1303 }
1304 }
1305
1306 if ( $this->mSubSectionBeforeFields ) {
1307 return $subsectionHtml . "\n" . $html;
1308 } else {
1309 return $html . "\n" . $subsectionHtml;
1310 }
1311 }
1312
1313 /**
1314 * Construct the form fields from the Descriptor array
1315 */
1316 function loadData() {
1317 $fieldData = array();
1318
1319 foreach ( $this->mFlatFields as $fieldname => $field ) {
1320 if ( !empty( $field->mParams['nodata'] ) ) {
1321 continue;
1322 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1323 $fieldData[$fieldname] = $field->getDefault();
1324 } else {
1325 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1326 }
1327 }
1328
1329 # Filter data.
1330 foreach ( $fieldData as $name => &$value ) {
1331 $field = $this->mFlatFields[$name];
1332 $value = $field->filter( $value, $this->mFlatFields );
1333 }
1334
1335 $this->mFieldData = $fieldData;
1336 }
1337
1338 /**
1339 * Stop a reset button being shown for this form
1340 *
1341 * @param bool $suppressReset Set to false to re-enable the button again
1342 *
1343 * @return HTMLForm $this for chaining calls (since 1.20)
1344 */
1345 function suppressReset( $suppressReset = true ) {
1346 $this->mShowReset = !$suppressReset;
1347
1348 return $this;
1349 }
1350
1351 /**
1352 * Overload this if you want to apply special filtration routines
1353 * to the form as a whole, after it's submitted but before it's
1354 * processed.
1355 *
1356 * @param array $data
1357 *
1358 * @return
1359 */
1360 function filterDataForSubmit( $data ) {
1361 return $data;
1362 }
1363
1364 /**
1365 * Get a string to go in the "<legend>" of a section fieldset.
1366 * Override this if you want something more complicated.
1367 *
1368 * @param string $key
1369 *
1370 * @return string
1371 */
1372 public function getLegend( $key ) {
1373 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1374 }
1375
1376 /**
1377 * Set the value for the action attribute of the form.
1378 * When set to false (which is the default state), the set title is used.
1379 *
1380 * @since 1.19
1381 *
1382 * @param string|bool $action
1383 *
1384 * @return HTMLForm $this for chaining calls (since 1.20)
1385 */
1386 public function setAction( $action ) {
1387 $this->mAction = $action;
1388
1389 return $this;
1390 }
1391
1392 /**
1393 * Get the value for the action attribute of the form.
1394 *
1395 * @since 1.22
1396 *
1397 * @return string
1398 */
1399 public function getAction() {
1400 global $wgScript, $wgArticlePath;
1401
1402 // If an action is alredy provided, return it
1403 if ( $this->mAction !== false ) {
1404 return $this->mAction;
1405 }
1406
1407 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1408 // meaning that getLocalURL() would return something like "index.php?title=...".
1409 // As browser remove the query string before submitting GET forms,
1410 // it means that the title would be lost. In such case use $wgScript instead
1411 // and put title in an hidden field (see getHiddenFields()).
1412 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1413 return $wgScript;
1414 }
1415
1416 return $this->getTitle()->getLocalURL();
1417 }
1418 }