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