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