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