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