* (bug 24563) Entries on Special:WhatLinksHere now have a link to their history
[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() != '&#160;' )
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 $cellAttributes = array();
817 $verticalLabel = false;
818
819 if ( !empty($this->mParams['vertical-label']) ) {
820 $cellAttributes['colspan'] = 2;
821 $verticalLabel = true;
822 }
823
824 if ( $errors === true || !$wgRequest->wasPosted() ) {
825 $errors = '';
826 } else {
827 $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
828 }
829
830 $label = $this->getLabelHtml( $cellAttributes );
831 $field = Html::rawElement(
832 'td',
833 array( 'class' => 'mw-input' ) + $cellAttributes,
834 $this->getInputHTML( $value ) . "\n$errors"
835 );
836
837 $fieldType = get_class( $this );
838
839 if ($verticalLabel) {
840 $html = Html::rawElement( 'tr',
841 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
842 $html .= Html::rawElement( 'tr',
843 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
844 $field );
845 } else {
846 $html = Html::rawElement( 'tr',
847 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
848 $label . $field );
849 }
850
851 $helptext = null;
852
853 if ( isset( $this->mParams['help-message'] ) ) {
854 $msg = $this->mParams['help-message'];
855 $helptext = wfMsgExt( $msg, 'parseinline' );
856 if ( wfEmptyMsg( $msg, $helptext ) ) {
857 # Never mind
858 $helptext = null;
859 }
860 } elseif ( isset( $this->mParams['help'] ) ) {
861 $helptext = $this->mParams['help'];
862 }
863
864 if ( !is_null( $helptext ) ) {
865 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
866 $helptext );
867 $row = Html::rawElement( 'tr', array(), $row );
868 $html .= "$row\n";
869 }
870
871 return $html;
872 }
873
874 function getLabel() {
875 return $this->mLabel;
876 }
877 function getLabelHtml( $cellAttributes = array() ) {
878 # Don't output a for= attribute for labels with no associated input.
879 # Kind of hacky here, possibly we don't want these to be <label>s at all.
880 $for = array();
881
882 if ( $this->needsLabel() ) {
883 $for['for'] = $this->mID;
884 }
885
886 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
887 Html::rawElement( 'label', $for, $this->getLabel() )
888 );
889 }
890
891 function getDefault() {
892 if ( isset( $this->mDefault ) ) {
893 return $this->mDefault;
894 } else {
895 return null;
896 }
897 }
898
899 /**
900 * Returns the attributes required for the tooltip and accesskey.
901 *
902 * @return array Attributes
903 */
904 public function getTooltipAndAccessKey() {
905 if ( empty( $this->mParams['tooltip'] ) ) {
906 return array();
907 }
908
909 global $wgUser;
910
911 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs();
912 }
913
914 /**
915 * flatten an array of options to a single array, for instance,
916 * a set of <options> inside <optgroups>.
917 * @param $options Associative Array with values either Strings
918 * or Arrays
919 * @return Array flattened input
920 */
921 public static function flattenOptions( $options ) {
922 $flatOpts = array();
923
924 foreach ( $options as $key => $value ) {
925 if ( is_array( $value ) ) {
926 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
927 } else {
928 $flatOpts[] = $value;
929 }
930 }
931
932 return $flatOpts;
933 }
934 }
935
936 class HTMLTextField extends HTMLFormField {
937 function getSize() {
938 return isset( $this->mParams['size'] )
939 ? $this->mParams['size']
940 : 45;
941 }
942
943 function getInputHTML( $value ) {
944 $attribs = array(
945 'id' => $this->mID,
946 'name' => $this->mName,
947 'size' => $this->getSize(),
948 'value' => $value,
949 ) + $this->getTooltipAndAccessKey();
950
951 if ( isset( $this->mParams['maxlength'] ) ) {
952 $attribs['maxlength'] = $this->mParams['maxlength'];
953 }
954
955 if ( !empty( $this->mParams['disabled'] ) ) {
956 $attribs['disabled'] = 'disabled';
957 }
958
959 # TODO: Enforce pattern, step, required, readonly on the server side as
960 # well
961 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
962 'placeholder' ) as $param ) {
963 if ( isset( $this->mParams[$param] ) ) {
964 $attribs[$param] = $this->mParams[$param];
965 }
966 }
967
968 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
969 if ( isset( $this->mParams[$param] ) ) {
970 $attribs[$param] = '';
971 }
972 }
973
974 # Implement tiny differences between some field variants
975 # here, rather than creating a new class for each one which
976 # is essentially just a clone of this one.
977 if ( isset( $this->mParams['type'] ) ) {
978 switch ( $this->mParams['type'] ) {
979 case 'email':
980 $attribs['type'] = 'email';
981 break;
982 case 'int':
983 $attribs['type'] = 'number';
984 break;
985 case 'float':
986 $attribs['type'] = 'number';
987 $attribs['step'] = 'any';
988 break;
989 # Pass through
990 case 'password':
991 case 'file':
992 $attribs['type'] = $this->mParams['type'];
993 break;
994 }
995 }
996
997 return Html::element( 'input', $attribs );
998 }
999
1000 public function validate( $value, $alldata ) {
1001 $p = parent::validate( $value, $alldata );
1002
1003 if ( $p !== true ) {
1004 return $p;
1005 }
1006
1007 if ( isset( $this->mParams['required'] ) && $value === '' ) {
1008 return wfMsgExt( 'htmlform-required', 'parseinline' );
1009 }
1010
1011 return true;
1012 }
1013 }
1014 class HTMLTextAreaField extends HTMLFormField {
1015 function getCols() {
1016 return isset( $this->mParams['cols'] )
1017 ? $this->mParams['cols']
1018 : 80;
1019 }
1020
1021 function getRows() {
1022 return isset( $this->mParams['rows'] )
1023 ? $this->mParams['rows']
1024 : 25;
1025 }
1026
1027 function getInputHTML( $value ) {
1028 $attribs = array(
1029 'id' => $this->mID,
1030 'name' => $this->mName,
1031 'cols' => $this->getCols(),
1032 'rows' => $this->getRows(),
1033 ) + $this->getTooltipAndAccessKey();
1034
1035
1036 if ( !empty( $this->mParams['disabled'] ) ) {
1037 $attribs['disabled'] = 'disabled';
1038 }
1039
1040 if ( !empty( $this->mParams['readonly'] ) ) {
1041 $attribs['readonly'] = 'readonly';
1042 }
1043
1044 foreach ( array( 'required', 'autofocus' ) as $param ) {
1045 if ( isset( $this->mParams[$param] ) ) {
1046 $attribs[$param] = '';
1047 }
1048 }
1049
1050 return Html::element( 'textarea', $attribs, $value );
1051 }
1052
1053 public function validate( $value, $alldata ) {
1054 $p = parent::validate( $value, $alldata );
1055
1056 if ( $p !== true ) {
1057 return $p;
1058 }
1059
1060 if ( isset( $this->mParams['required'] ) && $value === '' ) {
1061 return wfMsgExt( 'htmlform-required', 'parseinline' );
1062 }
1063
1064 return true;
1065 }
1066 }
1067
1068 /**
1069 * A field that will contain a numeric value
1070 */
1071 class HTMLFloatField extends HTMLTextField {
1072 function getSize() {
1073 return isset( $this->mParams['size'] )
1074 ? $this->mParams['size']
1075 : 20;
1076 }
1077
1078 function validate( $value, $alldata ) {
1079 $p = parent::validate( $value, $alldata );
1080
1081 if ( $p !== true ) {
1082 return $p;
1083 }
1084
1085 if ( floatval( $value ) != $value ) {
1086 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1087 }
1088
1089 $in_range = true;
1090
1091 # The "int" part of these message names is rather confusing.
1092 # They make equal sense for all numbers.
1093 if ( isset( $this->mParams['min'] ) ) {
1094 $min = $this->mParams['min'];
1095
1096 if ( $min > $value ) {
1097 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1098 }
1099 }
1100
1101 if ( isset( $this->mParams['max'] ) ) {
1102 $max = $this->mParams['max'];
1103
1104 if ( $max < $value ) {
1105 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1106 }
1107 }
1108
1109 return true;
1110 }
1111 }
1112
1113 /**
1114 * A field that must contain a number
1115 */
1116 class HTMLIntField extends HTMLFloatField {
1117 function validate( $value, $alldata ) {
1118 $p = parent::validate( $value, $alldata );
1119
1120 if ( $p !== true ) {
1121 return $p;
1122 }
1123
1124 if ( $value !== ''
1125 && ( !is_numeric( $value ) || round( $value ) != $value )
1126 ) {
1127 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1128 }
1129
1130 return true;
1131 }
1132 }
1133
1134 /**
1135 * A checkbox field
1136 */
1137 class HTMLCheckField extends HTMLFormField {
1138 function getInputHTML( $value ) {
1139 if ( !empty( $this->mParams['invert'] ) ) {
1140 $value = !$value;
1141 }
1142
1143 $attr = $this->getTooltipAndAccessKey();
1144 $attr['id'] = $this->mID;
1145
1146 if ( !empty( $this->mParams['disabled'] ) ) {
1147 $attr['disabled'] = 'disabled';
1148 }
1149
1150 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1151 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1152 }
1153
1154 /**
1155 * For a checkbox, the label goes on the right hand side, and is
1156 * added in getInputHTML(), rather than HTMLFormField::getRow()
1157 */
1158 function getLabel() {
1159 return '&#160;';
1160 }
1161
1162 function loadDataFromRequest( $request ) {
1163 $invert = false;
1164 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1165 $invert = true;
1166 }
1167
1168 // GetCheck won't work like we want for checks.
1169 if ( $request->getCheck( 'wpEditToken' ) ) {
1170 // XOR has the following truth table, which is what we want
1171 // INVERT VALUE | OUTPUT
1172 // true true | false
1173 // false true | true
1174 // false false | false
1175 // true false | true
1176 return $request->getBool( $this->mName ) xor $invert;
1177 } else {
1178 return $this->getDefault();
1179 }
1180 }
1181 }
1182
1183 /**
1184 * A select dropdown field. Basically a wrapper for Xmlselect class
1185 */
1186 class HTMLSelectField extends HTMLFormField {
1187 function validate( $value, $alldata ) {
1188 $p = parent::validate( $value, $alldata );
1189
1190 if ( $p !== true ) {
1191 return $p;
1192 }
1193
1194 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1195
1196 if ( in_array( $value, $validOptions ) )
1197 return true;
1198 else
1199 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1200 }
1201
1202 function getInputHTML( $value ) {
1203 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1204
1205 # If one of the options' 'name' is int(0), it is automatically selected.
1206 # because PHP sucks and things int(0) == 'some string'.
1207 # Working around this by forcing all of them to strings.
1208 $options = array_map( 'strval', $this->mParams['options'] );
1209
1210 if ( !empty( $this->mParams['disabled'] ) ) {
1211 $select->setAttribute( 'disabled', 'disabled' );
1212 }
1213
1214 $select->addOptions( $options );
1215
1216 return $select->getHTML();
1217 }
1218 }
1219
1220 /**
1221 * Select dropdown field, with an additional "other" textbox.
1222 */
1223 class HTMLSelectOrOtherField extends HTMLTextField {
1224 static $jsAdded = false;
1225
1226 function __construct( $params ) {
1227 if ( !in_array( 'other', $params['options'], true ) ) {
1228 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1229 }
1230
1231 parent::__construct( $params );
1232 }
1233
1234 static function forceToStringRecursive( $array ) {
1235 if ( is_array( $array ) ) {
1236 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1237 } else {
1238 return strval( $array );
1239 }
1240 }
1241
1242 function getInputHTML( $value ) {
1243 $valInSelect = false;
1244
1245 if ( $value !== false ) {
1246 $valInSelect = in_array(
1247 $value,
1248 HTMLFormField::flattenOptions( $this->mParams['options'] )
1249 );
1250 }
1251
1252 $selected = $valInSelect ? $value : 'other';
1253
1254 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1255
1256 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1257 $select->addOptions( $opts );
1258
1259 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1260
1261 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1262
1263 if ( !empty( $this->mParams['disabled'] ) ) {
1264 $select->setAttribute( 'disabled', 'disabled' );
1265 $tbAttribs['disabled'] = 'disabled';
1266 }
1267
1268 $select = $select->getHTML();
1269
1270 if ( isset( $this->mParams['maxlength'] ) ) {
1271 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1272 }
1273
1274 $textbox = Html::input(
1275 $this->mName . '-other',
1276 $valInSelect ? '' : $value,
1277 'text',
1278 $tbAttribs
1279 );
1280
1281 return "$select<br />\n$textbox";
1282 }
1283
1284 function loadDataFromRequest( $request ) {
1285 if ( $request->getCheck( $this->mName ) ) {
1286 $val = $request->getText( $this->mName );
1287
1288 if ( $val == 'other' ) {
1289 $val = $request->getText( $this->mName . '-other' );
1290 }
1291
1292 return $val;
1293 } else {
1294 return $this->getDefault();
1295 }
1296 }
1297 }
1298
1299 /**
1300 * Multi-select field
1301 */
1302 class HTMLMultiSelectField extends HTMLFormField {
1303 function validate( $value, $alldata ) {
1304 $p = parent::validate( $value, $alldata );
1305
1306 if ( $p !== true ) {
1307 return $p;
1308 }
1309
1310 if ( !is_array( $value ) ) {
1311 return false;
1312 }
1313
1314 # If all options are valid, array_intersect of the valid options
1315 # and the provided options will return the provided options.
1316 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1317
1318 $validValues = array_intersect( $value, $validOptions );
1319 if ( count( $validValues ) == count( $value ) ) {
1320 return true;
1321 } else {
1322 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1323 }
1324 }
1325
1326 function getInputHTML( $value ) {
1327 $html = $this->formatOptions( $this->mParams['options'], $value );
1328
1329 return $html;
1330 }
1331
1332 function formatOptions( $options, $value ) {
1333 $html = '';
1334
1335 $attribs = array();
1336
1337 if ( !empty( $this->mParams['disabled'] ) ) {
1338 $attribs['disabled'] = 'disabled';
1339 }
1340
1341 foreach ( $options as $label => $info ) {
1342 if ( is_array( $info ) ) {
1343 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1344 $html .= $this->formatOptions( $info, $value );
1345 } else {
1346 $thisAttribs = array( 'id' => $this->mID . "-$info", 'value' => $info );
1347
1348 $checkbox = Xml::check( $this->mName . '[]', in_array( $info, $value, true ),
1349 $attribs + $thisAttribs );
1350 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => $this->mID . "-$info" ), $label );
1351
1352 $html .= $checkbox . '<br />';
1353 }
1354 }
1355
1356 return $html;
1357 }
1358
1359 function loadDataFromRequest( $request ) {
1360 # won't work with getCheck
1361 if ( $request->getCheck( 'wpEditToken' ) ) {
1362 $arr = $request->getArray( $this->mName );
1363
1364 if ( !$arr ) {
1365 $arr = array();
1366 }
1367
1368 return $arr;
1369 } else {
1370 return $this->getDefault();
1371 }
1372 }
1373
1374 function getDefault() {
1375 if ( isset( $this->mDefault ) ) {
1376 return $this->mDefault;
1377 } else {
1378 return array();
1379 }
1380 }
1381
1382 protected function needsLabel() {
1383 return false;
1384 }
1385 }
1386
1387 /**
1388 * Radio checkbox fields.
1389 */
1390 class HTMLRadioField extends HTMLFormField {
1391 function validate( $value, $alldata ) {
1392 $p = parent::validate( $value, $alldata );
1393
1394 if ( $p !== true ) {
1395 return $p;
1396 }
1397
1398 if ( !is_string( $value ) && !is_int( $value ) ) {
1399 return false;
1400 }
1401
1402 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1403
1404 if ( in_array( $value, $validOptions ) ) {
1405 return true;
1406 } else {
1407 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1408 }
1409 }
1410
1411 /**
1412 * This returns a block of all the radio options, in one cell.
1413 * @see includes/HTMLFormField#getInputHTML()
1414 */
1415 function getInputHTML( $value ) {
1416 $html = $this->formatOptions( $this->mParams['options'], $value );
1417
1418 return $html;
1419 }
1420
1421 function formatOptions( $options, $value ) {
1422 $html = '';
1423
1424 $attribs = array();
1425 if ( !empty( $this->mParams['disabled'] ) ) {
1426 $attribs['disabled'] = 'disabled';
1427 }
1428
1429 # TODO: should this produce an unordered list perhaps?
1430 foreach ( $options as $label => $info ) {
1431 if ( is_array( $info ) ) {
1432 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1433 $html .= $this->formatOptions( $info, $value );
1434 } else {
1435 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1436 $html .= Xml::radio(
1437 $this->mName,
1438 $info,
1439 $info == $value,
1440 $attribs + array( 'id' => $id )
1441 );
1442 $html .= '&#160;' .
1443 Html::rawElement( 'label', array( 'for' => $id ), $label );
1444
1445 $html .= "<br />\n";
1446 }
1447 }
1448
1449 return $html;
1450 }
1451
1452 protected function needsLabel() {
1453 return false;
1454 }
1455 }
1456
1457 /**
1458 * An information field (text blob), not a proper input.
1459 */
1460 class HTMLInfoField extends HTMLFormField {
1461 function __construct( $info ) {
1462 $info['nodata'] = true;
1463
1464 parent::__construct( $info );
1465 }
1466
1467 function getInputHTML( $value ) {
1468 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1469 }
1470
1471 function getTableRow( $value ) {
1472 if ( !empty( $this->mParams['rawrow'] ) ) {
1473 return $value;
1474 }
1475
1476 return parent::getTableRow( $value );
1477 }
1478
1479 protected function needsLabel() {
1480 return false;
1481 }
1482 }
1483
1484 class HTMLHiddenField extends HTMLFormField {
1485 public function __construct( $params ) {
1486 parent::__construct( $params );
1487 # forcing the 'wp' prefix on hidden field names
1488 # is undesirable
1489 $this->mName = substr( $this->mName, 2 );
1490 }
1491
1492 public function getTableRow( $value ) {
1493 $params = array();
1494 if ( $this->mID ) {
1495 $params['id'] = $this->mID;
1496 }
1497
1498 $this->mParent->addHiddenField(
1499 $this->mName,
1500 $this->mDefault,
1501 $params
1502 );
1503
1504 return '';
1505 }
1506
1507 public function getInputHTML( $value ) { return ''; }
1508 }
1509
1510 /**
1511 * Add a submit button inline in the form (as opposed to
1512 * HTMLForm::addButton(), which will add it at the end).
1513 */
1514 class HTMLSubmitField extends HTMLFormField {
1515
1516 function __construct( $info ) {
1517 $info['nodata'] = true;
1518 parent::__construct( $info );
1519 }
1520
1521 function getInputHTML( $value ) {
1522 return Xml::submitButton(
1523 $value,
1524 array(
1525 'class' => 'mw-htmlform-submit',
1526 'name' => $this->mName,
1527 'id' => $this->mID,
1528 )
1529 );
1530 }
1531
1532 protected function needsLabel() {
1533 return false;
1534 }
1535 }
1536
1537 class HTMLEditTools extends HTMLFormField {
1538 public function getInputHTML( $value ) {
1539 return '';
1540 }
1541
1542 public function getTableRow( $value ) {
1543 return "<tr><td></td><td class=\"mw-input\">"
1544 . '<div class="mw-editTools">'
1545 . wfMsgExt( empty( $this->mParams['message'] )
1546 ? 'edittools' : $this->mParams['message'],
1547 array( 'parse', 'content' ) )
1548 . "</div></td></tr>\n";
1549 }
1550 }