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