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