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