Merge "[FileBackend] Added some basic directory functions."
[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 $wgArticlePath;
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 ( strpos( $wgArticlePath, '?' ) !== false && $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 )->text() );
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 if( is_null( $helptext ) ) {
1100 $helptext = '';
1101 } else {
1102 $helptext .= wfMessage( 'word-separator' )->escaped(); // some space
1103 }
1104 $helptext .= $msg->parse(); // Append message
1105 }
1106 }
1107 }
1108 elseif ( isset( $this->mParams['help'] ) ) {
1109 $helptext = $this->mParams['help'];
1110 }
1111
1112 if ( !is_null( $helptext ) ) {
1113 $row = Html::rawElement(
1114 'td',
1115 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1116 $helptext
1117 );
1118 $row = Html::rawElement( 'tr', array(), $row );
1119 $html .= "$row\n";
1120 }
1121
1122 return $html;
1123 }
1124
1125 function getLabel() {
1126 return $this->mLabel;
1127 }
1128 function getLabelHtml( $cellAttributes = array() ) {
1129 # Don't output a for= attribute for labels with no associated input.
1130 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1131 $for = array();
1132
1133 if ( $this->needsLabel() ) {
1134 $for['for'] = $this->mID;
1135 }
1136
1137 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1138 Html::rawElement( 'label', $for, $this->getLabel() )
1139 );
1140 }
1141
1142 function getDefault() {
1143 if ( isset( $this->mDefault ) ) {
1144 return $this->mDefault;
1145 } else {
1146 return null;
1147 }
1148 }
1149
1150 /**
1151 * Returns the attributes required for the tooltip and accesskey.
1152 *
1153 * @return array Attributes
1154 */
1155 public function getTooltipAndAccessKey() {
1156 if ( empty( $this->mParams['tooltip'] ) ) {
1157 return array();
1158 }
1159 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1160 }
1161
1162 /**
1163 * flatten an array of options to a single array, for instance,
1164 * a set of <options> inside <optgroups>.
1165 * @param $options array Associative Array with values either Strings
1166 * or Arrays
1167 * @return Array flattened input
1168 */
1169 public static function flattenOptions( $options ) {
1170 $flatOpts = array();
1171
1172 foreach ( $options as $value ) {
1173 if ( is_array( $value ) ) {
1174 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1175 } else {
1176 $flatOpts[] = $value;
1177 }
1178 }
1179
1180 return $flatOpts;
1181 }
1182
1183 /**
1184 * Formats one or more errors as accepted by field validation-callback.
1185 * @param $errors String|Message|Array of strings or Message instances
1186 * @return String html
1187 * @since 1.18
1188 */
1189 protected static function formatErrors( $errors ) {
1190 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1191 $errors = array_shift( $errors );
1192 }
1193
1194 if ( is_array( $errors ) ) {
1195 $lines = array();
1196 foreach ( $errors as $error ) {
1197 if ( $error instanceof Message ) {
1198 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1199 } else {
1200 $lines[] = Html::rawElement( 'li', array(), $error );
1201 }
1202 }
1203 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1204 } else {
1205 if ( $errors instanceof Message ) {
1206 $errors = $errors->parse();
1207 }
1208 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1209 }
1210 }
1211 }
1212
1213 class HTMLTextField extends HTMLFormField {
1214 function getSize() {
1215 return isset( $this->mParams['size'] )
1216 ? $this->mParams['size']
1217 : 45;
1218 }
1219
1220 function getInputHTML( $value ) {
1221 $attribs = array(
1222 'id' => $this->mID,
1223 'name' => $this->mName,
1224 'size' => $this->getSize(),
1225 'value' => $value,
1226 ) + $this->getTooltipAndAccessKey();
1227
1228 if ( $this->mClass !== '' ) {
1229 $attribs['class'] = $this->mClass;
1230 }
1231
1232 if ( isset( $this->mParams['maxlength'] ) ) {
1233 $attribs['maxlength'] = $this->mParams['maxlength'];
1234 }
1235
1236 if ( !empty( $this->mParams['disabled'] ) ) {
1237 $attribs['disabled'] = 'disabled';
1238 }
1239
1240 # TODO: Enforce pattern, step, required, readonly on the server side as
1241 # well
1242 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1243 'placeholder' ) as $param ) {
1244 if ( isset( $this->mParams[$param] ) ) {
1245 $attribs[$param] = $this->mParams[$param];
1246 }
1247 }
1248
1249 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1250 if ( isset( $this->mParams[$param] ) ) {
1251 $attribs[$param] = '';
1252 }
1253 }
1254
1255 # Implement tiny differences between some field variants
1256 # here, rather than creating a new class for each one which
1257 # is essentially just a clone of this one.
1258 if ( isset( $this->mParams['type'] ) ) {
1259 switch ( $this->mParams['type'] ) {
1260 case 'email':
1261 $attribs['type'] = 'email';
1262 break;
1263 case 'int':
1264 $attribs['type'] = 'number';
1265 break;
1266 case 'float':
1267 $attribs['type'] = 'number';
1268 $attribs['step'] = 'any';
1269 break;
1270 # Pass through
1271 case 'password':
1272 case 'file':
1273 $attribs['type'] = $this->mParams['type'];
1274 break;
1275 }
1276 }
1277
1278 return Html::element( 'input', $attribs );
1279 }
1280 }
1281 class HTMLTextAreaField extends HTMLFormField {
1282 function getCols() {
1283 return isset( $this->mParams['cols'] )
1284 ? $this->mParams['cols']
1285 : 80;
1286 }
1287
1288 function getRows() {
1289 return isset( $this->mParams['rows'] )
1290 ? $this->mParams['rows']
1291 : 25;
1292 }
1293
1294 function getInputHTML( $value ) {
1295 $attribs = array(
1296 'id' => $this->mID,
1297 'name' => $this->mName,
1298 'cols' => $this->getCols(),
1299 'rows' => $this->getRows(),
1300 ) + $this->getTooltipAndAccessKey();
1301
1302 if ( $this->mClass !== '' ) {
1303 $attribs['class'] = $this->mClass;
1304 }
1305
1306 if ( !empty( $this->mParams['disabled'] ) ) {
1307 $attribs['disabled'] = 'disabled';
1308 }
1309
1310 if ( !empty( $this->mParams['readonly'] ) ) {
1311 $attribs['readonly'] = 'readonly';
1312 }
1313
1314 if ( isset( $this->mParams['placeholder'] ) ) {
1315 $attribs['placeholder'] = $this->mParams['placeholder'];
1316 }
1317
1318 foreach ( array( 'required', 'autofocus' ) as $param ) {
1319 if ( isset( $this->mParams[$param] ) ) {
1320 $attribs[$param] = '';
1321 }
1322 }
1323
1324 return Html::element( 'textarea', $attribs, $value );
1325 }
1326 }
1327
1328 /**
1329 * A field that will contain a numeric value
1330 */
1331 class HTMLFloatField extends HTMLTextField {
1332 function getSize() {
1333 return isset( $this->mParams['size'] )
1334 ? $this->mParams['size']
1335 : 20;
1336 }
1337
1338 function validate( $value, $alldata ) {
1339 $p = parent::validate( $value, $alldata );
1340
1341 if ( $p !== true ) {
1342 return $p;
1343 }
1344
1345 $value = trim( $value );
1346
1347 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1348 # with the addition that a leading '+' sign is ok.
1349 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1350 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1351 }
1352
1353 # The "int" part of these message names is rather confusing.
1354 # They make equal sense for all numbers.
1355 if ( isset( $this->mParams['min'] ) ) {
1356 $min = $this->mParams['min'];
1357
1358 if ( $min > $value ) {
1359 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1360 }
1361 }
1362
1363 if ( isset( $this->mParams['max'] ) ) {
1364 $max = $this->mParams['max'];
1365
1366 if ( $max < $value ) {
1367 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1368 }
1369 }
1370
1371 return true;
1372 }
1373 }
1374
1375 /**
1376 * A field that must contain a number
1377 */
1378 class HTMLIntField extends HTMLFloatField {
1379 function validate( $value, $alldata ) {
1380 $p = parent::validate( $value, $alldata );
1381
1382 if ( $p !== true ) {
1383 return $p;
1384 }
1385
1386 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1387 # with the addition that a leading '+' sign is ok. Note that leading zeros
1388 # are fine, and will be left in the input, which is useful for things like
1389 # phone numbers when you know that they are integers (the HTML5 type=tel
1390 # input does not require its value to be numeric). If you want a tidier
1391 # value to, eg, save in the DB, clean it up with intval().
1392 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1393 ) {
1394 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1395 }
1396
1397 return true;
1398 }
1399 }
1400
1401 /**
1402 * A checkbox field
1403 */
1404 class HTMLCheckField extends HTMLFormField {
1405 function getInputHTML( $value ) {
1406 if ( !empty( $this->mParams['invert'] ) ) {
1407 $value = !$value;
1408 }
1409
1410 $attr = $this->getTooltipAndAccessKey();
1411 $attr['id'] = $this->mID;
1412
1413 if ( !empty( $this->mParams['disabled'] ) ) {
1414 $attr['disabled'] = 'disabled';
1415 }
1416
1417 if ( $this->mClass !== '' ) {
1418 $attr['class'] = $this->mClass;
1419 }
1420
1421 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1422 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1423 }
1424
1425 /**
1426 * For a checkbox, the label goes on the right hand side, and is
1427 * added in getInputHTML(), rather than HTMLFormField::getRow()
1428 * @return String
1429 */
1430 function getLabel() {
1431 return '&#160;';
1432 }
1433
1434 /**
1435 * @param $request WebRequest
1436 * @return String
1437 */
1438 function loadDataFromRequest( $request ) {
1439 $invert = false;
1440 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1441 $invert = true;
1442 }
1443
1444 // GetCheck won't work like we want for checks.
1445 // Fetch the value in either one of the two following case:
1446 // - we have a valid token (form got posted or GET forged by the user)
1447 // - checkbox name has a value (false or true), ie is not null
1448 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName )!== null ) {
1449 // XOR has the following truth table, which is what we want
1450 // INVERT VALUE | OUTPUT
1451 // true true | false
1452 // false true | true
1453 // false false | false
1454 // true false | true
1455 return $request->getBool( $this->mName ) xor $invert;
1456 } else {
1457 return $this->getDefault();
1458 }
1459 }
1460 }
1461
1462 /**
1463 * A select dropdown field. Basically a wrapper for Xmlselect class
1464 */
1465 class HTMLSelectField extends HTMLFormField {
1466 function validate( $value, $alldata ) {
1467 $p = parent::validate( $value, $alldata );
1468
1469 if ( $p !== true ) {
1470 return $p;
1471 }
1472
1473 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1474
1475 if ( in_array( $value, $validOptions ) )
1476 return true;
1477 else
1478 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1479 }
1480
1481 function getInputHTML( $value ) {
1482 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1483
1484 # If one of the options' 'name' is int(0), it is automatically selected.
1485 # because PHP sucks and thinks int(0) == 'some string'.
1486 # Working around this by forcing all of them to strings.
1487 foreach( $this->mParams['options'] as &$opt ){
1488 if( is_int( $opt ) ){
1489 $opt = strval( $opt );
1490 }
1491 }
1492 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1493
1494 if ( !empty( $this->mParams['disabled'] ) ) {
1495 $select->setAttribute( 'disabled', 'disabled' );
1496 }
1497
1498 if ( $this->mClass !== '' ) {
1499 $select->setAttribute( 'class', $this->mClass );
1500 }
1501
1502 $select->addOptions( $this->mParams['options'] );
1503
1504 return $select->getHTML();
1505 }
1506 }
1507
1508 /**
1509 * Select dropdown field, with an additional "other" textbox.
1510 */
1511 class HTMLSelectOrOtherField extends HTMLTextField {
1512 static $jsAdded = false;
1513
1514 function __construct( $params ) {
1515 if ( !in_array( 'other', $params['options'], true ) ) {
1516 $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
1517 $params['options'][$msg] = 'other';
1518 }
1519
1520 parent::__construct( $params );
1521 }
1522
1523 static function forceToStringRecursive( $array ) {
1524 if ( is_array( $array ) ) {
1525 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1526 } else {
1527 return strval( $array );
1528 }
1529 }
1530
1531 function getInputHTML( $value ) {
1532 $valInSelect = false;
1533
1534 if ( $value !== false ) {
1535 $valInSelect = in_array(
1536 $value,
1537 HTMLFormField::flattenOptions( $this->mParams['options'] )
1538 );
1539 }
1540
1541 $selected = $valInSelect ? $value : 'other';
1542
1543 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1544
1545 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1546 $select->addOptions( $opts );
1547
1548 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1549
1550 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1551
1552 if ( !empty( $this->mParams['disabled'] ) ) {
1553 $select->setAttribute( 'disabled', 'disabled' );
1554 $tbAttribs['disabled'] = 'disabled';
1555 }
1556
1557 $select = $select->getHTML();
1558
1559 if ( isset( $this->mParams['maxlength'] ) ) {
1560 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1561 }
1562
1563 if ( $this->mClass !== '' ) {
1564 $tbAttribs['class'] = $this->mClass;
1565 }
1566
1567 $textbox = Html::input(
1568 $this->mName . '-other',
1569 $valInSelect ? '' : $value,
1570 'text',
1571 $tbAttribs
1572 );
1573
1574 return "$select<br />\n$textbox";
1575 }
1576
1577 /**
1578 * @param $request WebRequest
1579 * @return String
1580 */
1581 function loadDataFromRequest( $request ) {
1582 if ( $request->getCheck( $this->mName ) ) {
1583 $val = $request->getText( $this->mName );
1584
1585 if ( $val == 'other' ) {
1586 $val = $request->getText( $this->mName . '-other' );
1587 }
1588
1589 return $val;
1590 } else {
1591 return $this->getDefault();
1592 }
1593 }
1594 }
1595
1596 /**
1597 * Multi-select field
1598 */
1599 class HTMLMultiSelectField extends HTMLFormField {
1600
1601 function validate( $value, $alldata ) {
1602 $p = parent::validate( $value, $alldata );
1603
1604 if ( $p !== true ) {
1605 return $p;
1606 }
1607
1608 if ( !is_array( $value ) ) {
1609 return false;
1610 }
1611
1612 # If all options are valid, array_intersect of the valid options
1613 # and the provided options will return the provided options.
1614 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1615
1616 $validValues = array_intersect( $value, $validOptions );
1617 if ( count( $validValues ) == count( $value ) ) {
1618 return true;
1619 } else {
1620 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1621 }
1622 }
1623
1624 function getInputHTML( $value ) {
1625 $html = $this->formatOptions( $this->mParams['options'], $value );
1626
1627 return $html;
1628 }
1629
1630 function formatOptions( $options, $value ) {
1631 $html = '';
1632
1633 $attribs = array();
1634
1635 if ( !empty( $this->mParams['disabled'] ) ) {
1636 $attribs['disabled'] = 'disabled';
1637 }
1638
1639 foreach ( $options as $label => $info ) {
1640 if ( is_array( $info ) ) {
1641 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1642 $html .= $this->formatOptions( $info, $value );
1643 } else {
1644 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1645
1646 $checkbox = Xml::check(
1647 $this->mName . '[]',
1648 in_array( $info, $value, true ),
1649 $attribs + $thisAttribs );
1650 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1651
1652 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1653 }
1654 }
1655
1656 return $html;
1657 }
1658
1659 /**
1660 * @param $request WebRequest
1661 * @return String
1662 */
1663 function loadDataFromRequest( $request ) {
1664 if ( $this->mParent->getMethod() == 'post' ) {
1665 if( $request->wasPosted() ){
1666 # Checkboxes are just not added to the request arrays if they're not checked,
1667 # so it's perfectly possible for there not to be an entry at all
1668 return $request->getArray( $this->mName, array() );
1669 } else {
1670 # That's ok, the user has not yet submitted the form, so show the defaults
1671 return $this->getDefault();
1672 }
1673 } else {
1674 # This is the impossible case: if we look at $_GET and see no data for our
1675 # field, is it because the user has not yet submitted the form, or that they
1676 # have submitted it with all the options unchecked? We will have to assume the
1677 # latter, which basically means that you can't specify 'positive' defaults
1678 # for GET forms.
1679 # @todo FIXME...
1680 return $request->getArray( $this->mName, array() );
1681 }
1682 }
1683
1684 function getDefault() {
1685 if ( isset( $this->mDefault ) ) {
1686 return $this->mDefault;
1687 } else {
1688 return array();
1689 }
1690 }
1691
1692 protected function needsLabel() {
1693 return false;
1694 }
1695 }
1696
1697 /**
1698 * Double field with a dropdown list constructed from a system message in the format
1699 * * Optgroup header
1700 * ** <option value>
1701 * * New Optgroup header
1702 * Plus a text field underneath for an additional reason. The 'value' of the field is
1703 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1704 * select dropdown.
1705 * @todo FIXME: If made 'required', only the text field should be compulsory.
1706 */
1707 class HTMLSelectAndOtherField extends HTMLSelectField {
1708
1709 function __construct( $params ) {
1710 if ( array_key_exists( 'other', $params ) ) {
1711 } elseif( array_key_exists( 'other-message', $params ) ){
1712 $params['other'] = wfMessage( $params['other-message'] )->plain();
1713 } else {
1714 $params['other'] = null;
1715 }
1716
1717 if ( array_key_exists( 'options', $params ) ) {
1718 # Options array already specified
1719 } elseif( array_key_exists( 'options-message', $params ) ){
1720 # Generate options array from a system message
1721 $params['options'] = self::parseMessage(
1722 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1723 $params['other']
1724 );
1725 } else {
1726 # Sulk
1727 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1728 }
1729 $this->mFlatOptions = self::flattenOptions( $params['options'] );
1730
1731 parent::__construct( $params );
1732 }
1733
1734 /**
1735 * Build a drop-down box from a textual list.
1736 * @param $string String message text
1737 * @param $otherName String name of "other reason" option
1738 * @return Array
1739 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1740 */
1741 public static function parseMessage( $string, $otherName=null ) {
1742 if( $otherName === null ){
1743 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1744 }
1745
1746 $optgroup = false;
1747 $options = array( $otherName => 'other' );
1748
1749 foreach ( explode( "\n", $string ) as $option ) {
1750 $value = trim( $option );
1751 if ( $value == '' ) {
1752 continue;
1753 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1754 # A new group is starting...
1755 $value = trim( substr( $value, 1 ) );
1756 $optgroup = $value;
1757 } elseif ( substr( $value, 0, 2) == '**' ) {
1758 # groupmember
1759 $opt = trim( substr( $value, 2 ) );
1760 if( $optgroup === false ){
1761 $options[$opt] = $opt;
1762 } else {
1763 $options[$optgroup][$opt] = $opt;
1764 }
1765 } else {
1766 # groupless reason list
1767 $optgroup = false;
1768 $options[$option] = $option;
1769 }
1770 }
1771
1772 return $options;
1773 }
1774
1775 function getInputHTML( $value ) {
1776 $select = parent::getInputHTML( $value[1] );
1777
1778 $textAttribs = array(
1779 'id' => $this->mID . '-other',
1780 'size' => $this->getSize(),
1781 );
1782
1783 if ( $this->mClass !== '' ) {
1784 $textAttribs['class'] = $this->mClass;
1785 }
1786
1787 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1788 if ( isset( $this->mParams[$param] ) ) {
1789 $textAttribs[$param] = '';
1790 }
1791 }
1792
1793 $textbox = Html::input(
1794 $this->mName . '-other',
1795 $value[2],
1796 'text',
1797 $textAttribs
1798 );
1799
1800 return "$select<br />\n$textbox";
1801 }
1802
1803 /**
1804 * @param $request WebRequest
1805 * @return Array( <overall message>, <select value>, <text field value> )
1806 */
1807 function loadDataFromRequest( $request ) {
1808 if ( $request->getCheck( $this->mName ) ) {
1809
1810 $list = $request->getText( $this->mName );
1811 $text = $request->getText( $this->mName . '-other' );
1812
1813 if ( $list == 'other' ) {
1814 $final = $text;
1815 } elseif( !in_array( $list, $this->mFlatOptions ) ){
1816 # User has spoofed the select form to give an option which wasn't
1817 # in the original offer. Sulk...
1818 $final = $text;
1819 } elseif( $text == '' ) {
1820 $final = $list;
1821 } else {
1822 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1823 }
1824
1825 } else {
1826 $final = $this->getDefault();
1827
1828 $list = 'other';
1829 $text = $final;
1830 foreach ( $this->mFlatOptions as $option ) {
1831 $match = $option . wfMsgForContent( 'colon-separator' );
1832 if( strpos( $text, $match ) === 0 ) {
1833 $list = $option;
1834 $text = substr( $text, strlen( $match ) );
1835 break;
1836 }
1837 }
1838 }
1839 return array( $final, $list, $text );
1840 }
1841
1842 function getSize() {
1843 return isset( $this->mParams['size'] )
1844 ? $this->mParams['size']
1845 : 45;
1846 }
1847
1848 function validate( $value, $alldata ) {
1849 # HTMLSelectField forces $value to be one of the options in the select
1850 # field, which is not useful here. But we do want the validation further up
1851 # the chain
1852 $p = parent::validate( $value[1], $alldata );
1853
1854 if ( $p !== true ) {
1855 return $p;
1856 }
1857
1858 if( isset( $this->mParams['required'] ) && $value[1] === '' ){
1859 return wfMsgExt( 'htmlform-required', 'parseinline' );
1860 }
1861
1862 return true;
1863 }
1864 }
1865
1866 /**
1867 * Radio checkbox fields.
1868 */
1869 class HTMLRadioField extends HTMLFormField {
1870
1871
1872 function validate( $value, $alldata ) {
1873 $p = parent::validate( $value, $alldata );
1874
1875 if ( $p !== true ) {
1876 return $p;
1877 }
1878
1879 if ( !is_string( $value ) && !is_int( $value ) ) {
1880 return false;
1881 }
1882
1883 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1884
1885 if ( in_array( $value, $validOptions ) ) {
1886 return true;
1887 } else {
1888 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1889 }
1890 }
1891
1892 /**
1893 * This returns a block of all the radio options, in one cell.
1894 * @see includes/HTMLFormField#getInputHTML()
1895 * @param $value String
1896 * @return String
1897 */
1898 function getInputHTML( $value ) {
1899 $html = $this->formatOptions( $this->mParams['options'], $value );
1900
1901 return $html;
1902 }
1903
1904 function formatOptions( $options, $value ) {
1905 $html = '';
1906
1907 $attribs = array();
1908 if ( !empty( $this->mParams['disabled'] ) ) {
1909 $attribs['disabled'] = 'disabled';
1910 }
1911
1912 # TODO: should this produce an unordered list perhaps?
1913 foreach ( $options as $label => $info ) {
1914 if ( is_array( $info ) ) {
1915 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1916 $html .= $this->formatOptions( $info, $value );
1917 } else {
1918 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1919 $radio = Xml::radio(
1920 $this->mName,
1921 $info,
1922 $info == $value,
1923 $attribs + array( 'id' => $id )
1924 );
1925 $radio .= '&#160;' .
1926 Html::rawElement( 'label', array( 'for' => $id ), $label );
1927
1928 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
1929 }
1930 }
1931
1932 return $html;
1933 }
1934
1935 protected function needsLabel() {
1936 return false;
1937 }
1938 }
1939
1940 /**
1941 * An information field (text blob), not a proper input.
1942 */
1943 class HTMLInfoField extends HTMLFormField {
1944 function __construct( $info ) {
1945 $info['nodata'] = true;
1946
1947 parent::__construct( $info );
1948 }
1949
1950 function getInputHTML( $value ) {
1951 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1952 }
1953
1954 function getTableRow( $value ) {
1955 if ( !empty( $this->mParams['rawrow'] ) ) {
1956 return $value;
1957 }
1958
1959 return parent::getTableRow( $value );
1960 }
1961
1962 protected function needsLabel() {
1963 return false;
1964 }
1965 }
1966
1967 class HTMLHiddenField extends HTMLFormField {
1968 public function __construct( $params ) {
1969 parent::__construct( $params );
1970
1971 # Per HTML5 spec, hidden fields cannot be 'required'
1972 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1973 unset( $this->mParams['required'] );
1974 }
1975
1976 public function getTableRow( $value ) {
1977 $params = array();
1978 if ( $this->mID ) {
1979 $params['id'] = $this->mID;
1980 }
1981
1982 $this->mParent->addHiddenField(
1983 $this->mName,
1984 $this->mDefault,
1985 $params
1986 );
1987
1988 return '';
1989 }
1990
1991 public function getInputHTML( $value ) { return ''; }
1992 }
1993
1994 /**
1995 * Add a submit button inline in the form (as opposed to
1996 * HTMLForm::addButton(), which will add it at the end).
1997 */
1998 class HTMLSubmitField extends HTMLFormField {
1999
2000 function __construct( $info ) {
2001 $info['nodata'] = true;
2002 parent::__construct( $info );
2003 }
2004
2005 function getInputHTML( $value ) {
2006 return Xml::submitButton(
2007 $value,
2008 array(
2009 'class' => 'mw-htmlform-submit ' . $this->mClass,
2010 'name' => $this->mName,
2011 'id' => $this->mID,
2012 )
2013 );
2014 }
2015
2016 protected function needsLabel() {
2017 return false;
2018 }
2019
2020 /**
2021 * Button cannot be invalid
2022 * @param $value String
2023 * @param $alldata Array
2024 * @return Bool
2025 */
2026 public function validate( $value, $alldata ){
2027 return true;
2028 }
2029 }
2030
2031 class HTMLEditTools extends HTMLFormField {
2032 public function getInputHTML( $value ) {
2033 return '';
2034 }
2035
2036 public function getTableRow( $value ) {
2037 if ( empty( $this->mParams['message'] ) ) {
2038 $msg = wfMessage( 'edittools' );
2039 } else {
2040 $msg = wfMessage( $this->mParams['message'] );
2041 if ( $msg->isDisabled() ) {
2042 $msg = wfMessage( 'edittools' );
2043 }
2044 }
2045 $msg->inContentLanguage();
2046
2047
2048 return '<tr><td></td><td class="mw-input">'
2049 . '<div class="mw-editTools">'
2050 . $msg->parseAsBlock()
2051 . "</div></td></tr>\n";
2052 }
2053 }