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