Merge "Cosmetic change: add a new line after a section title."
[lhc/web/wiklou.git] / includes / HTMLForm.php
1 <?php
2 /**
3 * HTML form generation and submission handling.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Object handling generic submission, CSRF protection, layout and
25 * other logic for UI forms. in a reusable manner.
26 *
27 * In order to generate the form, the HTMLForm object takes an array
28 * structure detailing the form fields available. Each element of the
29 * array is a basic property-list, including the type of field, the
30 * label it is to be given in the form, callbacks for validation and
31 * 'filtering', and other pertinent information.
32 *
33 * Field types are implemented as subclasses of the generic HTMLFormField
34 * object, and typically implement at least getInputHTML, which generates
35 * the HTML for the input field to be placed in the table.
36 *
37 * The constructor input is an associative array of $fieldname => $info,
38 * where $info is an Associative Array with any of the following:
39 *
40 * 'class' -- the subclass of HTMLFormField that will be used
41 * to create the object. *NOT* the CSS class!
42 * 'type' -- roughly translates into the <select> type attribute.
43 * if 'class' is not specified, this is used as a map
44 * through HTMLForm::$typeMappings to get the class name.
45 * 'default' -- default value when the form is displayed
46 * 'id' -- HTML id attribute
47 * 'cssclass' -- CSS class
48 * 'options' -- varies according to the specific object.
49 * 'label-message' -- message key for a message to use as the label.
50 * can be an array of msg key and then parameters to
51 * the message.
52 * 'label' -- alternatively, a raw text message. Overridden by
53 * label-message
54 * 'help' -- message text for a message to use as a help text.
55 * 'help-message' -- message key for a message to use as a help text.
56 * can be an array of msg key and then parameters to
57 * the message.
58 * Overwrites 'help-messages' and 'help'.
59 * 'help-messages' -- array of message key. As above, each item can
60 * be an array of msg key and then parameters.
61 * Overwrites 'help'.
62 * 'required' -- passed through to the object, indicating that it
63 * is a required field.
64 * 'size' -- the length of text fields
65 * 'filter-callback -- a function name to give you the chance to
66 * massage the inputted value before it's processed.
67 * @see HTMLForm::filter()
68 * 'validation-callback' -- a function name to give you the chance
69 * to impose extra validation on the field input.
70 * @see HTMLForm::validate()
71 * 'name' -- By default, the 'name' attribute of the input field
72 * is "wp{$fieldname}". If you want a different name
73 * (eg one without the "wp" prefix), specify it here and
74 * it will be used without modification.
75 *
76 * TODO: Document 'section' / 'subsection' stuff
77 */
78 class HTMLForm extends ContextSource {
79
80 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
81 static $typeMappings = array(
82 'text' => 'HTMLTextField',
83 'textarea' => 'HTMLTextAreaField',
84 'select' => 'HTMLSelectField',
85 'radio' => 'HTMLRadioField',
86 'multiselect' => 'HTMLMultiSelectField',
87 'check' => 'HTMLCheckField',
88 'toggle' => 'HTMLCheckField',
89 'int' => 'HTMLIntField',
90 'float' => 'HTMLFloatField',
91 'info' => 'HTMLInfoField',
92 'selectorother' => 'HTMLSelectOrOtherField',
93 'selectandother' => 'HTMLSelectAndOtherField',
94 'submit' => 'HTMLSubmitField',
95 'hidden' => 'HTMLHiddenField',
96 'edittools' => 'HTMLEditTools',
97
98 // HTMLTextField will output the correct type="" attribute automagically.
99 // There are about four zillion other HTML5 input types, like url, but
100 // we don't use those at the moment, so no point in adding all of them.
101 'email' => 'HTMLTextField',
102 'password' => 'HTMLTextField',
103 );
104
105 protected $mMessagePrefix;
106
107 /** @var HTMLFormField[] */
108 protected $mFlatFields;
109
110 protected $mFieldTree;
111 protected $mShowReset = false;
112 public $mFieldData;
113
114 protected $mSubmitCallback;
115 protected $mValidationErrorMessage;
116
117 protected $mPre = '';
118 protected $mHeader = '';
119 protected $mFooter = '';
120 protected $mSectionHeaders = array();
121 protected $mSectionFooters = array();
122 protected $mPost = '';
123 protected $mId;
124
125 protected $mSubmitID;
126 protected $mSubmitName;
127 protected $mSubmitText;
128 protected $mSubmitTooltip;
129
130 protected $mTitle;
131 protected $mMethod = 'post';
132
133 /**
134 * Form action URL. false means we will use the URL to set Title
135 * @since 1.19
136 * @var bool|string
137 */
138 protected $mAction = false;
139
140 protected $mUseMultipart = false;
141 protected $mHiddenFields = array();
142 protected $mButtons = array();
143
144 protected $mWrapperLegend = false;
145
146 /**
147 * If true, sections that contain both fields and subsections will
148 * render their subsections before their fields.
149 *
150 * Subclasses may set this to false to render subsections after fields
151 * instead.
152 */
153 protected $mSubSectionBeforeFields = true;
154
155 /**
156 * Build a new HTMLForm from an array of field attributes
157 * @param $descriptor Array of Field constructs, as described above
158 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
159 * Obviates the need to call $form->setTitle()
160 * @param $messagePrefix String a prefix to go in front of default messages
161 */
162 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
163 if( $context instanceof IContextSource ){
164 $this->setContext( $context );
165 $this->mTitle = false; // We don't need them to set a title
166 $this->mMessagePrefix = $messagePrefix;
167 } else {
168 // B/C since 1.18
169 if( is_string( $context ) && $messagePrefix === '' ){
170 // it's actually $messagePrefix
171 $this->mMessagePrefix = $context;
172 }
173 }
174
175 // Expand out into a tree.
176 $loadedDescriptor = array();
177 $this->mFlatFields = array();
178
179 foreach ( $descriptor as $fieldname => $info ) {
180 $section = isset( $info['section'] )
181 ? $info['section']
182 : '';
183
184 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
185 $this->mUseMultipart = true;
186 }
187
188 $field = self::loadInputFromParameters( $fieldname, $info );
189 $field->mParent = $this;
190
191 $setSection =& $loadedDescriptor;
192 if ( $section ) {
193 $sectionParts = explode( '/', $section );
194
195 while ( count( $sectionParts ) ) {
196 $newName = array_shift( $sectionParts );
197
198 if ( !isset( $setSection[$newName] ) ) {
199 $setSection[$newName] = array();
200 }
201
202 $setSection =& $setSection[$newName];
203 }
204 }
205
206 $setSection[$fieldname] = $field;
207 $this->mFlatFields[$fieldname] = $field;
208 }
209
210 $this->mFieldTree = $loadedDescriptor;
211 }
212
213 /**
214 * Add the HTMLForm-specific JavaScript, if it hasn't been
215 * done already.
216 * @deprecated since 1.18 load modules with ResourceLoader instead
217 */
218 static function addJS() { wfDeprecated( __METHOD__, '1.18' ); }
219
220 /**
221 * Initialise a new Object for the field
222 * @param $fieldname string
223 * @param $descriptor string input Descriptor, as described above
224 * @return HTMLFormField subclass
225 */
226 static function loadInputFromParameters( $fieldname, $descriptor ) {
227 if ( isset( $descriptor['class'] ) ) {
228 $class = $descriptor['class'];
229 } elseif ( isset( $descriptor['type'] ) ) {
230 $class = self::$typeMappings[$descriptor['type']];
231 $descriptor['class'] = $class;
232 } else {
233 $class = null;
234 }
235
236 if ( !$class ) {
237 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
238 }
239
240 $descriptor['fieldname'] = $fieldname;
241
242 # TODO
243 # This will throw a fatal error whenever someone try to use
244 # 'class' to feed a CSS class instead of 'cssclass'. Would be
245 # great to avoid the fatal error and show a nice error.
246 $obj = new $class( $descriptor );
247
248 return $obj;
249 }
250
251 /**
252 * Prepare form for submission
253 */
254 function prepareForm() {
255 # Check if we have the info we need
256 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
257 throw new MWException( "You must call setTitle() on an HTMLForm" );
258 }
259
260 # Load data from the request.
261 $this->loadData();
262 }
263
264 /**
265 * Try submitting, with edit token check first
266 * @return Status|boolean
267 */
268 function tryAuthorizedSubmit() {
269 $result = false;
270
271 $submit = false;
272 if ( $this->getMethod() != 'post' ) {
273 $submit = true; // no session check needed
274 } elseif ( $this->getRequest()->wasPosted() ) {
275 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
276 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
277 // Session tokens for logged-out users have no security value.
278 // However, if the user gave one, check it in order to give a nice
279 // "session expired" error instead of "permission denied" or such.
280 $submit = $this->getUser()->matchEditToken( $editToken );
281 } else {
282 $submit = true;
283 }
284 }
285
286 if ( $submit ) {
287 $result = $this->trySubmit();
288 }
289
290 return $result;
291 }
292
293 /**
294 * The here's-one-I-made-earlier option: do the submission if
295 * posted, or display the form with or without funky validation
296 * errors
297 * @return Bool or Status whether submission was successful.
298 */
299 function show() {
300 $this->prepareForm();
301
302 $result = $this->tryAuthorizedSubmit();
303 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
304 return $result;
305 }
306
307 $this->displayForm( $result );
308 return false;
309 }
310
311 /**
312 * Validate all the fields, and call the submision callback
313 * function if everything is kosher.
314 * @return Mixed Bool true == Successful submission, Bool false
315 * == No submission attempted, anything else == Error to
316 * display.
317 */
318 function trySubmit() {
319 # Check for validation
320 foreach ( $this->mFlatFields as $fieldname => $field ) {
321 if ( !empty( $field->mParams['nodata'] ) ) {
322 continue;
323 }
324 if ( $field->validate(
325 $this->mFieldData[$fieldname],
326 $this->mFieldData )
327 !== true
328 ) {
329 return isset( $this->mValidationErrorMessage )
330 ? $this->mValidationErrorMessage
331 : array( 'htmlform-invalid-input' );
332 }
333 }
334
335 $callback = $this->mSubmitCallback;
336
337 $data = $this->filterDataForSubmit( $this->mFieldData );
338
339 $res = call_user_func( $callback, $data, $this );
340
341 return $res;
342 }
343
344 /**
345 * Set a callback to a function to do something with the form
346 * once it's been successfully validated.
347 * @param $cb String function name. The function will be passed
348 * the output from HTMLForm::filterDataForSubmit, and must
349 * return Bool true on success, Bool false if no submission
350 * was attempted, or String HTML output to display on error.
351 */
352 function setSubmitCallback( $cb ) {
353 $this->mSubmitCallback = $cb;
354 }
355
356 /**
357 * Set a message to display on a validation error.
358 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
359 * (so each entry can be either a String or Array)
360 */
361 function setValidationErrorMessage( $msg ) {
362 $this->mValidationErrorMessage = $msg;
363 }
364
365 /**
366 * Set the introductory message, overwriting any existing message.
367 * @param $msg String complete text of message to display
368 */
369 function setIntro( $msg ) {
370 $this->setPreText( $msg );
371 }
372
373 /**
374 * Set the introductory message, overwriting any existing message.
375 * @since 1.19
376 * @param $msg String complete text of message to display
377 */
378 function setPreText( $msg ) { $this->mPre = $msg; }
379
380 /**
381 * Add introductory text.
382 * @param $msg String complete text of message to display
383 */
384 function addPreText( $msg ) { $this->mPre .= $msg; }
385
386 /**
387 * Add header text, inside the form.
388 * @param $msg String complete text of message to display
389 * @param $section string The section to add the header to
390 */
391 function addHeaderText( $msg, $section = null ) {
392 if ( is_null( $section ) ) {
393 $this->mHeader .= $msg;
394 } else {
395 if ( !isset( $this->mSectionHeaders[$section] ) ) {
396 $this->mSectionHeaders[$section] = '';
397 }
398 $this->mSectionHeaders[$section] .= $msg;
399 }
400 }
401
402 /**
403 * Set header text, inside the form.
404 * @since 1.19
405 * @param $msg String complete text of message to display
406 * @param $section The section to add the header to
407 */
408 function setHeaderText( $msg, $section = null ) {
409 if ( is_null( $section ) ) {
410 $this->mHeader = $msg;
411 } else {
412 $this->mSectionHeaders[$section] = $msg;
413 }
414 }
415
416 /**
417 * Add footer text, inside the form.
418 * @param $msg String complete text of message to display
419 * @param $section string The section to add the footer text to
420 */
421 function addFooterText( $msg, $section = null ) {
422 if ( is_null( $section ) ) {
423 $this->mFooter .= $msg;
424 } else {
425 if ( !isset( $this->mSectionFooters[$section] ) ) {
426 $this->mSectionFooters[$section] = '';
427 }
428 $this->mSectionFooters[$section] .= $msg;
429 }
430 }
431
432 /**
433 * Set footer text, inside the form.
434 * @since 1.19
435 * @param $msg String complete text of message to display
436 * @param $section string The section to add the footer text to
437 */
438 function setFooterText( $msg, $section = null ) {
439 if ( is_null( $section ) ) {
440 $this->mFooter = $msg;
441 } else {
442 $this->mSectionFooters[$section] = $msg;
443 }
444 }
445
446 /**
447 * Add text to the end of the display.
448 * @param $msg String complete text of message to display
449 */
450 function addPostText( $msg ) { $this->mPost .= $msg; }
451
452 /**
453 * Set text at the end of the display.
454 * @param $msg String complete text of message to display
455 */
456 function setPostText( $msg ) { $this->mPost = $msg; }
457
458 /**
459 * Add a hidden field to the output
460 * @param $name String field name. This will be used exactly as entered
461 * @param $value String field value
462 * @param $attribs Array
463 */
464 public function addHiddenField( $name, $value, $attribs = array() ) {
465 $attribs += array( 'name' => $name );
466 $this->mHiddenFields[] = array( $value, $attribs );
467 }
468
469 public function addButton( $name, $value, $id = null, $attribs = null ) {
470 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
471 }
472
473 /**
474 * Display the form (sending to $wgOut), with an appropriate error
475 * message or stack of messages, and any validation errors, etc.
476 * @param $submitResult Mixed output from HTMLForm::trySubmit()
477 */
478 function displayForm( $submitResult ) {
479 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
480 }
481
482 /**
483 * Returns the raw HTML generated by the form
484 * @param $submitResult Mixed output from HTMLForm::trySubmit()
485 * @return string
486 */
487 function getHTML( $submitResult ) {
488 # For good measure (it is the default)
489 $this->getOutput()->preventClickjacking();
490 $this->getOutput()->addModules( 'mediawiki.htmlform' );
491
492 $html = ''
493 . $this->getErrors( $submitResult )
494 . $this->mHeader
495 . $this->getBody()
496 . $this->getHiddenFields()
497 . $this->getButtons()
498 . $this->mFooter
499 ;
500
501 $html = $this->wrapForm( $html );
502
503 return '' . $this->mPre . $html . $this->mPost;
504 }
505
506 /**
507 * Wrap the form innards in an actual <form> element
508 * @param $html String HTML contents to wrap.
509 * @return String wrapped HTML.
510 */
511 function wrapForm( $html ) {
512
513 # Include a <fieldset> wrapper for style, if requested.
514 if ( $this->mWrapperLegend !== false ) {
515 $html = Xml::fieldset( $this->mWrapperLegend, $html );
516 }
517 # Use multipart/form-data
518 $encType = $this->mUseMultipart
519 ? 'multipart/form-data'
520 : 'application/x-www-form-urlencoded';
521 # Attributes
522 $attribs = array(
523 'action' => $this->mAction === false ? $this->getTitle()->getFullURL() : $this->mAction,
524 'method' => $this->mMethod,
525 'class' => 'visualClear',
526 'enctype' => $encType,
527 );
528 if ( !empty( $this->mId ) ) {
529 $attribs['id'] = $this->mId;
530 }
531
532 return Html::rawElement( 'form', $attribs, $html );
533 }
534
535 /**
536 * Get the hidden fields that should go inside the form.
537 * @return String HTML.
538 */
539 function getHiddenFields() {
540 global $wgArticlePath;
541
542 $html = '';
543 if( $this->getMethod() == 'post' ){
544 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
545 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
546 }
547
548 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
549 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
550 }
551
552 foreach ( $this->mHiddenFields as $data ) {
553 list( $value, $attribs ) = $data;
554 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
555 }
556
557 return $html;
558 }
559
560 /**
561 * Get the submit and (potentially) reset buttons.
562 * @return String HTML.
563 */
564 function getButtons() {
565 $html = '';
566 $attribs = array();
567
568 if ( isset( $this->mSubmitID ) ) {
569 $attribs['id'] = $this->mSubmitID;
570 }
571
572 if ( isset( $this->mSubmitName ) ) {
573 $attribs['name'] = $this->mSubmitName;
574 }
575
576 if ( isset( $this->mSubmitTooltip ) ) {
577 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
578 }
579
580 $attribs['class'] = 'mw-htmlform-submit';
581
582 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
583
584 if ( $this->mShowReset ) {
585 $html .= Html::element(
586 'input',
587 array(
588 'type' => 'reset',
589 'value' => wfMsg( 'htmlform-reset' )
590 )
591 ) . "\n";
592 }
593
594 foreach ( $this->mButtons as $button ) {
595 $attrs = array(
596 'type' => 'submit',
597 'name' => $button['name'],
598 'value' => $button['value']
599 );
600
601 if ( $button['attribs'] ) {
602 $attrs += $button['attribs'];
603 }
604
605 if ( isset( $button['id'] ) ) {
606 $attrs['id'] = $button['id'];
607 }
608
609 $html .= Html::element( 'input', $attrs );
610 }
611
612 return $html;
613 }
614
615 /**
616 * Get the whole body of the form.
617 * @return String
618 */
619 function getBody() {
620 return $this->displaySection( $this->mFieldTree );
621 }
622
623 /**
624 * Format and display an error message stack.
625 * @param $errors String|Array|Status
626 * @return String
627 */
628 function getErrors( $errors ) {
629 if ( $errors instanceof Status ) {
630 if ( $errors->isOK() ) {
631 $errorstr = '';
632 } else {
633 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
634 }
635 } elseif ( is_array( $errors ) ) {
636 $errorstr = $this->formatErrors( $errors );
637 } else {
638 $errorstr = $errors;
639 }
640
641 return $errorstr
642 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
643 : '';
644 }
645
646 /**
647 * Format a stack of error messages into a single HTML string
648 * @param $errors Array of message keys/values
649 * @return String HTML, a <ul> list of errors
650 */
651 public static function formatErrors( $errors ) {
652 $errorstr = '';
653
654 foreach ( $errors as $error ) {
655 if ( is_array( $error ) ) {
656 $msg = array_shift( $error );
657 } else {
658 $msg = $error;
659 $error = array();
660 }
661
662 $errorstr .= Html::rawElement(
663 'li',
664 array(),
665 wfMsgExt( $msg, array( 'parseinline' ), $error )
666 );
667 }
668
669 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
670
671 return $errorstr;
672 }
673
674 /**
675 * Set the text for the submit button
676 * @param $t String plaintext.
677 */
678 function setSubmitText( $t ) {
679 $this->mSubmitText = $t;
680 }
681
682 /**
683 * Set the text for the submit button to a message
684 * @since 1.19
685 * @param $msg String message key
686 */
687 public function setSubmitTextMsg( $msg ) {
688 return $this->setSubmitText( $this->msg( $msg )->text() );
689 }
690
691 /**
692 * Get the text for the submit button, either customised or a default.
693 * @return string
694 */
695 function getSubmitText() {
696 return $this->mSubmitText
697 ? $this->mSubmitText
698 : wfMsg( 'htmlform-submit' );
699 }
700
701 public function setSubmitName( $name ) {
702 $this->mSubmitName = $name;
703 }
704
705 public function setSubmitTooltip( $name ) {
706 $this->mSubmitTooltip = $name;
707 }
708
709 /**
710 * Set the id for the submit button.
711 * @param $t String.
712 * @todo FIXME: Integrity of $t is *not* validated
713 */
714 function setSubmitID( $t ) {
715 $this->mSubmitID = $t;
716 }
717
718 public function setId( $id ) {
719 $this->mId = $id;
720 }
721 /**
722 * Prompt the whole form to be wrapped in a <fieldset>, with
723 * this text as its <legend> element.
724 * @param $legend String HTML to go inside the <legend> element.
725 * Will be escaped
726 */
727 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
728
729 /**
730 * Prompt the whole form to be wrapped in a <fieldset>, with
731 * this message as its <legend> element.
732 * @since 1.19
733 * @param $msg String message key
734 */
735 public function setWrapperLegendMsg( $msg ) {
736 return $this->setWrapperLegend( $this->msg( $msg )->escaped() );
737 }
738
739 /**
740 * Set the prefix for various default messages
741 * TODO: currently only used for the <fieldset> legend on forms
742 * with multiple sections; should be used elsewhre?
743 * @param $p String
744 */
745 function setMessagePrefix( $p ) {
746 $this->mMessagePrefix = $p;
747 }
748
749 /**
750 * Set the title for form submission
751 * @param $t Title of page the form is on/should be posted to
752 */
753 function setTitle( $t ) {
754 $this->mTitle = $t;
755 }
756
757 /**
758 * Get the title
759 * @return Title
760 */
761 function getTitle() {
762 return $this->mTitle === false
763 ? $this->getContext()->getTitle()
764 : $this->mTitle;
765 }
766
767 /**
768 * Set the method used to submit the form
769 * @param $method String
770 */
771 public function setMethod( $method = 'post' ) {
772 $this->mMethod = $method;
773 }
774
775 public function getMethod() {
776 return $this->mMethod;
777 }
778
779 /**
780 * TODO: Document
781 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
782 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
783 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
784 * @return String
785 */
786 function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
787 $tableHtml = '';
788 $subsectionHtml = '';
789 $hasLeftColumn = false;
790
791 foreach ( $fields as $key => $value ) {
792 if ( is_object( $value ) ) {
793 $v = empty( $value->mParams['nodata'] )
794 ? $this->mFieldData[$key]
795 : $value->getDefault();
796 $tableHtml .= $value->getTableRow( $v );
797
798 if ( $value->getLabel() != '&#160;' ) {
799 $hasLeftColumn = true;
800 }
801 } elseif ( is_array( $value ) ) {
802 $section = $this->displaySection( $value, $key );
803 $legend = $this->getLegend( $key );
804 if ( isset( $this->mSectionHeaders[$key] ) ) {
805 $section = $this->mSectionHeaders[$key] . $section;
806 }
807 if ( isset( $this->mSectionFooters[$key] ) ) {
808 $section .= $this->mSectionFooters[$key];
809 }
810 $attributes = array();
811 if ( $fieldsetIDPrefix ) {
812 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
813 }
814 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
815 }
816 }
817
818 $classes = array();
819
820 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
821 $classes[] = 'mw-htmlform-nolabel';
822 }
823
824 $attribs = array(
825 'class' => implode( ' ', $classes ),
826 );
827
828 if ( $sectionName ) {
829 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
830 }
831
832 $tableHtml = Html::rawElement( 'table', $attribs,
833 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
834
835 if ( $this->mSubSectionBeforeFields ) {
836 return $subsectionHtml . "\n" . $tableHtml;
837 } else {
838 return $tableHtml . "\n" . $subsectionHtml;
839 }
840 }
841
842 /**
843 * Construct the form fields from the Descriptor array
844 */
845 function loadData() {
846 $fieldData = array();
847
848 foreach ( $this->mFlatFields as $fieldname => $field ) {
849 if ( !empty( $field->mParams['nodata'] ) ) {
850 continue;
851 } elseif ( !empty( $field->mParams['disabled'] ) ) {
852 $fieldData[$fieldname] = $field->getDefault();
853 } else {
854 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
855 }
856 }
857
858 # Filter data.
859 foreach ( $fieldData as $name => &$value ) {
860 $field = $this->mFlatFields[$name];
861 $value = $field->filter( $value, $this->mFlatFields );
862 }
863
864 $this->mFieldData = $fieldData;
865 }
866
867 /**
868 * Stop a reset button being shown for this form
869 * @param $suppressReset Bool set to false to re-enable the
870 * button again
871 */
872 function suppressReset( $suppressReset = true ) {
873 $this->mShowReset = !$suppressReset;
874 }
875
876 /**
877 * Overload this if you want to apply special filtration routines
878 * to the form as a whole, after it's submitted but before it's
879 * processed.
880 * @param $data
881 * @return
882 */
883 function filterDataForSubmit( $data ) {
884 return $data;
885 }
886
887 /**
888 * Get a string to go in the <legend> of a section fieldset. Override this if you
889 * want something more complicated
890 * @param $key String
891 * @return String
892 */
893 public function getLegend( $key ) {
894 return wfMsg( "{$this->mMessagePrefix}-$key" );
895 }
896
897 /**
898 * Set the value for the action attribute of the form.
899 * When set to false (which is the default state), the set title is used.
900 *
901 * @since 1.19
902 *
903 * @param string|bool $action
904 */
905 public function setAction( $action ) {
906 $this->mAction = $action;
907 }
908
909 }
910
911 /**
912 * The parent class to generate form fields. Any field type should
913 * be a subclass of this.
914 */
915 abstract class HTMLFormField {
916
917 protected $mValidationCallback;
918 protected $mFilterCallback;
919 protected $mName;
920 public $mParams;
921 protected $mLabel; # String label. Set on construction
922 protected $mID;
923 protected $mClass = '';
924 protected $mDefault;
925
926 /**
927 * @var HTMLForm
928 */
929 public $mParent;
930
931 /**
932 * This function must be implemented to return the HTML to generate
933 * the input object itself. It should not implement the surrounding
934 * table cells/rows, or labels/help messages.
935 * @param $value String the value to set the input to; eg a default
936 * text for a text input.
937 * @return String valid HTML.
938 */
939 abstract function getInputHTML( $value );
940
941 /**
942 * Override this function to add specific validation checks on the
943 * field input. Don't forget to call parent::validate() to ensure
944 * that the user-defined callback mValidationCallback is still run
945 * @param $value String the value the field was submitted with
946 * @param $alldata Array the data collected from the form
947 * @return Mixed Bool true on success, or String error to display.
948 */
949 function validate( $value, $alldata ) {
950 if ( isset( $this->mParams['required'] ) && $value === '' ) {
951 return wfMsgExt( 'htmlform-required', 'parseinline' );
952 }
953
954 if ( isset( $this->mValidationCallback ) ) {
955 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
956 }
957
958 return true;
959 }
960
961 function filter( $value, $alldata ) {
962 if ( isset( $this->mFilterCallback ) ) {
963 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
964 }
965
966 return $value;
967 }
968
969 /**
970 * Should this field have a label, or is there no input element with the
971 * appropriate id for the label to point to?
972 *
973 * @return bool True to output a label, false to suppress
974 */
975 protected function needsLabel() {
976 return true;
977 }
978
979 /**
980 * Get the value that this input has been set to from a posted form,
981 * or the input's default value if it has not been set.
982 * @param $request WebRequest
983 * @return String the value
984 */
985 function loadDataFromRequest( $request ) {
986 if ( $request->getCheck( $this->mName ) ) {
987 return $request->getText( $this->mName );
988 } else {
989 return $this->getDefault();
990 }
991 }
992
993 /**
994 * Initialise the object
995 * @param $params array Associative Array. See HTMLForm doc for syntax.
996 */
997 function __construct( $params ) {
998 $this->mParams = $params;
999
1000 # Generate the label from a message, if possible
1001 if ( isset( $params['label-message'] ) ) {
1002 $msgInfo = $params['label-message'];
1003
1004 if ( is_array( $msgInfo ) ) {
1005 $msg = array_shift( $msgInfo );
1006 } else {
1007 $msg = $msgInfo;
1008 $msgInfo = array();
1009 }
1010
1011 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
1012 } elseif ( isset( $params['label'] ) ) {
1013 $this->mLabel = $params['label'];
1014 }
1015
1016 $this->mName = "wp{$params['fieldname']}";
1017 if ( isset( $params['name'] ) ) {
1018 $this->mName = $params['name'];
1019 }
1020
1021 $validName = Sanitizer::escapeId( $this->mName );
1022 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1023 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1024 }
1025
1026 $this->mID = "mw-input-{$this->mName}";
1027
1028 if ( isset( $params['default'] ) ) {
1029 $this->mDefault = $params['default'];
1030 }
1031
1032 if ( isset( $params['id'] ) ) {
1033 $id = $params['id'];
1034 $validId = Sanitizer::escapeId( $id );
1035
1036 if ( $id != $validId ) {
1037 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1038 }
1039
1040 $this->mID = $id;
1041 }
1042
1043 if ( isset( $params['cssclass'] ) ) {
1044 $this->mClass = $params['cssclass'];
1045 }
1046
1047 if ( isset( $params['validation-callback'] ) ) {
1048 $this->mValidationCallback = $params['validation-callback'];
1049 }
1050
1051 if ( isset( $params['filter-callback'] ) ) {
1052 $this->mFilterCallback = $params['filter-callback'];
1053 }
1054
1055 if ( isset( $params['flatlist'] ) ){
1056 $this->mClass .= ' mw-htmlform-flatlist';
1057 }
1058 }
1059
1060 /**
1061 * Get the complete table row for the input, including help text,
1062 * labels, and whatever.
1063 * @param $value String the value to set the input to.
1064 * @return String complete HTML table row.
1065 */
1066 function getTableRow( $value ) {
1067 # Check for invalid data.
1068
1069 $errors = $this->validate( $value, $this->mParent->mFieldData );
1070
1071 $cellAttributes = array();
1072 $verticalLabel = false;
1073
1074 if ( !empty($this->mParams['vertical-label']) ) {
1075 $cellAttributes['colspan'] = 2;
1076 $verticalLabel = true;
1077 }
1078
1079 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1080 $errors = '';
1081 $errorClass = '';
1082 } else {
1083 $errors = self::formatErrors( $errors );
1084 $errorClass = 'mw-htmlform-invalid-input';
1085 }
1086
1087 $label = $this->getLabelHtml( $cellAttributes );
1088 $field = Html::rawElement(
1089 'td',
1090 array( 'class' => 'mw-input' ) + $cellAttributes,
1091 $this->getInputHTML( $value ) . "\n$errors"
1092 );
1093
1094 $fieldType = get_class( $this );
1095
1096 if ( $verticalLabel ) {
1097 $html = Html::rawElement( 'tr',
1098 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1099 $html .= Html::rawElement( 'tr',
1100 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1101 $field );
1102 } else {
1103 $html = Html::rawElement( 'tr',
1104 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1105 $label . $field );
1106 }
1107
1108 $helptext = null;
1109
1110 if ( isset( $this->mParams['help-message'] ) ) {
1111 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1112 }
1113
1114 if ( isset( $this->mParams['help-messages'] ) ) {
1115 foreach( $this->mParams['help-messages'] as $name ) {
1116 $helpMessage = (array)$name;
1117 $msg = wfMessage( array_shift( $helpMessage ), $helpMessage );
1118
1119 if( $msg->exists() ) {
1120 if( is_null( $helptext ) ) {
1121 $helptext = '';
1122 } else {
1123 $helptext .= wfMessage( 'word-separator' )->escaped(); // some space
1124 }
1125 $helptext .= $msg->parse(); // Append message
1126 }
1127 }
1128 }
1129 elseif ( isset( $this->mParams['help'] ) ) {
1130 $helptext = $this->mParams['help'];
1131 }
1132
1133 if ( !is_null( $helptext ) ) {
1134 $row = Html::rawElement(
1135 'td',
1136 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1137 $helptext
1138 );
1139 $row = Html::rawElement( 'tr', array(), $row );
1140 $html .= "$row\n";
1141 }
1142
1143 return $html;
1144 }
1145
1146 function getLabel() {
1147 return $this->mLabel;
1148 }
1149 function getLabelHtml( $cellAttributes = array() ) {
1150 # Don't output a for= attribute for labels with no associated input.
1151 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1152 $for = array();
1153
1154 if ( $this->needsLabel() ) {
1155 $for['for'] = $this->mID;
1156 }
1157
1158 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1159 Html::rawElement( 'label', $for, $this->getLabel() )
1160 );
1161 }
1162
1163 function getDefault() {
1164 if ( isset( $this->mDefault ) ) {
1165 return $this->mDefault;
1166 } else {
1167 return null;
1168 }
1169 }
1170
1171 /**
1172 * Returns the attributes required for the tooltip and accesskey.
1173 *
1174 * @return array Attributes
1175 */
1176 public function getTooltipAndAccessKey() {
1177 if ( empty( $this->mParams['tooltip'] ) ) {
1178 return array();
1179 }
1180 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1181 }
1182
1183 /**
1184 * flatten an array of options to a single array, for instance,
1185 * a set of <options> inside <optgroups>.
1186 * @param $options array Associative Array with values either Strings
1187 * or Arrays
1188 * @return Array flattened input
1189 */
1190 public static function flattenOptions( $options ) {
1191 $flatOpts = array();
1192
1193 foreach ( $options as $value ) {
1194 if ( is_array( $value ) ) {
1195 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1196 } else {
1197 $flatOpts[] = $value;
1198 }
1199 }
1200
1201 return $flatOpts;
1202 }
1203
1204 /**
1205 * Formats one or more errors as accepted by field validation-callback.
1206 * @param $errors String|Message|Array of strings or Message instances
1207 * @return String html
1208 * @since 1.18
1209 */
1210 protected static function formatErrors( $errors ) {
1211 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1212 $errors = array_shift( $errors );
1213 }
1214
1215 if ( is_array( $errors ) ) {
1216 $lines = array();
1217 foreach ( $errors as $error ) {
1218 if ( $error instanceof Message ) {
1219 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1220 } else {
1221 $lines[] = Html::rawElement( 'li', array(), $error );
1222 }
1223 }
1224 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1225 } else {
1226 if ( $errors instanceof Message ) {
1227 $errors = $errors->parse();
1228 }
1229 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1230 }
1231 }
1232 }
1233
1234 class HTMLTextField extends HTMLFormField {
1235 function getSize() {
1236 return isset( $this->mParams['size'] )
1237 ? $this->mParams['size']
1238 : 45;
1239 }
1240
1241 function getInputHTML( $value ) {
1242 $attribs = array(
1243 'id' => $this->mID,
1244 'name' => $this->mName,
1245 'size' => $this->getSize(),
1246 'value' => $value,
1247 ) + $this->getTooltipAndAccessKey();
1248
1249 if ( $this->mClass !== '' ) {
1250 $attribs['class'] = $this->mClass;
1251 }
1252
1253 if ( isset( $this->mParams['maxlength'] ) ) {
1254 $attribs['maxlength'] = $this->mParams['maxlength'];
1255 }
1256
1257 if ( !empty( $this->mParams['disabled'] ) ) {
1258 $attribs['disabled'] = 'disabled';
1259 }
1260
1261 # TODO: Enforce pattern, step, required, readonly on the server side as
1262 # well
1263 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1264 'placeholder' ) as $param ) {
1265 if ( isset( $this->mParams[$param] ) ) {
1266 $attribs[$param] = $this->mParams[$param];
1267 }
1268 }
1269
1270 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1271 if ( isset( $this->mParams[$param] ) ) {
1272 $attribs[$param] = '';
1273 }
1274 }
1275
1276 # Implement tiny differences between some field variants
1277 # here, rather than creating a new class for each one which
1278 # is essentially just a clone of this one.
1279 if ( isset( $this->mParams['type'] ) ) {
1280 switch ( $this->mParams['type'] ) {
1281 case 'email':
1282 $attribs['type'] = 'email';
1283 break;
1284 case 'int':
1285 $attribs['type'] = 'number';
1286 break;
1287 case 'float':
1288 $attribs['type'] = 'number';
1289 $attribs['step'] = 'any';
1290 break;
1291 # Pass through
1292 case 'password':
1293 case 'file':
1294 $attribs['type'] = $this->mParams['type'];
1295 break;
1296 }
1297 }
1298
1299 return Html::element( 'input', $attribs );
1300 }
1301 }
1302 class HTMLTextAreaField extends HTMLFormField {
1303 function getCols() {
1304 return isset( $this->mParams['cols'] )
1305 ? $this->mParams['cols']
1306 : 80;
1307 }
1308
1309 function getRows() {
1310 return isset( $this->mParams['rows'] )
1311 ? $this->mParams['rows']
1312 : 25;
1313 }
1314
1315 function getInputHTML( $value ) {
1316 $attribs = array(
1317 'id' => $this->mID,
1318 'name' => $this->mName,
1319 'cols' => $this->getCols(),
1320 'rows' => $this->getRows(),
1321 ) + $this->getTooltipAndAccessKey();
1322
1323 if ( $this->mClass !== '' ) {
1324 $attribs['class'] = $this->mClass;
1325 }
1326
1327 if ( !empty( $this->mParams['disabled'] ) ) {
1328 $attribs['disabled'] = 'disabled';
1329 }
1330
1331 if ( !empty( $this->mParams['readonly'] ) ) {
1332 $attribs['readonly'] = 'readonly';
1333 }
1334
1335 if ( isset( $this->mParams['placeholder'] ) ) {
1336 $attribs['placeholder'] = $this->mParams['placeholder'];
1337 }
1338
1339 foreach ( array( 'required', 'autofocus' ) as $param ) {
1340 if ( isset( $this->mParams[$param] ) ) {
1341 $attribs[$param] = '';
1342 }
1343 }
1344
1345 return Html::element( 'textarea', $attribs, $value );
1346 }
1347 }
1348
1349 /**
1350 * A field that will contain a numeric value
1351 */
1352 class HTMLFloatField extends HTMLTextField {
1353 function getSize() {
1354 return isset( $this->mParams['size'] )
1355 ? $this->mParams['size']
1356 : 20;
1357 }
1358
1359 function validate( $value, $alldata ) {
1360 $p = parent::validate( $value, $alldata );
1361
1362 if ( $p !== true ) {
1363 return $p;
1364 }
1365
1366 $value = trim( $value );
1367
1368 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1369 # with the addition that a leading '+' sign is ok.
1370 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1371 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1372 }
1373
1374 # The "int" part of these message names is rather confusing.
1375 # They make equal sense for all numbers.
1376 if ( isset( $this->mParams['min'] ) ) {
1377 $min = $this->mParams['min'];
1378
1379 if ( $min > $value ) {
1380 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1381 }
1382 }
1383
1384 if ( isset( $this->mParams['max'] ) ) {
1385 $max = $this->mParams['max'];
1386
1387 if ( $max < $value ) {
1388 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1389 }
1390 }
1391
1392 return true;
1393 }
1394 }
1395
1396 /**
1397 * A field that must contain a number
1398 */
1399 class HTMLIntField extends HTMLFloatField {
1400 function validate( $value, $alldata ) {
1401 $p = parent::validate( $value, $alldata );
1402
1403 if ( $p !== true ) {
1404 return $p;
1405 }
1406
1407 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1408 # with the addition that a leading '+' sign is ok. Note that leading zeros
1409 # are fine, and will be left in the input, which is useful for things like
1410 # phone numbers when you know that they are integers (the HTML5 type=tel
1411 # input does not require its value to be numeric). If you want a tidier
1412 # value to, eg, save in the DB, clean it up with intval().
1413 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1414 ) {
1415 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1416 }
1417
1418 return true;
1419 }
1420 }
1421
1422 /**
1423 * A checkbox field
1424 */
1425 class HTMLCheckField extends HTMLFormField {
1426 function getInputHTML( $value ) {
1427 if ( !empty( $this->mParams['invert'] ) ) {
1428 $value = !$value;
1429 }
1430
1431 $attr = $this->getTooltipAndAccessKey();
1432 $attr['id'] = $this->mID;
1433
1434 if ( !empty( $this->mParams['disabled'] ) ) {
1435 $attr['disabled'] = 'disabled';
1436 }
1437
1438 if ( $this->mClass !== '' ) {
1439 $attr['class'] = $this->mClass;
1440 }
1441
1442 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1443 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1444 }
1445
1446 /**
1447 * For a checkbox, the label goes on the right hand side, and is
1448 * added in getInputHTML(), rather than HTMLFormField::getRow()
1449 * @return String
1450 */
1451 function getLabel() {
1452 return '&#160;';
1453 }
1454
1455 /**
1456 * @param $request WebRequest
1457 * @return String
1458 */
1459 function loadDataFromRequest( $request ) {
1460 $invert = false;
1461 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1462 $invert = true;
1463 }
1464
1465 // GetCheck won't work like we want for checks.
1466 // Fetch the value in either one of the two following case:
1467 // - we have a valid token (form got posted or GET forged by the user)
1468 // - checkbox name has a value (false or true), ie is not null
1469 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName )!== null ) {
1470 // XOR has the following truth table, which is what we want
1471 // INVERT VALUE | OUTPUT
1472 // true true | false
1473 // false true | true
1474 // false false | false
1475 // true false | true
1476 return $request->getBool( $this->mName ) xor $invert;
1477 } else {
1478 return $this->getDefault();
1479 }
1480 }
1481 }
1482
1483 /**
1484 * A select dropdown field. Basically a wrapper for Xmlselect class
1485 */
1486 class HTMLSelectField extends HTMLFormField {
1487 function validate( $value, $alldata ) {
1488 $p = parent::validate( $value, $alldata );
1489
1490 if ( $p !== true ) {
1491 return $p;
1492 }
1493
1494 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1495
1496 if ( in_array( $value, $validOptions ) )
1497 return true;
1498 else
1499 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1500 }
1501
1502 function getInputHTML( $value ) {
1503 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1504
1505 # If one of the options' 'name' is int(0), it is automatically selected.
1506 # because PHP sucks and thinks int(0) == 'some string'.
1507 # Working around this by forcing all of them to strings.
1508 foreach( $this->mParams['options'] as &$opt ){
1509 if( is_int( $opt ) ){
1510 $opt = strval( $opt );
1511 }
1512 }
1513 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1514
1515 if ( !empty( $this->mParams['disabled'] ) ) {
1516 $select->setAttribute( 'disabled', 'disabled' );
1517 }
1518
1519 if ( $this->mClass !== '' ) {
1520 $select->setAttribute( 'class', $this->mClass );
1521 }
1522
1523 $select->addOptions( $this->mParams['options'] );
1524
1525 return $select->getHTML();
1526 }
1527 }
1528
1529 /**
1530 * Select dropdown field, with an additional "other" textbox.
1531 */
1532 class HTMLSelectOrOtherField extends HTMLTextField {
1533 static $jsAdded = false;
1534
1535 function __construct( $params ) {
1536 if ( !in_array( 'other', $params['options'], true ) ) {
1537 $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
1538 $params['options'][$msg] = 'other';
1539 }
1540
1541 parent::__construct( $params );
1542 }
1543
1544 static function forceToStringRecursive( $array ) {
1545 if ( is_array( $array ) ) {
1546 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1547 } else {
1548 return strval( $array );
1549 }
1550 }
1551
1552 function getInputHTML( $value ) {
1553 $valInSelect = false;
1554
1555 if ( $value !== false ) {
1556 $valInSelect = in_array(
1557 $value,
1558 HTMLFormField::flattenOptions( $this->mParams['options'] )
1559 );
1560 }
1561
1562 $selected = $valInSelect ? $value : 'other';
1563
1564 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1565
1566 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1567 $select->addOptions( $opts );
1568
1569 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1570
1571 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1572
1573 if ( !empty( $this->mParams['disabled'] ) ) {
1574 $select->setAttribute( 'disabled', 'disabled' );
1575 $tbAttribs['disabled'] = 'disabled';
1576 }
1577
1578 $select = $select->getHTML();
1579
1580 if ( isset( $this->mParams['maxlength'] ) ) {
1581 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1582 }
1583
1584 if ( $this->mClass !== '' ) {
1585 $tbAttribs['class'] = $this->mClass;
1586 }
1587
1588 $textbox = Html::input(
1589 $this->mName . '-other',
1590 $valInSelect ? '' : $value,
1591 'text',
1592 $tbAttribs
1593 );
1594
1595 return "$select<br />\n$textbox";
1596 }
1597
1598 /**
1599 * @param $request WebRequest
1600 * @return String
1601 */
1602 function loadDataFromRequest( $request ) {
1603 if ( $request->getCheck( $this->mName ) ) {
1604 $val = $request->getText( $this->mName );
1605
1606 if ( $val == 'other' ) {
1607 $val = $request->getText( $this->mName . '-other' );
1608 }
1609
1610 return $val;
1611 } else {
1612 return $this->getDefault();
1613 }
1614 }
1615 }
1616
1617 /**
1618 * Multi-select field
1619 */
1620 class HTMLMultiSelectField extends HTMLFormField {
1621
1622 function validate( $value, $alldata ) {
1623 $p = parent::validate( $value, $alldata );
1624
1625 if ( $p !== true ) {
1626 return $p;
1627 }
1628
1629 if ( !is_array( $value ) ) {
1630 return false;
1631 }
1632
1633 # If all options are valid, array_intersect of the valid options
1634 # and the provided options will return the provided options.
1635 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1636
1637 $validValues = array_intersect( $value, $validOptions );
1638 if ( count( $validValues ) == count( $value ) ) {
1639 return true;
1640 } else {
1641 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1642 }
1643 }
1644
1645 function getInputHTML( $value ) {
1646 $html = $this->formatOptions( $this->mParams['options'], $value );
1647
1648 return $html;
1649 }
1650
1651 function formatOptions( $options, $value ) {
1652 $html = '';
1653
1654 $attribs = array();
1655
1656 if ( !empty( $this->mParams['disabled'] ) ) {
1657 $attribs['disabled'] = 'disabled';
1658 }
1659
1660 foreach ( $options as $label => $info ) {
1661 if ( is_array( $info ) ) {
1662 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1663 $html .= $this->formatOptions( $info, $value );
1664 } else {
1665 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1666
1667 $checkbox = Xml::check(
1668 $this->mName . '[]',
1669 in_array( $info, $value, true ),
1670 $attribs + $thisAttribs );
1671 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1672
1673 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1674 }
1675 }
1676
1677 return $html;
1678 }
1679
1680 /**
1681 * @param $request WebRequest
1682 * @return String
1683 */
1684 function loadDataFromRequest( $request ) {
1685 if ( $this->mParent->getMethod() == 'post' ) {
1686 if( $request->wasPosted() ){
1687 # Checkboxes are just not added to the request arrays if they're not checked,
1688 # so it's perfectly possible for there not to be an entry at all
1689 return $request->getArray( $this->mName, array() );
1690 } else {
1691 # That's ok, the user has not yet submitted the form, so show the defaults
1692 return $this->getDefault();
1693 }
1694 } else {
1695 # This is the impossible case: if we look at $_GET and see no data for our
1696 # field, is it because the user has not yet submitted the form, or that they
1697 # have submitted it with all the options unchecked? We will have to assume the
1698 # latter, which basically means that you can't specify 'positive' defaults
1699 # for GET forms.
1700 # @todo FIXME...
1701 return $request->getArray( $this->mName, array() );
1702 }
1703 }
1704
1705 function getDefault() {
1706 if ( isset( $this->mDefault ) ) {
1707 return $this->mDefault;
1708 } else {
1709 return array();
1710 }
1711 }
1712
1713 protected function needsLabel() {
1714 return false;
1715 }
1716 }
1717
1718 /**
1719 * Double field with a dropdown list constructed from a system message in the format
1720 * * Optgroup header
1721 * ** <option value>
1722 * * New Optgroup header
1723 * Plus a text field underneath for an additional reason. The 'value' of the field is
1724 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1725 * select dropdown.
1726 * @todo FIXME: If made 'required', only the text field should be compulsory.
1727 */
1728 class HTMLSelectAndOtherField extends HTMLSelectField {
1729
1730 function __construct( $params ) {
1731 if ( array_key_exists( 'other', $params ) ) {
1732 } elseif( array_key_exists( 'other-message', $params ) ){
1733 $params['other'] = wfMessage( $params['other-message'] )->plain();
1734 } else {
1735 $params['other'] = null;
1736 }
1737
1738 if ( array_key_exists( 'options', $params ) ) {
1739 # Options array already specified
1740 } elseif( array_key_exists( 'options-message', $params ) ){
1741 # Generate options array from a system message
1742 $params['options'] = self::parseMessage(
1743 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1744 $params['other']
1745 );
1746 } else {
1747 # Sulk
1748 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1749 }
1750 $this->mFlatOptions = self::flattenOptions( $params['options'] );
1751
1752 parent::__construct( $params );
1753 }
1754
1755 /**
1756 * Build a drop-down box from a textual list.
1757 * @param $string String message text
1758 * @param $otherName String name of "other reason" option
1759 * @return Array
1760 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1761 */
1762 public static function parseMessage( $string, $otherName=null ) {
1763 if( $otherName === null ){
1764 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1765 }
1766
1767 $optgroup = false;
1768 $options = array( $otherName => 'other' );
1769
1770 foreach ( explode( "\n", $string ) as $option ) {
1771 $value = trim( $option );
1772 if ( $value == '' ) {
1773 continue;
1774 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1775 # A new group is starting...
1776 $value = trim( substr( $value, 1 ) );
1777 $optgroup = $value;
1778 } elseif ( substr( $value, 0, 2) == '**' ) {
1779 # groupmember
1780 $opt = trim( substr( $value, 2 ) );
1781 if( $optgroup === false ){
1782 $options[$opt] = $opt;
1783 } else {
1784 $options[$optgroup][$opt] = $opt;
1785 }
1786 } else {
1787 # groupless reason list
1788 $optgroup = false;
1789 $options[$option] = $option;
1790 }
1791 }
1792
1793 return $options;
1794 }
1795
1796 function getInputHTML( $value ) {
1797 $select = parent::getInputHTML( $value[1] );
1798
1799 $textAttribs = array(
1800 'id' => $this->mID . '-other',
1801 'size' => $this->getSize(),
1802 );
1803
1804 if ( $this->mClass !== '' ) {
1805 $textAttribs['class'] = $this->mClass;
1806 }
1807
1808 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1809 if ( isset( $this->mParams[$param] ) ) {
1810 $textAttribs[$param] = '';
1811 }
1812 }
1813
1814 $textbox = Html::input(
1815 $this->mName . '-other',
1816 $value[2],
1817 'text',
1818 $textAttribs
1819 );
1820
1821 return "$select<br />\n$textbox";
1822 }
1823
1824 /**
1825 * @param $request WebRequest
1826 * @return Array( <overall message>, <select value>, <text field value> )
1827 */
1828 function loadDataFromRequest( $request ) {
1829 if ( $request->getCheck( $this->mName ) ) {
1830
1831 $list = $request->getText( $this->mName );
1832 $text = $request->getText( $this->mName . '-other' );
1833
1834 if ( $list == 'other' ) {
1835 $final = $text;
1836 } elseif( !in_array( $list, $this->mFlatOptions ) ){
1837 # User has spoofed the select form to give an option which wasn't
1838 # in the original offer. Sulk...
1839 $final = $text;
1840 } elseif( $text == '' ) {
1841 $final = $list;
1842 } else {
1843 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1844 }
1845
1846 } else {
1847 $final = $this->getDefault();
1848
1849 $list = 'other';
1850 $text = $final;
1851 foreach ( $this->mFlatOptions as $option ) {
1852 $match = $option . wfMsgForContent( 'colon-separator' );
1853 if( strpos( $text, $match ) === 0 ) {
1854 $list = $option;
1855 $text = substr( $text, strlen( $match ) );
1856 break;
1857 }
1858 }
1859 }
1860 return array( $final, $list, $text );
1861 }
1862
1863 function getSize() {
1864 return isset( $this->mParams['size'] )
1865 ? $this->mParams['size']
1866 : 45;
1867 }
1868
1869 function validate( $value, $alldata ) {
1870 # HTMLSelectField forces $value to be one of the options in the select
1871 # field, which is not useful here. But we do want the validation further up
1872 # the chain
1873 $p = parent::validate( $value[1], $alldata );
1874
1875 if ( $p !== true ) {
1876 return $p;
1877 }
1878
1879 if( isset( $this->mParams['required'] ) && $value[1] === '' ){
1880 return wfMsgExt( 'htmlform-required', 'parseinline' );
1881 }
1882
1883 return true;
1884 }
1885 }
1886
1887 /**
1888 * Radio checkbox fields.
1889 */
1890 class HTMLRadioField extends HTMLFormField {
1891
1892
1893 function validate( $value, $alldata ) {
1894 $p = parent::validate( $value, $alldata );
1895
1896 if ( $p !== true ) {
1897 return $p;
1898 }
1899
1900 if ( !is_string( $value ) && !is_int( $value ) ) {
1901 return false;
1902 }
1903
1904 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1905
1906 if ( in_array( $value, $validOptions ) ) {
1907 return true;
1908 } else {
1909 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1910 }
1911 }
1912
1913 /**
1914 * This returns a block of all the radio options, in one cell.
1915 * @see includes/HTMLFormField#getInputHTML()
1916 * @param $value String
1917 * @return String
1918 */
1919 function getInputHTML( $value ) {
1920 $html = $this->formatOptions( $this->mParams['options'], $value );
1921
1922 return $html;
1923 }
1924
1925 function formatOptions( $options, $value ) {
1926 $html = '';
1927
1928 $attribs = array();
1929 if ( !empty( $this->mParams['disabled'] ) ) {
1930 $attribs['disabled'] = 'disabled';
1931 }
1932
1933 # TODO: should this produce an unordered list perhaps?
1934 foreach ( $options as $label => $info ) {
1935 if ( is_array( $info ) ) {
1936 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1937 $html .= $this->formatOptions( $info, $value );
1938 } else {
1939 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1940 $radio = Xml::radio(
1941 $this->mName,
1942 $info,
1943 $info == $value,
1944 $attribs + array( 'id' => $id )
1945 );
1946 $radio .= '&#160;' .
1947 Html::rawElement( 'label', array( 'for' => $id ), $label );
1948
1949 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
1950 }
1951 }
1952
1953 return $html;
1954 }
1955
1956 protected function needsLabel() {
1957 return false;
1958 }
1959 }
1960
1961 /**
1962 * An information field (text blob), not a proper input.
1963 */
1964 class HTMLInfoField extends HTMLFormField {
1965 function __construct( $info ) {
1966 $info['nodata'] = true;
1967
1968 parent::__construct( $info );
1969 }
1970
1971 function getInputHTML( $value ) {
1972 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1973 }
1974
1975 function getTableRow( $value ) {
1976 if ( !empty( $this->mParams['rawrow'] ) ) {
1977 return $value;
1978 }
1979
1980 return parent::getTableRow( $value );
1981 }
1982
1983 protected function needsLabel() {
1984 return false;
1985 }
1986 }
1987
1988 class HTMLHiddenField extends HTMLFormField {
1989 public function __construct( $params ) {
1990 parent::__construct( $params );
1991
1992 # Per HTML5 spec, hidden fields cannot be 'required'
1993 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1994 unset( $this->mParams['required'] );
1995 }
1996
1997 public function getTableRow( $value ) {
1998 $params = array();
1999 if ( $this->mID ) {
2000 $params['id'] = $this->mID;
2001 }
2002
2003 $this->mParent->addHiddenField(
2004 $this->mName,
2005 $this->mDefault,
2006 $params
2007 );
2008
2009 return '';
2010 }
2011
2012 public function getInputHTML( $value ) { return ''; }
2013 }
2014
2015 /**
2016 * Add a submit button inline in the form (as opposed to
2017 * HTMLForm::addButton(), which will add it at the end).
2018 */
2019 class HTMLSubmitField extends HTMLFormField {
2020
2021 function __construct( $info ) {
2022 $info['nodata'] = true;
2023 parent::__construct( $info );
2024 }
2025
2026 function getInputHTML( $value ) {
2027 return Xml::submitButton(
2028 $value,
2029 array(
2030 'class' => 'mw-htmlform-submit ' . $this->mClass,
2031 'name' => $this->mName,
2032 'id' => $this->mID,
2033 )
2034 );
2035 }
2036
2037 protected function needsLabel() {
2038 return false;
2039 }
2040
2041 /**
2042 * Button cannot be invalid
2043 * @param $value String
2044 * @param $alldata Array
2045 * @return Bool
2046 */
2047 public function validate( $value, $alldata ){
2048 return true;
2049 }
2050 }
2051
2052 class HTMLEditTools extends HTMLFormField {
2053 public function getInputHTML( $value ) {
2054 return '';
2055 }
2056
2057 public function getTableRow( $value ) {
2058 if ( empty( $this->mParams['message'] ) ) {
2059 $msg = wfMessage( 'edittools' );
2060 } else {
2061 $msg = wfMessage( $this->mParams['message'] );
2062 if ( $msg->isDisabled() ) {
2063 $msg = wfMessage( 'edittools' );
2064 }
2065 }
2066 $msg->inContentLanguage();
2067
2068
2069 return '<tr><td></td><td class="mw-input">'
2070 . '<div class="mw-editTools">'
2071 . $msg->parseAsBlock()
2072 . "</div></td></tr>\n";
2073 }
2074 }