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