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