Bug 23699: Add trailing \n at the end of <div>s in wrapWikiMsg()
[lhc/web/wiklou.git] / includes / HTMLForm.php
1 <?php
2
3 /**
4 * Object handling generic submission, CSRF protection, layout and
5 * other logic for UI forms. in a reusable manner.
6 *
7 * In order to generate the form, the HTMLForm object takes an array
8 * structure detailing the form fields available. Each element of the
9 * array is a basic property-list, including the type of field, the
10 * label it is to be given in the form, callbacks for validation and
11 * 'filtering', and other pertinent information.
12 *
13 * Field types are implemented as subclasses of the generic HTMLFormField
14 * object, and typically implement at least getInputHTML, which generates
15 * the HTML for the input field to be placed in the table.
16 *
17 * The constructor input is an associative array of $fieldname => $info,
18 * where $info is an Associative Array with any of the following:
19 *
20 * 'class' -- the subclass of HTMLFormField that will be used
21 * to create the object. *NOT* the CSS class!
22 * 'type' -- roughly translates into the <select> type attribute.
23 * if 'class' is not specified, this is used as a map
24 * through HTMLForm::$typeMappings to get the class name.
25 * 'default' -- default value when the form is displayed
26 * 'id' -- HTML id attribute
27 * 'cssclass' -- CSS class
28 * 'options' -- varies according to the specific object.
29 * 'label-message' -- message key for a message to use as the label.
30 * can be an array of msg key and then parameters to
31 * the message.
32 * 'label' -- alternatively, a raw text message. Overridden by
33 * label-message
34 * 'help-message' -- message key for a message to use as a help text.
35 * can be an array of msg key and then parameters to
36 * the message.
37 * 'required' -- passed through to the object, indicating that it
38 * is a required field.
39 * 'size' -- the length of text fields
40 * 'filter-callback -- a function name to give you the chance to
41 * massage the inputted value before it's processed.
42 * @see HTMLForm::filter()
43 * 'validation-callback' -- a function name to give you the chance
44 * to impose extra validation on the field input.
45 * @see HTMLForm::validate()
46 *
47 * TODO: Document 'section' / 'subsection' stuff
48 */
49 class HTMLForm {
50 static $jsAdded = false;
51
52 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
53 static $typeMappings = array(
54 'text' => 'HTMLTextField',
55 'textarea' => 'HTMLTextAreaField',
56 'select' => 'HTMLSelectField',
57 'radio' => 'HTMLRadioField',
58 'multiselect' => 'HTMLMultiSelectField',
59 'check' => 'HTMLCheckField',
60 'toggle' => 'HTMLCheckField',
61 'int' => 'HTMLIntField',
62 'float' => 'HTMLFloatField',
63 'info' => 'HTMLInfoField',
64 'selectorother' => 'HTMLSelectOrOtherField',
65 'submit' => 'HTMLSubmitField',
66 'hidden' => 'HTMLHiddenField',
67 'edittools' => 'HTMLEditTools',
68
69 # HTMLTextField will output the correct type="" attribute automagically.
70 # There are about four zillion other HTML5 input types, like url, but
71 # we don't use those at the moment, so no point in adding all of them.
72 'email' => 'HTMLTextField',
73 'password' => 'HTMLTextField',
74 );
75
76 protected $mMessagePrefix;
77 protected $mFlatFields;
78 protected $mFieldTree;
79 protected $mShowReset = false;
80 public $mFieldData;
81
82 protected $mSubmitCallback;
83 protected $mValidationErrorMessage;
84
85 protected $mPre = '';
86 protected $mHeader = '';
87 protected $mFooter = '';
88 protected $mPost = '';
89 protected $mId;
90
91 protected $mSubmitID;
92 protected $mSubmitName;
93 protected $mSubmitText;
94 protected $mSubmitTooltip;
95 protected $mTitle;
96
97 protected $mUseMultipart = false;
98 protected $mHiddenFields = array();
99 protected $mButtons = array();
100
101 protected $mWrapperLegend = false;
102
103 /**
104 * Build a new HTMLForm from an array of field attributes
105 * @param $descriptor Array of Field constructs, as described above
106 * @param $messagePrefix String a prefix to go in front of default messages
107 */
108 public function __construct( $descriptor, $messagePrefix='' ) {
109 $this->mMessagePrefix = $messagePrefix;
110
111 // Expand out into a tree.
112 $loadedDescriptor = array();
113 $this->mFlatFields = array();
114
115 foreach( $descriptor as $fieldname => $info ) {
116 $section = isset( $info['section'] )
117 ? $info['section']
118 : '';
119
120 $info['name'] = isset( $info['name'] )
121 ? $info['name']
122 : $fieldname;
123
124 if ( isset( $info['type'] ) && $info['type'] == 'file' ){
125 $this->mUseMultipart = true;
126 }
127
128 $field = self::loadInputFromParameters( $info );
129 $field->mParent = $this;
130
131 $setSection =& $loadedDescriptor;
132 if( $section ) {
133 $sectionParts = explode( '/', $section );
134
135 while( count( $sectionParts ) ) {
136 $newName = array_shift( $sectionParts );
137
138 if ( !isset( $setSection[$newName] ) ) {
139 $setSection[$newName] = array();
140 }
141
142 $setSection =& $setSection[$newName];
143 }
144 }
145
146 $setSection[$fieldname] = $field;
147 $this->mFlatFields[$fieldname] = $field;
148 }
149
150 $this->mFieldTree = $loadedDescriptor;
151 }
152
153 /**
154 * Add the HTMLForm-specific JavaScript, if it hasn't been
155 * done already.
156 */
157 static function addJS() {
158 if( self::$jsAdded ) return;
159
160 global $wgOut, $wgStylePath;
161
162 $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
163 }
164
165 /**
166 * Initialise a new Object for the field
167 * @param $descriptor input Descriptor, as described above
168 * @return HTMLFormField subclass
169 */
170 static function loadInputFromParameters( $descriptor ) {
171 if ( isset( $descriptor['class'] ) ) {
172 $class = $descriptor['class'];
173 } elseif ( isset( $descriptor['type'] ) ) {
174 $class = self::$typeMappings[$descriptor['type']];
175 $descriptor['class'] = $class;
176 }
177
178 if( !$class ) {
179 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
180 }
181
182 $obj = new $class( $descriptor );
183
184 return $obj;
185 }
186
187 /**
188 * The here's-one-I-made-earlier option: do the submission if
189 * posted, or display the form with or without funky valiation
190 * errors
191 * @return Bool whether submission was successful.
192 */
193 function show() {
194 // Check if we have the info we need
195 if ( ! $this->mTitle ) {
196 throw new MWException( "You must call setTitle() on an HTMLForm" );
197 }
198
199 self::addJS();
200
201 # Load data from the request.
202 $this->loadData();
203
204 # Try a submission
205 global $wgUser, $wgRequest;
206 $editToken = $wgRequest->getVal( 'wpEditToken' );
207
208 $result = false;
209 if ( $wgUser->matchEditToken( $editToken ) )
210 $result = $this->trySubmit();
211
212 if( $result === true )
213 return $result;
214
215 # Display form.
216 $this->displayForm( $result );
217 return false;
218 }
219
220 /**
221 * Validate all the fields, and call the submision callback
222 * function if everything is kosher.
223 * @return Mixed Bool true == Successful submission, Bool false
224 * == No submission attempted, anything else == Error to
225 * display.
226 */
227 function trySubmit() {
228 # Check for validation
229 foreach( $this->mFlatFields as $fieldname => $field ) {
230 if ( !empty( $field->mParams['nodata'] ) ){
231 continue;
232 }
233 if ( $field->validate(
234 $this->mFieldData[$fieldname],
235 $this->mFieldData )
236 !== true )
237 {
238 return isset( $this->mValidationErrorMessage )
239 ? $this->mValidationErrorMessage
240 : array( 'htmlform-invalid-input' );
241 }
242 }
243
244 $callback = $this->mSubmitCallback;
245
246 $data = $this->filterDataForSubmit( $this->mFieldData );
247
248 $res = call_user_func( $callback, $data );
249
250 return $res;
251 }
252
253 /**
254 * Set a callback to a function to do something with the form
255 * once it's been successfully validated.
256 * @param $cb String function name. The function will be passed
257 * the output from HTMLForm::filterDataForSubmit, and must
258 * return Bool true on success, Bool false if no submission
259 * was attempted, or String HTML output to display on error.
260 */
261 function setSubmitCallback( $cb ) {
262 $this->mSubmitCallback = $cb;
263 }
264
265 /**
266 * Set a message to display on a validation error.
267 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
268 * (so each entry can be either a String or Array)
269 */
270 function setValidationErrorMessage( $msg ) {
271 $this->mValidationErrorMessage = $msg;
272 }
273
274 /**
275 * Set the introductory message, overwriting any existing message.
276 * @param $msg String complete text of message to display
277 */
278 function setIntro( $msg ) { $this->mPre = $msg; }
279
280 /**
281 * Add introductory text.
282 * @param $msg String complete text of message to display
283 */
284 function addPreText( $msg ) { $this->mPre .= $msg; }
285
286 /**
287 * Add header text, inside the form.
288 * @param $msg String complete text of message to display
289 */
290 function addHeaderText( $msg ) { $this->mHeader .= $msg; }
291
292 /**
293 * Add footer text, inside the form.
294 * @param $msg String complete text of message to display
295 */
296 function addFooterText( $msg ) { $this->mFooter .= $msg; }
297
298 /**
299 * Add text to the end of the display.
300 * @param $msg String complete text of message to display
301 */
302 function addPostText( $msg ) { $this->mPost .= $msg; }
303
304 /**
305 * Add a hidden field to the output
306 * @param $name String field name
307 * @param $value String field value
308 * @param $attribs Array
309 */
310 public function addHiddenField( $name, $value, $attribs=array() ){
311 $attribs += array( 'name' => $name );
312 $this->mHiddenFields[] = array( $value, $attribs );
313 }
314
315 public function addButton( $name, $value, $id=null, $attribs=null ){
316 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
317 }
318
319 /**
320 * Display the form (sending to wgOut), with an appropriate error
321 * message or stack of messages, and any validation errors, etc.
322 * @param $submitResult Mixed output from HTMLForm::trySubmit()
323 */
324 function displayForm( $submitResult ) {
325 global $wgOut;
326
327 $html = ''
328 . $this->getErrors( $submitResult )
329 . $this->mHeader
330 . $this->getBody()
331 . $this->getHiddenFields()
332 . $this->getButtons()
333 . $this->mFooter
334 ;
335
336 $html = $this->wrapForm( $html );
337
338 $wgOut->addHTML( ''
339 . $this->mPre
340 . $html
341 . $this->mPost
342 );
343 }
344
345 /**
346 * Wrap the form innards in an actual <form> element
347 * @param $html String HTML contents to wrap.
348 * @return String wrapped HTML.
349 */
350 function wrapForm( $html ) {
351
352 # Include a <fieldset> wrapper for style, if requested.
353 if ( $this->mWrapperLegend !== false ){
354 $html = Xml::fieldset( $this->mWrapperLegend, $html );
355 }
356 # Use multipart/form-data
357 $encType = $this->mUseMultipart
358 ? 'multipart/form-data'
359 : 'application/x-www-form-urlencoded';
360 # Attributes
361 $attribs = array(
362 'action' => $this->getTitle()->getFullURL(),
363 'method' => 'post',
364 'class' => 'visualClear',
365 'enctype' => $encType,
366 );
367 if ( !empty( $this->mId ) )
368 $attribs['id'] = $this->mId;
369
370 return Html::rawElement( 'form', $attribs, $html );
371 }
372
373 /**
374 * Get the hidden fields that should go inside the form.
375 * @return String HTML.
376 */
377 function getHiddenFields() {
378 global $wgUser;
379 $html = '';
380
381 $html .= Html::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
382 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
383
384 foreach( $this->mHiddenFields as $data ){
385 list( $value, $attribs ) = $data;
386 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
387 }
388
389 return $html;
390 }
391
392 /**
393 * Get the submit and (potentially) reset buttons.
394 * @return String HTML.
395 */
396 function getButtons() {
397 $html = '';
398
399 $attribs = array();
400
401 if ( isset( $this->mSubmitID ) )
402 $attribs['id'] = $this->mSubmitID;
403 if ( isset( $this->mSubmitName ) )
404 $attribs['name'] = $this->mSubmitName;
405 if ( isset( $this->mSubmitTooltip ) ) {
406 global $wgUser;
407 $attribs += $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip );
408 }
409
410 $attribs['class'] = 'mw-htmlform-submit';
411
412 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
413
414 if( $this->mShowReset ) {
415 $html .= Html::element(
416 'input',
417 array(
418 'type' => 'reset',
419 'value' => wfMsg( 'htmlform-reset' )
420 )
421 ) . "\n";
422 }
423
424 foreach( $this->mButtons as $button ){
425 $attrs = array(
426 'type' => 'submit',
427 'name' => $button['name'],
428 'value' => $button['value']
429 );
430 if ( $button['attribs'] )
431 $attrs += $button['attribs'];
432 if( isset( $button['id'] ) )
433 $attrs['id'] = $button['id'];
434 $html .= Html::element( 'input', $attrs );
435 }
436
437 return $html;
438 }
439
440 /**
441 * Get the whole body of the form.
442 */
443 function getBody() {
444 return $this->displaySection( $this->mFieldTree );
445 }
446
447 /**
448 * Format and display an error message stack.
449 * @param $errors Mixed String or Array of message keys
450 * @return String
451 */
452 function getErrors( $errors ) {
453 if ( is_array( $errors ) ) {
454 $errorstr = $this->formatErrors( $errors );
455 } else {
456 $errorstr = $errors;
457 }
458
459 return $errorstr
460 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
461 : '';
462 }
463
464 /**
465 * Format a stack of error messages into a single HTML string
466 * @param $errors Array of message keys/values
467 * @return String HTML, a <ul> list of errors
468 */
469 static function formatErrors( $errors ) {
470 $errorstr = '';
471 foreach ( $errors as $error ) {
472 if( is_array( $error ) ) {
473 $msg = array_shift( $error );
474 } else {
475 $msg = $error;
476 $error = array();
477 }
478 $errorstr .= Html::rawElement(
479 'li',
480 null,
481 wfMsgExt( $msg, array( 'parseinline' ), $error )
482 );
483 }
484
485 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
486
487 return $errorstr;
488 }
489
490 /**
491 * Set the text for the submit button
492 * @param $t String plaintext.
493 */
494 function setSubmitText( $t ) {
495 $this->mSubmitText = $t;
496 }
497
498 /**
499 * Get the text for the submit button, either customised or a default.
500 * @return unknown_type
501 */
502 function getSubmitText() {
503 return $this->mSubmitText
504 ? $this->mSubmitText
505 : wfMsg( 'htmlform-submit' );
506 }
507
508 public function setSubmitName( $name ) {
509 $this->mSubmitName = $name;
510 }
511
512 public function setSubmitTooltip( $name ) {
513 $this->mSubmitTooltip = $name;
514 }
515
516
517 /**
518 * Set the id for the submit button.
519 * @param $t String. FIXME: Integrity is *not* validated
520 */
521 function setSubmitID( $t ) {
522 $this->mSubmitID = $t;
523 }
524
525 public function setId( $id ) {
526 $this->mId = $id;
527 }
528 /**
529 * Prompt the whole form to be wrapped in a <fieldset>, with
530 * this text as its <legend> element.
531 * @param $legend String HTML to go inside the <legend> element.
532 * Will be escaped
533 */
534 public function setWrapperLegend( $legend ){ $this->mWrapperLegend = $legend; }
535
536 /**
537 * Set the prefix for various default messages
538 * TODO: currently only used for the <fieldset> legend on forms
539 * with multiple sections; should be used elsewhre?
540 * @param $p String
541 */
542 function setMessagePrefix( $p ) {
543 $this->mMessagePrefix = $p;
544 }
545
546 /**
547 * Set the title for form submission
548 * @param $t Title of page the form is on/should be posted to
549 */
550 function setTitle( $t ) {
551 $this->mTitle = $t;
552 }
553
554 /**
555 * Get the title
556 * @return Title
557 */
558 function getTitle() {
559 return $this->mTitle;
560 }
561
562 /**
563 * TODO: Document
564 * @param $fields
565 */
566 function displaySection( $fields, $sectionName = '' ) {
567 $tableHtml = '';
568 $subsectionHtml = '';
569 $hasLeftColumn = false;
570
571 foreach( $fields as $key => $value ) {
572 if ( is_object( $value ) ) {
573 $v = empty( $value->mParams['nodata'] )
574 ? $this->mFieldData[$key]
575 : $value->getDefault();
576 $tableHtml .= $value->getTableRow( $v );
577
578 if( $value->getLabel() != '&nbsp;' )
579 $hasLeftColumn = true;
580 } elseif ( is_array( $value ) ) {
581 $section = $this->displaySection( $value, $key );
582 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
583 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
584 }
585 }
586
587 $classes = array();
588 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
589 $classes[] = 'mw-htmlform-nolabel';
590 $attribs = array(
591 'class' => implode( ' ', $classes ),
592 );
593 if ( $sectionName )
594 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
595
596 $tableHtml = Html::rawElement( 'table', $attribs,
597 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
598
599 return $subsectionHtml . "\n" . $tableHtml;
600 }
601
602 /**
603 * Construct the form fields from the Descriptor array
604 */
605 function loadData() {
606 global $wgRequest;
607
608 $fieldData = array();
609
610 foreach( $this->mFlatFields as $fieldname => $field ) {
611 if ( !empty( $field->mParams['nodata'] ) ){
612 continue;
613 } elseif ( !empty( $field->mParams['disabled'] ) ) {
614 $fieldData[$fieldname] = $field->getDefault();
615 } else {
616 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
617 }
618 }
619
620 # Filter data.
621 foreach( $fieldData as $name => &$value ) {
622 $field = $this->mFlatFields[$name];
623 $value = $field->filter( $value, $this->mFlatFields );
624 }
625
626 $this->mFieldData = $fieldData;
627 }
628
629 /**
630 * Stop a reset button being shown for this form
631 * @param $suppressReset Bool set to false to re-enable the
632 * button again
633 */
634 function suppressReset( $suppressReset = true ) {
635 $this->mShowReset = !$suppressReset;
636 }
637
638 /**
639 * Overload this if you want to apply special filtration routines
640 * to the form as a whole, after it's submitted but before it's
641 * processed.
642 * @param $data
643 * @return unknown_type
644 */
645 function filterDataForSubmit( $data ) {
646 return $data;
647 }
648 }
649
650 /**
651 * The parent class to generate form fields. Any field type should
652 * be a subclass of this.
653 */
654 abstract class HTMLFormField {
655
656 protected $mValidationCallback;
657 protected $mFilterCallback;
658 protected $mName;
659 public $mParams;
660 protected $mLabel; # String label. Set on construction
661 protected $mID;
662 protected $mClass = '';
663 protected $mDefault;
664 public $mParent;
665
666 /**
667 * This function must be implemented to return the HTML to generate
668 * the input object itself. It should not implement the surrounding
669 * table cells/rows, or labels/help messages.
670 * @param $value String the value to set the input to; eg a default
671 * text for a text input.
672 * @return String valid HTML.
673 */
674 abstract function getInputHTML( $value );
675
676 /**
677 * Override this function to add specific validation checks on the
678 * field input. Don't forget to call parent::validate() to ensure
679 * that the user-defined callback mValidationCallback is still run
680 * @param $value String the value the field was submitted with
681 * @param $alldata Array the data collected from the form
682 * @return Mixed Bool true on success, or String error to display.
683 */
684 function validate( $value, $alldata ) {
685 if ( isset( $this->mValidationCallback ) ) {
686 return call_user_func( $this->mValidationCallback, $value, $alldata );
687 }
688
689 return true;
690 }
691
692 function filter( $value, $alldata ) {
693 if( isset( $this->mFilterCallback ) ) {
694 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
695 }
696
697 return $value;
698 }
699
700 /**
701 * Should this field have a label, or is there no input element with the
702 * appropriate id for the label to point to?
703 *
704 * @return bool True to output a label, false to suppress
705 */
706 protected function needsLabel() {
707 return true;
708 }
709
710 /**
711 * Get the value that this input has been set to from a posted form,
712 * or the input's default value if it has not been set.
713 * @param $request WebRequest
714 * @return String the value
715 */
716 function loadDataFromRequest( $request ) {
717 if( $request->getCheck( $this->mName ) ) {
718 return $request->getText( $this->mName );
719 } else {
720 return $this->getDefault();
721 }
722 }
723
724 /**
725 * Initialise the object
726 * @param $params Associative Array. See HTMLForm doc for syntax.
727 */
728 function __construct( $params ) {
729 $this->mParams = $params;
730
731 # Generate the label from a message, if possible
732 if( isset( $params['label-message'] ) ) {
733 $msgInfo = $params['label-message'];
734
735 if ( is_array( $msgInfo ) ) {
736 $msg = array_shift( $msgInfo );
737 } else {
738 $msg = $msgInfo;
739 $msgInfo = array();
740 }
741
742 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
743 } elseif ( isset( $params['label'] ) ) {
744 $this->mLabel = $params['label'];
745 }
746
747 if ( isset( $params['name'] ) ) {
748 $name = $params['name'];
749 $validName = Sanitizer::escapeId( $name );
750 if( $name != $validName ) {
751 throw new MWException("Invalid name '$name' passed to " . __METHOD__ );
752 }
753 $this->mName = 'wp'.$name;
754 $this->mID = 'mw-input-'.$name;
755 }
756
757 if ( isset( $params['default'] ) ) {
758 $this->mDefault = $params['default'];
759 }
760
761 if ( isset( $params['id'] ) ) {
762 $id = $params['id'];
763 $validId = Sanitizer::escapeId( $id );
764 if( $id != $validId ) {
765 throw new MWException("Invalid id '$id' passed to " . __METHOD__ );
766 }
767 $this->mID = $id;
768 }
769
770 if ( isset( $params['cssclass'] ) ) {
771 $this->mClass = $params['cssclass'];
772 }
773
774 if ( isset( $params['validation-callback'] ) ) {
775 $this->mValidationCallback = $params['validation-callback'];
776 }
777
778 if ( isset( $params['filter-callback'] ) ) {
779 $this->mFilterCallback = $params['filter-callback'];
780 }
781 }
782
783 /**
784 * Get the complete table row for the input, including help text,
785 * labels, and whatever.
786 * @param $value String the value to set the input to.
787 * @return String complete HTML table row.
788 */
789 function getTableRow( $value ) {
790 # Check for invalid data.
791 global $wgRequest;
792
793 $errors = $this->validate( $value, $this->mParent->mFieldData );
794 if ( $errors === true || !$wgRequest->wasPosted() ) {
795 $errors = '';
796 } else {
797 $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
798 }
799
800 $html = $this->getLabelHtml();
801 $html .= Html::rawElement(
802 'td',
803 array( 'class' => 'mw-input' ),
804 $this->getInputHTML( $value ) ."\n$errors"
805 );
806
807 $fieldType = get_class( $this );
808
809 $html = Html::rawElement(
810 'tr',
811 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
812 $html
813 ) . "\n";
814
815 $helptext = null;
816 if ( isset( $this->mParams['help-message'] ) ) {
817 $msg = $this->mParams['help-message'];
818 $helptext = wfMsgExt( $msg, 'parseinline' );
819 if ( wfEmptyMsg( $msg, $helptext ) ) {
820 # Never mind
821 $helptext = null;
822 }
823 } elseif ( isset( $this->mParams['help'] ) ) {
824 $helptext = $this->mParams['help'];
825 }
826
827 if ( !is_null( $helptext ) ) {
828 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
829 $helptext );
830 $row = Html::rawElement( 'tr', array(), $row );
831 $html .= "$row\n";
832 }
833
834 return $html;
835 }
836
837 function getLabel() {
838 return $this->mLabel;
839 }
840 function getLabelHtml() {
841 # Don't output a for= attribute for labels with no associated input.
842 # Kind of hacky here, possibly we don't want these to be <label>s at all.
843 $for = array();
844 if ( $this->needsLabel() ) {
845 $for['for'] = $this->mID;
846 }
847 return Html::rawElement( 'td', array( 'class' => 'mw-label' ),
848 Html::rawElement( 'label', $for, $this->getLabel() )
849 );
850 }
851
852 function getDefault() {
853 if ( isset( $this->mDefault ) ) {
854 return $this->mDefault;
855 } else {
856 return null;
857 }
858 }
859
860 /**
861 * Returns the attributes required for the tooltip and accesskey.
862 *
863 * @return array Attributes
864 */
865 public function getTooltipAndAccessKey() {
866 if ( empty( $this->mParams['tooltip'] ) )
867 return array();
868
869 global $wgUser;
870 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
871 }
872
873 /**
874 * flatten an array of options to a single array, for instance,
875 * a set of <options> inside <optgroups>.
876 * @param $options Associative Array with values either Strings
877 * or Arrays
878 * @return Array flattened input
879 */
880 public static function flattenOptions( $options ) {
881 $flatOpts = array();
882
883 foreach( $options as $key => $value ) {
884 if ( is_array( $value ) ) {
885 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
886 } else {
887 $flatOpts[] = $value;
888 }
889 }
890
891 return $flatOpts;
892 }
893
894 }
895
896 class HTMLTextField extends HTMLFormField {
897
898 function getSize() {
899 return isset( $this->mParams['size'] )
900 ? $this->mParams['size']
901 : 45;
902 }
903
904 function getInputHTML( $value ) {
905 $attribs = array(
906 'id' => $this->mID,
907 'name' => $this->mName,
908 'size' => $this->getSize(),
909 'value' => $value,
910 ) + $this->getTooltipAndAccessKey();
911
912 if ( isset( $this->mParams['maxlength'] ) ) {
913 $attribs['maxlength'] = $this->mParams['maxlength'];
914 }
915
916 if ( !empty( $this->mParams['disabled'] ) ) {
917 $attribs['disabled'] = 'disabled';
918 }
919
920 # TODO: Enforce pattern, step, required, readonly on the server side as
921 # well
922 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
923 'placeholder' ) as $param ) {
924 if ( isset( $this->mParams[$param] ) ) {
925 $attribs[$param] = $this->mParams[$param];
926 }
927 }
928 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as
929 $param ) {
930 if ( isset( $this->mParams[$param] ) ) {
931 $attribs[$param] = '';
932 }
933 }
934
935 # Implement tiny differences between some field variants
936 # here, rather than creating a new class for each one which
937 # is essentially just a clone of this one.
938 if ( isset( $this->mParams['type'] ) ) {
939 switch ( $this->mParams['type'] ) {
940 case 'email':
941 $attribs['type'] = 'email';
942 break;
943 case 'int':
944 $attribs['type'] = 'number';
945 break;
946 case 'float':
947 $attribs['type'] = 'number';
948 $attribs['step'] = 'any';
949 break;
950 # Pass through
951 case 'password':
952 case 'file':
953 $attribs['type'] = $this->mParams['type'];
954 break;
955 }
956 }
957
958 return Html::element( 'input', $attribs );
959 }
960
961 public function validate( $value, $alldata ){
962 $p = parent::validate( $value, $alldata );
963 if( $p !== true ) return $p;
964
965 if( isset( $this->mParams['required'] ) && $value === '' ){
966 return wfMsgExt( 'htmlform-required', 'parseinline' );
967 }
968 return true;
969 }
970 }
971 class HTMLTextAreaField extends HTMLFormField {
972
973 function getCols() {
974 return isset( $this->mParams['cols'] )
975 ? $this->mParams['cols']
976 : 80;
977 }
978 function getRows() {
979 return isset( $this->mParams['rows'] )
980 ? $this->mParams['rows']
981 : 25;
982 }
983
984 function getInputHTML( $value ) {
985 $attribs = array(
986 'id' => $this->mID,
987 'name' => $this->mName,
988 'cols' => $this->getCols(),
989 'rows' => $this->getRows(),
990 ) + $this->getTooltipAndAccessKey();
991
992
993 if ( !empty( $this->mParams['disabled'] ) ) {
994 $attribs['disabled'] = 'disabled';
995 }
996 if ( !empty( $this->mParams['readonly'] ) ) {
997 $attribs['readonly'] = 'readonly';
998 }
999
1000 foreach ( array( 'required', 'autofocus' ) as $param ) {
1001 if ( isset( $this->mParams[$param] ) ) {
1002 $attribs[$param] = '';
1003 }
1004 }
1005
1006 return Html::element( 'textarea', $attribs, $value );
1007 }
1008
1009 public function validate( $value, $alldata ){
1010 $p = parent::validate( $value, $alldata );
1011 if( $p !== true ) return $p;
1012
1013 if( isset( $this->mParams['required'] ) && $value === '' ){
1014 return wfMsgExt( 'htmlform-required', 'parseinline' );
1015 }
1016 return true;
1017 }
1018 }
1019
1020 /**
1021 * A field that will contain a numeric value
1022 */
1023 class HTMLFloatField extends HTMLTextField {
1024
1025 function getSize() {
1026 return isset( $this->mParams['size'] )
1027 ? $this->mParams['size']
1028 : 20;
1029 }
1030
1031 function validate( $value, $alldata ) {
1032 $p = parent::validate( $value, $alldata );
1033
1034 if ( $p !== true ) return $p;
1035
1036 if ( floatval( $value ) != $value ) {
1037 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1038 }
1039
1040 $in_range = true;
1041
1042 # The "int" part of these message names is rather confusing.
1043 # They make equal sense for all numbers.
1044 if ( isset( $this->mParams['min'] ) ) {
1045 $min = $this->mParams['min'];
1046 if ( $min > $value )
1047 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1048 }
1049
1050 if ( isset( $this->mParams['max'] ) ) {
1051 $max = $this->mParams['max'];
1052 if( $max < $value )
1053 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1054 }
1055
1056 return true;
1057 }
1058 }
1059
1060 /**
1061 * A field that must contain a number
1062 */
1063 class HTMLIntField extends HTMLFloatField {
1064 function validate( $value, $alldata ) {
1065 $p = parent::validate( $value, $alldata );
1066
1067 if ( $p !== true ) return $p;
1068
1069 if ( $value !== ''
1070 && ( !is_numeric( $value ) || round( $value ) != $value ) )
1071 {
1072 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1073 }
1074
1075 return true;
1076 }
1077 }
1078
1079 /**
1080 * A checkbox field
1081 */
1082 class HTMLCheckField extends HTMLFormField {
1083 function getInputHTML( $value ) {
1084 if ( !empty( $this->mParams['invert'] ) )
1085 $value = !$value;
1086
1087 $attr = $this->getTooltipAndAccessKey();
1088 $attr['id'] = $this->mID;
1089 if( !empty( $this->mParams['disabled'] ) ) {
1090 $attr['disabled'] = 'disabled';
1091 }
1092
1093 return Xml::check( $this->mName, $value, $attr ) . '&nbsp;' .
1094 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1095 }
1096
1097 /**
1098 * For a checkbox, the label goes on the right hand side, and is
1099 * added in getInputHTML(), rather than HTMLFormField::getRow()
1100 */
1101 function getLabel() {
1102 return '&nbsp;';
1103 }
1104
1105 function loadDataFromRequest( $request ) {
1106 $invert = false;
1107 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1108 $invert = true;
1109 }
1110
1111 // GetCheck won't work like we want for checks.
1112 if( $request->getCheck( 'wpEditToken' ) ) {
1113 // XOR has the following truth table, which is what we want
1114 // INVERT VALUE | OUTPUT
1115 // true true | false
1116 // false true | true
1117 // false false | false
1118 // true false | true
1119 return $request->getBool( $this->mName ) xor $invert;
1120 } else {
1121 return $this->getDefault();
1122 }
1123 }
1124 }
1125
1126 /**
1127 * A select dropdown field. Basically a wrapper for Xmlselect class
1128 */
1129 class HTMLSelectField extends HTMLFormField {
1130
1131 function validate( $value, $alldata ) {
1132 $p = parent::validate( $value, $alldata );
1133 if( $p !== true ) return $p;
1134
1135 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1136 if ( in_array( $value, $validOptions ) )
1137 return true;
1138 else
1139 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1140 }
1141
1142 function getInputHTML( $value ) {
1143 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1144
1145 # If one of the options' 'name' is int(0), it is automatically selected.
1146 # because PHP sucks and things int(0) == 'some string'.
1147 # Working around this by forcing all of them to strings.
1148 $options = array_map( 'strval', $this->mParams['options'] );
1149
1150 if( !empty( $this->mParams['disabled'] ) ) {
1151 $select->setAttribute( 'disabled', 'disabled' );
1152 }
1153
1154 $select->addOptions( $options );
1155
1156 return $select->getHTML();
1157 }
1158 }
1159
1160 /**
1161 * Select dropdown field, with an additional "other" textbox.
1162 */
1163 class HTMLSelectOrOtherField extends HTMLTextField {
1164 static $jsAdded = false;
1165
1166 function __construct( $params ) {
1167 if( !in_array( 'other', $params['options'], true ) ) {
1168 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1169 }
1170
1171 parent::__construct( $params );
1172 }
1173
1174 static function forceToStringRecursive( $array ) {
1175 if ( is_array($array) ) {
1176 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array);
1177 } else {
1178 return strval($array);
1179 }
1180 }
1181
1182 function getInputHTML( $value ) {
1183 $valInSelect = false;
1184
1185 if( $value !== false )
1186 $valInSelect = in_array( $value,
1187 HTMLFormField::flattenOptions( $this->mParams['options'] ) );
1188
1189 $selected = $valInSelect ? $value : 'other';
1190
1191 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1192
1193 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1194 $select->addOptions( $opts );
1195
1196 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1197
1198 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1199 if( !empty( $this->mParams['disabled'] ) ) {
1200 $select->setAttribute( 'disabled', 'disabled' );
1201 $tbAttribs['disabled'] = 'disabled';
1202 }
1203
1204 $select = $select->getHTML();
1205
1206 if ( isset( $this->mParams['maxlength'] ) ) {
1207 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1208 }
1209
1210 $textbox = Html::input( $this->mName . '-other',
1211 $valInSelect ? '' : $value,
1212 'text',
1213 $tbAttribs );
1214
1215 return "$select<br />\n$textbox";
1216 }
1217
1218 function loadDataFromRequest( $request ) {
1219 if( $request->getCheck( $this->mName ) ) {
1220 $val = $request->getText( $this->mName );
1221
1222 if( $val == 'other' ) {
1223 $val = $request->getText( $this->mName . '-other' );
1224 }
1225
1226 return $val;
1227 } else {
1228 return $this->getDefault();
1229 }
1230 }
1231 }
1232
1233 /**
1234 * Multi-select field
1235 */
1236 class HTMLMultiSelectField extends HTMLFormField {
1237
1238 function validate( $value, $alldata ) {
1239 $p = parent::validate( $value, $alldata );
1240 if( $p !== true ) return $p;
1241
1242 if( !is_array( $value ) ) return false;
1243
1244 # If all options are valid, array_intersect of the valid options
1245 # and the provided options will return the provided options.
1246 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1247
1248 $validValues = array_intersect( $value, $validOptions );
1249 if ( count( $validValues ) == count( $value ) )
1250 return true;
1251 else
1252 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1253 }
1254
1255 function getInputHTML( $value ) {
1256 $html = $this->formatOptions( $this->mParams['options'], $value );
1257
1258 return $html;
1259 }
1260
1261 function formatOptions( $options, $value ) {
1262 $html = '';
1263
1264 $attribs = array();
1265 if ( !empty( $this->mParams['disabled'] ) ) {
1266 $attribs['disabled'] = 'disabled';
1267 }
1268
1269 foreach( $options as $label => $info ) {
1270 if( is_array( $info ) ) {
1271 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1272 $html .= $this->formatOptions( $info, $value );
1273 } else {
1274 $thisAttribs = array( 'id' => $this->mID . "-$info", 'value' => $info );
1275
1276 $checkbox = Xml::check( $this->mName . '[]', in_array( $info, $value, true ),
1277 $attribs + $thisAttribs );
1278 $checkbox .= '&nbsp;' . Html::rawElement( 'label', array( 'for' => $this->mID . "-$info" ), $label );
1279
1280 $html .= $checkbox . '<br />';
1281 }
1282 }
1283
1284 return $html;
1285 }
1286
1287 function loadDataFromRequest( $request ) {
1288 # won't work with getCheck
1289 if( $request->getCheck( 'wpEditToken' ) ) {
1290 $arr = $request->getArray( $this->mName );
1291
1292 if( !$arr )
1293 $arr = array();
1294
1295 return $arr;
1296 } else {
1297 return $this->getDefault();
1298 }
1299 }
1300
1301 function getDefault() {
1302 if ( isset( $this->mDefault ) ) {
1303 return $this->mDefault;
1304 } else {
1305 return array();
1306 }
1307 }
1308
1309 protected function needsLabel() {
1310 return false;
1311 }
1312 }
1313
1314 /**
1315 * Radio checkbox fields.
1316 */
1317 class HTMLRadioField extends HTMLFormField {
1318 function validate( $value, $alldata ) {
1319 $p = parent::validate( $value, $alldata );
1320 if( $p !== true ) return $p;
1321
1322 if( !is_string( $value ) && !is_int( $value ) )
1323 return false;
1324
1325 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1326
1327 if ( in_array( $value, $validOptions ) )
1328 return true;
1329 else
1330 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1331 }
1332
1333 /**
1334 * This returns a block of all the radio options, in one cell.
1335 * @see includes/HTMLFormField#getInputHTML()
1336 */
1337 function getInputHTML( $value ) {
1338 $html = $this->formatOptions( $this->mParams['options'], $value );
1339
1340 return $html;
1341 }
1342
1343 function formatOptions( $options, $value ) {
1344 $html = '';
1345
1346 $attribs = array();
1347 if ( !empty( $this->mParams['disabled'] ) ) {
1348 $attribs['disabled'] = 'disabled';
1349 }
1350
1351 # TODO: should this produce an unordered list perhaps?
1352 foreach( $options as $label => $info ) {
1353 if( is_array( $info ) ) {
1354 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1355 $html .= $this->formatOptions( $info, $value );
1356 } else {
1357 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1358 $html .= Xml::radio( $this->mName, $info, $info == $value,
1359 $attribs + array( 'id' => $id ) );
1360 $html .= '&nbsp;' .
1361 Html::rawElement( 'label', array( 'for' => $id ), $label );
1362
1363 $html .= "<br />\n";
1364 }
1365 }
1366
1367 return $html;
1368 }
1369
1370 protected function needsLabel() {
1371 return false;
1372 }
1373 }
1374
1375 /**
1376 * An information field (text blob), not a proper input.
1377 */
1378 class HTMLInfoField extends HTMLFormField {
1379 function __construct( $info ) {
1380 $info['nodata'] = true;
1381
1382 parent::__construct( $info );
1383 }
1384
1385 function getInputHTML( $value ) {
1386 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1387 }
1388
1389 function getTableRow( $value ) {
1390 if ( !empty( $this->mParams['rawrow'] ) ) {
1391 return $value;
1392 }
1393
1394 return parent::getTableRow( $value );
1395 }
1396
1397 protected function needsLabel() {
1398 return false;
1399 }
1400 }
1401
1402 class HTMLHiddenField extends HTMLFormField {
1403
1404 public function __construct( $params ){
1405 parent::__construct( $params );
1406 # forcing the 'wp' prefix on hidden field names
1407 # is undesirable
1408 $this->mName = substr( $this->mName, 2 );
1409 }
1410
1411 public function getTableRow( $value ){
1412 $params = array();
1413 if( $this->mID ){
1414 $params['id'] = $this->mID;
1415 }
1416 $this->mParent->addHiddenField(
1417 $this->mName,
1418 $this->mDefault,
1419 $params
1420 );
1421 return '';
1422 }
1423
1424 public function getInputHTML( $value ){ return ''; }
1425 }
1426
1427 /**
1428 * Add a submit button inline in the form (as opposed to
1429 * HTMLForm::addButton(), which will add it at the end).
1430 */
1431 class HTMLSubmitField extends HTMLFormField {
1432
1433 function __construct( $info ) {
1434 $info['nodata'] = true;
1435 parent::__construct( $info );
1436 }
1437
1438 function getInputHTML( $value ) {
1439 return Xml::submitButton(
1440 $value,
1441 array(
1442 'class' => 'mw-htmlform-submit',
1443 'name' => $this->mName,
1444 'id' => $this->mID,
1445 )
1446 );
1447 }
1448
1449 protected function needsLabel() {
1450 return false;
1451 }
1452 }
1453
1454 class HTMLEditTools extends HTMLFormField {
1455 public function getInputHTML( $value ) {
1456 return '';
1457 }
1458 public function getTableRow( $value ) {
1459 return "<tr><td></td><td class=\"mw-input\">"
1460 . '<div class="mw-editTools">'
1461 . wfMsgExt( empty( $this->mParams['message'] )
1462 ? 'edittools' : $this->mParams['message'],
1463 array( 'parse', 'content' ) )
1464 . "</div></td></tr>\n";
1465 }
1466 }