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