Follow up r100512, adding @since tags and using wfMessage
[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 * @since 1.19
586 * @param $msg String message key
587 */
588 public function setSubmitTextMsg( $msg ) {
589 return $this->setSubmitText( wfMessage( $msg )->escaped() );
590 }
591
592 /**
593 * Get the text for the submit button, either customised or a default.
594 * @return unknown_type
595 */
596 function getSubmitText() {
597 return $this->mSubmitText
598 ? $this->mSubmitText
599 : wfMsg( 'htmlform-submit' );
600 }
601
602 public function setSubmitName( $name ) {
603 $this->mSubmitName = $name;
604 }
605
606 public function setSubmitTooltip( $name ) {
607 $this->mSubmitTooltip = $name;
608 }
609
610 /**
611 * Set the id for the submit button.
612 * @param $t String.
613 * @todo FIXME: Integrity of $t is *not* validated
614 */
615 function setSubmitID( $t ) {
616 $this->mSubmitID = $t;
617 }
618
619 public function setId( $id ) {
620 $this->mId = $id;
621 }
622 /**
623 * Prompt the whole form to be wrapped in a <fieldset>, with
624 * this text as its <legend> element.
625 * @param $legend String HTML to go inside the <legend> element.
626 * Will be escaped
627 */
628 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
629
630 /**
631 * Prompt the whole form to be wrapped in a <fieldset>, with
632 * this message as its <legend> element.
633 * @since 1.19
634 * @param $msg String message key
635 */
636 public function setWrapperLegendMsg( $msg ) {
637 return $this->setWrapperLegend( wfMessage( $msg )->escaped() );
638 }
639
640 /**
641 * Set the prefix for various default messages
642 * TODO: currently only used for the <fieldset> legend on forms
643 * with multiple sections; should be used elsewhre?
644 * @param $p String
645 */
646 function setMessagePrefix( $p ) {
647 $this->mMessagePrefix = $p;
648 }
649
650 /**
651 * Set the title for form submission
652 * @param $t Title of page the form is on/should be posted to
653 */
654 function setTitle( $t ) {
655 $this->mTitle = $t;
656 }
657
658 /**
659 * Get the title
660 * @return Title
661 */
662 function getTitle() {
663 return $this->mTitle === false
664 ? $this->getContext()->getTitle()
665 : $this->mTitle;
666 }
667
668 /**
669 * @return IContextSource
670 */
671 public function getContext(){
672 return $this->mContext instanceof IContextSource
673 ? $this->mContext
674 : RequestContext::getMain();
675 }
676
677 /**
678 * @return OutputPage
679 */
680 public function getOutput(){
681 return $this->getContext()->getOutput();
682 }
683
684 /**
685 * @return WebRequest
686 */
687 public function getRequest(){
688 return $this->getContext()->getRequest();
689 }
690
691 /**
692 * @return User
693 */
694 public function getUser(){
695 return $this->getContext()->getUser();
696 }
697
698 /**
699 * Set the method used to submit the form
700 * @param $method String
701 */
702 public function setMethod( $method='post' ){
703 $this->mMethod = $method;
704 }
705
706 public function getMethod(){
707 return $this->mMethod;
708 }
709
710 /**
711 * TODO: Document
712 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
713 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
714 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
715 * @return String
716 */
717 function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
718 $tableHtml = '';
719 $subsectionHtml = '';
720 $hasLeftColumn = false;
721
722 foreach ( $fields as $key => $value ) {
723 if ( is_object( $value ) ) {
724 $v = empty( $value->mParams['nodata'] )
725 ? $this->mFieldData[$key]
726 : $value->getDefault();
727 $tableHtml .= $value->getTableRow( $v );
728
729 if ( $value->getLabel() != '&#160;' ) {
730 $hasLeftColumn = true;
731 }
732 } elseif ( is_array( $value ) ) {
733 $section = $this->displaySection( $value, $key );
734 $legend = $this->getLegend( $key );
735 if ( isset( $this->mSectionHeaders[$key] ) ) {
736 $section = $this->mSectionHeaders[$key] . $section;
737 }
738 if ( isset( $this->mSectionFooters[$key] ) ) {
739 $section .= $this->mSectionFooters[$key];
740 }
741 $attributes = array();
742 if ( $fieldsetIDPrefix ) {
743 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
744 }
745 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
746 }
747 }
748
749 $classes = array();
750
751 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
752 $classes[] = 'mw-htmlform-nolabel';
753 }
754
755 $attribs = array(
756 'class' => implode( ' ', $classes ),
757 );
758
759 if ( $sectionName ) {
760 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
761 }
762
763 $tableHtml = Html::rawElement( 'table', $attribs,
764 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
765
766 return $subsectionHtml . "\n" . $tableHtml;
767 }
768
769 /**
770 * Construct the form fields from the Descriptor array
771 */
772 function loadData() {
773 $fieldData = array();
774
775 foreach ( $this->mFlatFields as $fieldname => $field ) {
776 if ( !empty( $field->mParams['nodata'] ) ) {
777 continue;
778 } elseif ( !empty( $field->mParams['disabled'] ) ) {
779 $fieldData[$fieldname] = $field->getDefault();
780 } else {
781 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
782 }
783 }
784
785 # Filter data.
786 foreach ( $fieldData as $name => &$value ) {
787 $field = $this->mFlatFields[$name];
788 $value = $field->filter( $value, $this->mFlatFields );
789 }
790
791 $this->mFieldData = $fieldData;
792 }
793
794 /**
795 * Stop a reset button being shown for this form
796 * @param $suppressReset Bool set to false to re-enable the
797 * button again
798 */
799 function suppressReset( $suppressReset = true ) {
800 $this->mShowReset = !$suppressReset;
801 }
802
803 /**
804 * Overload this if you want to apply special filtration routines
805 * to the form as a whole, after it's submitted but before it's
806 * processed.
807 * @param $data
808 * @return unknown_type
809 */
810 function filterDataForSubmit( $data ) {
811 return $data;
812 }
813
814 /**
815 * Get a string to go in the <legend> of a section fieldset. Override this if you
816 * want something more complicated
817 * @param $key String
818 * @return String
819 */
820 public function getLegend( $key ) {
821 return wfMsg( "{$this->mMessagePrefix}-$key" );
822 }
823 }
824
825 /**
826 * The parent class to generate form fields. Any field type should
827 * be a subclass of this.
828 */
829 abstract class HTMLFormField {
830
831 protected $mValidationCallback;
832 protected $mFilterCallback;
833 protected $mName;
834 public $mParams;
835 protected $mLabel; # String label. Set on construction
836 protected $mID;
837 protected $mClass = '';
838 protected $mDefault;
839
840 /**
841 * @var HTMLForm
842 */
843 public $mParent;
844
845 /**
846 * This function must be implemented to return the HTML to generate
847 * the input object itself. It should not implement the surrounding
848 * table cells/rows, or labels/help messages.
849 * @param $value String the value to set the input to; eg a default
850 * text for a text input.
851 * @return String valid HTML.
852 */
853 abstract function getInputHTML( $value );
854
855 /**
856 * Override this function to add specific validation checks on the
857 * field input. Don't forget to call parent::validate() to ensure
858 * that the user-defined callback mValidationCallback is still run
859 * @param $value String the value the field was submitted with
860 * @param $alldata Array the data collected from the form
861 * @return Mixed Bool true on success, or String error to display.
862 */
863 function validate( $value, $alldata ) {
864 if ( isset( $this->mParams['required'] ) && $value === '' ) {
865 return wfMsgExt( 'htmlform-required', 'parseinline' );
866 }
867
868 if ( isset( $this->mValidationCallback ) ) {
869 return call_user_func( $this->mValidationCallback, $value, $alldata );
870 }
871
872 return true;
873 }
874
875 function filter( $value, $alldata ) {
876 if ( isset( $this->mFilterCallback ) ) {
877 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
878 }
879
880 return $value;
881 }
882
883 /**
884 * Should this field have a label, or is there no input element with the
885 * appropriate id for the label to point to?
886 *
887 * @return bool True to output a label, false to suppress
888 */
889 protected function needsLabel() {
890 return true;
891 }
892
893 /**
894 * Get the value that this input has been set to from a posted form,
895 * or the input's default value if it has not been set.
896 * @param $request WebRequest
897 * @return String the value
898 */
899 function loadDataFromRequest( $request ) {
900 if ( $request->getCheck( $this->mName ) ) {
901 return $request->getText( $this->mName );
902 } else {
903 return $this->getDefault();
904 }
905 }
906
907 /**
908 * Initialise the object
909 * @param $params array Associative Array. See HTMLForm doc for syntax.
910 */
911 function __construct( $params ) {
912 $this->mParams = $params;
913
914 # Generate the label from a message, if possible
915 if ( isset( $params['label-message'] ) ) {
916 $msgInfo = $params['label-message'];
917
918 if ( is_array( $msgInfo ) ) {
919 $msg = array_shift( $msgInfo );
920 } else {
921 $msg = $msgInfo;
922 $msgInfo = array();
923 }
924
925 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
926 } elseif ( isset( $params['label'] ) ) {
927 $this->mLabel = $params['label'];
928 }
929
930 $this->mName = "wp{$params['fieldname']}";
931 if ( isset( $params['name'] ) ) {
932 $this->mName = $params['name'];
933 }
934
935 $validName = Sanitizer::escapeId( $this->mName );
936 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
937 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
938 }
939
940 $this->mID = "mw-input-{$this->mName}";
941
942 if ( isset( $params['default'] ) ) {
943 $this->mDefault = $params['default'];
944 }
945
946 if ( isset( $params['id'] ) ) {
947 $id = $params['id'];
948 $validId = Sanitizer::escapeId( $id );
949
950 if ( $id != $validId ) {
951 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
952 }
953
954 $this->mID = $id;
955 }
956
957 if ( isset( $params['cssclass'] ) ) {
958 $this->mClass = $params['cssclass'];
959 }
960
961 if ( isset( $params['validation-callback'] ) ) {
962 $this->mValidationCallback = $params['validation-callback'];
963 }
964
965 if ( isset( $params['filter-callback'] ) ) {
966 $this->mFilterCallback = $params['filter-callback'];
967 }
968 }
969
970 /**
971 * Get the complete table row for the input, including help text,
972 * labels, and whatever.
973 * @param $value String the value to set the input to.
974 * @return String complete HTML table row.
975 */
976 function getTableRow( $value ) {
977 # Check for invalid data.
978
979 $errors = $this->validate( $value, $this->mParent->mFieldData );
980
981 $cellAttributes = array();
982 $verticalLabel = false;
983
984 if ( !empty($this->mParams['vertical-label']) ) {
985 $cellAttributes['colspan'] = 2;
986 $verticalLabel = true;
987 }
988
989 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
990 $errors = '';
991 $errorClass = '';
992 } else {
993 $errors = self::formatErrors( $errors );
994 $errorClass = 'mw-htmlform-invalid-input';
995 }
996
997 $label = $this->getLabelHtml( $cellAttributes );
998 $field = Html::rawElement(
999 'td',
1000 array( 'class' => 'mw-input' ) + $cellAttributes,
1001 $this->getInputHTML( $value ) . "\n$errors"
1002 );
1003
1004 $fieldType = get_class( $this );
1005
1006 if ( $verticalLabel ) {
1007 $html = Html::rawElement( 'tr',
1008 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1009 $html .= Html::rawElement( 'tr',
1010 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1011 $field );
1012 } else {
1013 $html = Html::rawElement( 'tr',
1014 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1015 $label . $field );
1016 }
1017
1018 $helptext = null;
1019
1020 if ( isset( $this->mParams['help-message'] ) ) {
1021 $msg = wfMessage( $this->mParams['help-message'] );
1022 if ( $msg->exists() ) {
1023 $helptext = $msg->parse();
1024 }
1025 } elseif ( isset( $this->mParams['help-messages'] ) ) {
1026 # help-message can be passed a message key (string) or an array containing
1027 # a message key and additional parameters. This makes it impossible to pass
1028 # an array of message key
1029 foreach( $this->mParams['help-messages'] as $name ) {
1030 $msg = wfMessage( $name );
1031 if( $msg->exists() ) {
1032 $helptext .= $msg->parse(); // append message
1033 }
1034 }
1035 } elseif ( isset( $this->mParams['help'] ) ) {
1036 $helptext = $this->mParams['help'];
1037 }
1038
1039 if ( !is_null( $helptext ) ) {
1040 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1041 $helptext );
1042 $row = Html::rawElement( 'tr', array(), $row );
1043 $html .= "$row\n";
1044 }
1045
1046 return $html;
1047 }
1048
1049 function getLabel() {
1050 return $this->mLabel;
1051 }
1052 function getLabelHtml( $cellAttributes = array() ) {
1053 # Don't output a for= attribute for labels with no associated input.
1054 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1055 $for = array();
1056
1057 if ( $this->needsLabel() ) {
1058 $for['for'] = $this->mID;
1059 }
1060
1061 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1062 Html::rawElement( 'label', $for, $this->getLabel() )
1063 );
1064 }
1065
1066 function getDefault() {
1067 if ( isset( $this->mDefault ) ) {
1068 return $this->mDefault;
1069 } else {
1070 return null;
1071 }
1072 }
1073
1074 /**
1075 * Returns the attributes required for the tooltip and accesskey.
1076 *
1077 * @return array Attributes
1078 */
1079 public function getTooltipAndAccessKey() {
1080 if ( empty( $this->mParams['tooltip'] ) ) {
1081 return array();
1082 }
1083 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1084 }
1085
1086 /**
1087 * flatten an array of options to a single array, for instance,
1088 * a set of <options> inside <optgroups>.
1089 * @param $options Associative Array with values either Strings
1090 * or Arrays
1091 * @return Array flattened input
1092 */
1093 public static function flattenOptions( $options ) {
1094 $flatOpts = array();
1095
1096 foreach ( $options as $value ) {
1097 if ( is_array( $value ) ) {
1098 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1099 } else {
1100 $flatOpts[] = $value;
1101 }
1102 }
1103
1104 return $flatOpts;
1105 }
1106
1107 /**
1108 * Formats one or more errors as accepted by field validation-callback.
1109 * @param $errors String|Message|Array of strings or Message instances
1110 * @return String html
1111 * @since 1.18
1112 */
1113 protected static function formatErrors( $errors ) {
1114 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1115 $errors = array_shift( $errors );
1116 }
1117
1118 if ( is_array( $errors ) ) {
1119 $lines = array();
1120 foreach ( $errors as $error ) {
1121 if ( $error instanceof Message ) {
1122 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1123 } else {
1124 $lines[] = Html::rawElement( 'li', array(), $error );
1125 }
1126 }
1127 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1128 } else {
1129 if ( $errors instanceof Message ) {
1130 $errors = $errors->parse();
1131 }
1132 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1133 }
1134 }
1135 }
1136
1137 class HTMLTextField extends HTMLFormField {
1138 function getSize() {
1139 return isset( $this->mParams['size'] )
1140 ? $this->mParams['size']
1141 : 45;
1142 }
1143
1144 function getInputHTML( $value ) {
1145 $attribs = array(
1146 'id' => $this->mID,
1147 'name' => $this->mName,
1148 'size' => $this->getSize(),
1149 'value' => $value,
1150 ) + $this->getTooltipAndAccessKey();
1151
1152 if ( isset( $this->mParams['maxlength'] ) ) {
1153 $attribs['maxlength'] = $this->mParams['maxlength'];
1154 }
1155
1156 if ( !empty( $this->mParams['disabled'] ) ) {
1157 $attribs['disabled'] = 'disabled';
1158 }
1159
1160 # TODO: Enforce pattern, step, required, readonly on the server side as
1161 # well
1162 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1163 'placeholder' ) as $param ) {
1164 if ( isset( $this->mParams[$param] ) ) {
1165 $attribs[$param] = $this->mParams[$param];
1166 }
1167 }
1168
1169 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1170 if ( isset( $this->mParams[$param] ) ) {
1171 $attribs[$param] = '';
1172 }
1173 }
1174
1175 # Implement tiny differences between some field variants
1176 # here, rather than creating a new class for each one which
1177 # is essentially just a clone of this one.
1178 if ( isset( $this->mParams['type'] ) ) {
1179 switch ( $this->mParams['type'] ) {
1180 case 'email':
1181 $attribs['type'] = 'email';
1182 break;
1183 case 'int':
1184 $attribs['type'] = 'number';
1185 break;
1186 case 'float':
1187 $attribs['type'] = 'number';
1188 $attribs['step'] = 'any';
1189 break;
1190 # Pass through
1191 case 'password':
1192 case 'file':
1193 $attribs['type'] = $this->mParams['type'];
1194 break;
1195 }
1196 }
1197
1198 return Html::element( 'input', $attribs );
1199 }
1200 }
1201 class HTMLTextAreaField extends HTMLFormField {
1202 function getCols() {
1203 return isset( $this->mParams['cols'] )
1204 ? $this->mParams['cols']
1205 : 80;
1206 }
1207
1208 function getRows() {
1209 return isset( $this->mParams['rows'] )
1210 ? $this->mParams['rows']
1211 : 25;
1212 }
1213
1214 function getInputHTML( $value ) {
1215 $attribs = array(
1216 'id' => $this->mID,
1217 'name' => $this->mName,
1218 'cols' => $this->getCols(),
1219 'rows' => $this->getRows(),
1220 ) + $this->getTooltipAndAccessKey();
1221
1222
1223 if ( !empty( $this->mParams['disabled'] ) ) {
1224 $attribs['disabled'] = 'disabled';
1225 }
1226
1227 if ( !empty( $this->mParams['readonly'] ) ) {
1228 $attribs['readonly'] = 'readonly';
1229 }
1230
1231 foreach ( array( 'required', 'autofocus' ) as $param ) {
1232 if ( isset( $this->mParams[$param] ) ) {
1233 $attribs[$param] = '';
1234 }
1235 }
1236
1237 return Html::element( 'textarea', $attribs, $value );
1238 }
1239 }
1240
1241 /**
1242 * A field that will contain a numeric value
1243 */
1244 class HTMLFloatField extends HTMLTextField {
1245 function getSize() {
1246 return isset( $this->mParams['size'] )
1247 ? $this->mParams['size']
1248 : 20;
1249 }
1250
1251 function validate( $value, $alldata ) {
1252 $p = parent::validate( $value, $alldata );
1253
1254 if ( $p !== true ) {
1255 return $p;
1256 }
1257
1258 $value = trim( $value );
1259
1260 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1261 # with the addition that a leading '+' sign is ok.
1262 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1263 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1264 }
1265
1266 # The "int" part of these message names is rather confusing.
1267 # They make equal sense for all numbers.
1268 if ( isset( $this->mParams['min'] ) ) {
1269 $min = $this->mParams['min'];
1270
1271 if ( $min > $value ) {
1272 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1273 }
1274 }
1275
1276 if ( isset( $this->mParams['max'] ) ) {
1277 $max = $this->mParams['max'];
1278
1279 if ( $max < $value ) {
1280 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1281 }
1282 }
1283
1284 return true;
1285 }
1286 }
1287
1288 /**
1289 * A field that must contain a number
1290 */
1291 class HTMLIntField extends HTMLFloatField {
1292 function validate( $value, $alldata ) {
1293 $p = parent::validate( $value, $alldata );
1294
1295 if ( $p !== true ) {
1296 return $p;
1297 }
1298
1299 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1300 # with the addition that a leading '+' sign is ok. Note that leading zeros
1301 # are fine, and will be left in the input, which is useful for things like
1302 # phone numbers when you know that they are integers (the HTML5 type=tel
1303 # input does not require its value to be numeric). If you want a tidier
1304 # value to, eg, save in the DB, clean it up with intval().
1305 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1306 ) {
1307 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1308 }
1309
1310 return true;
1311 }
1312 }
1313
1314 /**
1315 * A checkbox field
1316 */
1317 class HTMLCheckField extends HTMLFormField {
1318 function getInputHTML( $value ) {
1319 if ( !empty( $this->mParams['invert'] ) ) {
1320 $value = !$value;
1321 }
1322
1323 $attr = $this->getTooltipAndAccessKey();
1324 $attr['id'] = $this->mID;
1325
1326 if ( !empty( $this->mParams['disabled'] ) ) {
1327 $attr['disabled'] = 'disabled';
1328 }
1329
1330 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1331 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1332 }
1333
1334 /**
1335 * For a checkbox, the label goes on the right hand side, and is
1336 * added in getInputHTML(), rather than HTMLFormField::getRow()
1337 * @return String
1338 */
1339 function getLabel() {
1340 return '&#160;';
1341 }
1342
1343 /**
1344 * @param $request WebRequest
1345 * @return String
1346 */
1347 function loadDataFromRequest( $request ) {
1348 $invert = false;
1349 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1350 $invert = true;
1351 }
1352
1353 // GetCheck won't work like we want for checks.
1354 if ( $request->getCheck( 'wpEditToken' ) || $this->mParent->getMethod() != 'post' ) {
1355 // XOR has the following truth table, which is what we want
1356 // INVERT VALUE | OUTPUT
1357 // true true | false
1358 // false true | true
1359 // false false | false
1360 // true false | true
1361 return $request->getBool( $this->mName ) xor $invert;
1362 } else {
1363 return $this->getDefault();
1364 }
1365 }
1366 }
1367
1368 /**
1369 * A select dropdown field. Basically a wrapper for Xmlselect class
1370 */
1371 class HTMLSelectField extends HTMLFormField {
1372 function validate( $value, $alldata ) {
1373 $p = parent::validate( $value, $alldata );
1374
1375 if ( $p !== true ) {
1376 return $p;
1377 }
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 $select->addOptions( $this->mParams['options'] );
1405
1406 return $select->getHTML();
1407 }
1408 }
1409
1410 /**
1411 * Select dropdown field, with an additional "other" textbox.
1412 */
1413 class HTMLSelectOrOtherField extends HTMLTextField {
1414 static $jsAdded = false;
1415
1416 function __construct( $params ) {
1417 if ( !in_array( 'other', $params['options'], true ) ) {
1418 $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
1419 $params['options'][$msg] = 'other';
1420 }
1421
1422 parent::__construct( $params );
1423 }
1424
1425 static function forceToStringRecursive( $array ) {
1426 if ( is_array( $array ) ) {
1427 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1428 } else {
1429 return strval( $array );
1430 }
1431 }
1432
1433 function getInputHTML( $value ) {
1434 $valInSelect = false;
1435
1436 if ( $value !== false ) {
1437 $valInSelect = in_array(
1438 $value,
1439 HTMLFormField::flattenOptions( $this->mParams['options'] )
1440 );
1441 }
1442
1443 $selected = $valInSelect ? $value : 'other';
1444
1445 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1446
1447 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1448 $select->addOptions( $opts );
1449
1450 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1451
1452 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1453
1454 if ( !empty( $this->mParams['disabled'] ) ) {
1455 $select->setAttribute( 'disabled', 'disabled' );
1456 $tbAttribs['disabled'] = 'disabled';
1457 }
1458
1459 $select = $select->getHTML();
1460
1461 if ( isset( $this->mParams['maxlength'] ) ) {
1462 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1463 }
1464
1465 $textbox = Html::input(
1466 $this->mName . '-other',
1467 $valInSelect ? '' : $value,
1468 'text',
1469 $tbAttribs
1470 );
1471
1472 return "$select<br />\n$textbox";
1473 }
1474
1475 /**
1476 * @param $request WebRequest
1477 * @return String
1478 */
1479 function loadDataFromRequest( $request ) {
1480 if ( $request->getCheck( $this->mName ) ) {
1481 $val = $request->getText( $this->mName );
1482
1483 if ( $val == 'other' ) {
1484 $val = $request->getText( $this->mName . '-other' );
1485 }
1486
1487 return $val;
1488 } else {
1489 return $this->getDefault();
1490 }
1491 }
1492 }
1493
1494 /**
1495 * Multi-select field
1496 */
1497 class HTMLMultiSelectField extends HTMLFormField {
1498
1499 public function __construct( $params ){
1500 parent::__construct( $params );
1501 if( isset( $params['flatlist'] ) ){
1502 $this->mClass .= ' mw-htmlform-multiselect-flatlist';
1503 }
1504 }
1505
1506 function validate( $value, $alldata ) {
1507 $p = parent::validate( $value, $alldata );
1508
1509 if ( $p !== true ) {
1510 return $p;
1511 }
1512
1513 if ( !is_array( $value ) ) {
1514 return false;
1515 }
1516
1517 # If all options are valid, array_intersect of the valid options
1518 # and the provided options will return the provided options.
1519 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1520
1521 $validValues = array_intersect( $value, $validOptions );
1522 if ( count( $validValues ) == count( $value ) ) {
1523 return true;
1524 } else {
1525 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1526 }
1527 }
1528
1529 function getInputHTML( $value ) {
1530 $html = $this->formatOptions( $this->mParams['options'], $value );
1531
1532 return $html;
1533 }
1534
1535 function formatOptions( $options, $value ) {
1536 $html = '';
1537
1538 $attribs = array();
1539
1540 if ( !empty( $this->mParams['disabled'] ) ) {
1541 $attribs['disabled'] = 'disabled';
1542 }
1543
1544 foreach ( $options as $label => $info ) {
1545 if ( is_array( $info ) ) {
1546 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1547 $html .= $this->formatOptions( $info, $value );
1548 } else {
1549 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1550
1551 $checkbox = Xml::check(
1552 $this->mName . '[]',
1553 in_array( $info, $value, true ),
1554 $attribs + $thisAttribs );
1555 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1556
1557 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
1558 }
1559 }
1560
1561 return $html;
1562 }
1563
1564 /**
1565 * @param $request WebRequest
1566 * @return String
1567 */
1568 function loadDataFromRequest( $request ) {
1569 if ( $this->mParent->getMethod() == 'post' ) {
1570 if( $request->wasPosted() ){
1571 # Checkboxes are just not added to the request arrays if they're not checked,
1572 # so it's perfectly possible for there not to be an entry at all
1573 return $request->getArray( $this->mName, array() );
1574 } else {
1575 # That's ok, the user has not yet submitted the form, so show the defaults
1576 return $this->getDefault();
1577 }
1578 } else {
1579 # This is the impossible case: if we look at $_GET and see no data for our
1580 # field, is it because the user has not yet submitted the form, or that they
1581 # have submitted it with all the options unchecked? We will have to assume the
1582 # latter, which basically means that you can't specify 'positive' defaults
1583 # for GET forms.
1584 # @todo FIXME...
1585 return $request->getArray( $this->mName, array() );
1586 }
1587 }
1588
1589 function getDefault() {
1590 if ( isset( $this->mDefault ) ) {
1591 return $this->mDefault;
1592 } else {
1593 return array();
1594 }
1595 }
1596
1597 protected function needsLabel() {
1598 return false;
1599 }
1600 }
1601
1602 /**
1603 * Double field with a dropdown list constructed from a system message in the format
1604 * * Optgroup header
1605 * ** <option value>
1606 * * New Optgroup header
1607 * Plus a text field underneath for an additional reason. The 'value' of the field is
1608 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1609 * select dropdown.
1610 * @todo FIXME: If made 'required', only the text field should be compulsory.
1611 */
1612 class HTMLSelectAndOtherField extends HTMLSelectField {
1613
1614 function __construct( $params ) {
1615 if ( array_key_exists( 'other', $params ) ) {
1616 } elseif( array_key_exists( 'other-message', $params ) ){
1617 $params['other'] = wfMessage( $params['other-message'] )->plain();
1618 } else {
1619 $params['other'] = null;
1620 }
1621
1622 if ( array_key_exists( 'options', $params ) ) {
1623 # Options array already specified
1624 } elseif( array_key_exists( 'options-message', $params ) ){
1625 # Generate options array from a system message
1626 $params['options'] = self::parseMessage(
1627 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1628 $params['other']
1629 );
1630 } else {
1631 # Sulk
1632 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1633 }
1634 $this->mFlatOptions = self::flattenOptions( $params['options'] );
1635
1636 parent::__construct( $params );
1637 }
1638
1639 /**
1640 * Build a drop-down box from a textual list.
1641 * @param $string String message text
1642 * @param $otherName String name of "other reason" option
1643 * @return Array
1644 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1645 */
1646 public static function parseMessage( $string, $otherName=null ) {
1647 if( $otherName === null ){
1648 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1649 }
1650
1651 $optgroup = false;
1652 $options = array( $otherName => 'other' );
1653
1654 foreach ( explode( "\n", $string ) as $option ) {
1655 $value = trim( $option );
1656 if ( $value == '' ) {
1657 continue;
1658 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1659 # A new group is starting...
1660 $value = trim( substr( $value, 1 ) );
1661 $optgroup = $value;
1662 } elseif ( substr( $value, 0, 2) == '**' ) {
1663 # groupmember
1664 $opt = trim( substr( $value, 2 ) );
1665 if( $optgroup === false ){
1666 $options[$opt] = $opt;
1667 } else {
1668 $options[$optgroup][$opt] = $opt;
1669 }
1670 } else {
1671 # groupless reason list
1672 $optgroup = false;
1673 $options[$option] = $option;
1674 }
1675 }
1676
1677 return $options;
1678 }
1679
1680 function getInputHTML( $value ) {
1681 $select = parent::getInputHTML( $value[1] );
1682
1683 $textAttribs = array(
1684 'id' => $this->mID . '-other',
1685 'size' => $this->getSize(),
1686 );
1687
1688 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1689 if ( isset( $this->mParams[$param] ) ) {
1690 $textAttribs[$param] = '';
1691 }
1692 }
1693
1694 $textbox = Html::input(
1695 $this->mName . '-other',
1696 $value[2],
1697 'text',
1698 $textAttribs
1699 );
1700
1701 return "$select<br />\n$textbox";
1702 }
1703
1704 /**
1705 * @param $request WebRequest
1706 * @return Array( <overall message>, <select value>, <text field value> )
1707 */
1708 function loadDataFromRequest( $request ) {
1709 if ( $request->getCheck( $this->mName ) ) {
1710
1711 $list = $request->getText( $this->mName );
1712 $text = $request->getText( $this->mName . '-other' );
1713
1714 if ( $list == 'other' ) {
1715 $final = $text;
1716 } elseif( !in_array( $list, $this->mFlatOptions ) ){
1717 # User has spoofed the select form to give an option which wasn't
1718 # in the original offer. Sulk...
1719 $final = $text;
1720 } elseif( $text == '' ) {
1721 $final = $list;
1722 } else {
1723 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1724 }
1725
1726 } else {
1727 $final = $this->getDefault();
1728
1729 $list = 'other';
1730 $text = $final;
1731 foreach ( $this->mFlatOptions as $option ) {
1732 $match = $option . wfMsgForContent( 'colon-separator' );
1733 if( strpos( $text, $match ) === 0 ) {
1734 $list = $option;
1735 $text = substr( $text, strlen( $match ) );
1736 break;
1737 }
1738 }
1739 }
1740 return array( $final, $list, $text );
1741 }
1742
1743 function getSize() {
1744 return isset( $this->mParams['size'] )
1745 ? $this->mParams['size']
1746 : 45;
1747 }
1748
1749 function validate( $value, $alldata ) {
1750 # HTMLSelectField forces $value to be one of the options in the select
1751 # field, which is not useful here. But we do want the validation further up
1752 # the chain
1753 $p = parent::validate( $value[1], $alldata );
1754
1755 if ( $p !== true ) {
1756 return $p;
1757 }
1758
1759 if( isset( $this->mParams['required'] ) && $value[1] === '' ){
1760 return wfMsgExt( 'htmlform-required', 'parseinline' );
1761 }
1762
1763 return true;
1764 }
1765 }
1766
1767 /**
1768 * Radio checkbox fields.
1769 */
1770 class HTMLRadioField extends HTMLFormField {
1771 function validate( $value, $alldata ) {
1772 $p = parent::validate( $value, $alldata );
1773
1774 if ( $p !== true ) {
1775 return $p;
1776 }
1777
1778 if ( !is_string( $value ) && !is_int( $value ) ) {
1779 return false;
1780 }
1781
1782 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1783
1784 if ( in_array( $value, $validOptions ) ) {
1785 return true;
1786 } else {
1787 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1788 }
1789 }
1790
1791 /**
1792 * This returns a block of all the radio options, in one cell.
1793 * @see includes/HTMLFormField#getInputHTML()
1794 * @param $value String
1795 * @return String
1796 */
1797 function getInputHTML( $value ) {
1798 $html = $this->formatOptions( $this->mParams['options'], $value );
1799
1800 return $html;
1801 }
1802
1803 function formatOptions( $options, $value ) {
1804 $html = '';
1805
1806 $attribs = array();
1807 if ( !empty( $this->mParams['disabled'] ) ) {
1808 $attribs['disabled'] = 'disabled';
1809 }
1810
1811 # TODO: should this produce an unordered list perhaps?
1812 foreach ( $options as $label => $info ) {
1813 if ( is_array( $info ) ) {
1814 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1815 $html .= $this->formatOptions( $info, $value );
1816 } else {
1817 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1818 $html .= Xml::radio(
1819 $this->mName,
1820 $info,
1821 $info == $value,
1822 $attribs + array( 'id' => $id )
1823 );
1824 $html .= '&#160;' .
1825 Html::rawElement( 'label', array( 'for' => $id ), $label );
1826
1827 $html .= "<br />\n";
1828 }
1829 }
1830
1831 return $html;
1832 }
1833
1834 protected function needsLabel() {
1835 return false;
1836 }
1837 }
1838
1839 /**
1840 * An information field (text blob), not a proper input.
1841 */
1842 class HTMLInfoField extends HTMLFormField {
1843 function __construct( $info ) {
1844 $info['nodata'] = true;
1845
1846 parent::__construct( $info );
1847 }
1848
1849 function getInputHTML( $value ) {
1850 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1851 }
1852
1853 function getTableRow( $value ) {
1854 if ( !empty( $this->mParams['rawrow'] ) ) {
1855 return $value;
1856 }
1857
1858 return parent::getTableRow( $value );
1859 }
1860
1861 protected function needsLabel() {
1862 return false;
1863 }
1864 }
1865
1866 class HTMLHiddenField extends HTMLFormField {
1867 public function __construct( $params ) {
1868 parent::__construct( $params );
1869
1870 # Per HTML5 spec, hidden fields cannot be 'required'
1871 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1872 unset( $this->mParams['required'] );
1873 }
1874
1875 public function getTableRow( $value ) {
1876 $params = array();
1877 if ( $this->mID ) {
1878 $params['id'] = $this->mID;
1879 }
1880
1881 $this->mParent->addHiddenField(
1882 $this->mName,
1883 $this->mDefault,
1884 $params
1885 );
1886
1887 return '';
1888 }
1889
1890 public function getInputHTML( $value ) { return ''; }
1891 }
1892
1893 /**
1894 * Add a submit button inline in the form (as opposed to
1895 * HTMLForm::addButton(), which will add it at the end).
1896 */
1897 class HTMLSubmitField extends HTMLFormField {
1898
1899 function __construct( $info ) {
1900 $info['nodata'] = true;
1901 parent::__construct( $info );
1902 }
1903
1904 function getInputHTML( $value ) {
1905 return Xml::submitButton(
1906 $value,
1907 array(
1908 'class' => 'mw-htmlform-submit',
1909 'name' => $this->mName,
1910 'id' => $this->mID,
1911 )
1912 );
1913 }
1914
1915 protected function needsLabel() {
1916 return false;
1917 }
1918
1919 /**
1920 * Button cannot be invalid
1921 * @param $value String
1922 * @param $alldata Array
1923 * @return Bool
1924 */
1925 public function validate( $value, $alldata ){
1926 return true;
1927 }
1928 }
1929
1930 class HTMLEditTools extends HTMLFormField {
1931 public function getInputHTML( $value ) {
1932 return '';
1933 }
1934
1935 public function getTableRow( $value ) {
1936 if ( empty( $this->mParams['message'] ) ) {
1937 $msg = wfMessage( 'edittools' );
1938 } else {
1939 $msg = wfMessage( $this->mParams['message'] );
1940 if ( $msg->isDisabled() ) {
1941 $msg = wfMessage( 'edittools' );
1942 }
1943 }
1944 $msg->inContentLanguage();
1945
1946
1947 return '<tr><td></td><td class="mw-input">'
1948 . '<div class="mw-editTools">'
1949 . $msg->parseAsBlock()
1950 . "</div></td></tr>\n";
1951 }
1952 }