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