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