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