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