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