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