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