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