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