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