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