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