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