Clean up the running mess that is r64866, r65040, and then r67277. Implement and...
[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 ( $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 $html .= Html::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
401 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
402
403 foreach ( $this->mHiddenFields as $data ) {
404 list( $value, $attribs ) = $data;
405 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
406 }
407
408 return $html;
409 }
410
411 /**
412 * Get the submit and (potentially) reset buttons.
413 * @return String HTML.
414 */
415 function getButtons() {
416 $html = '';
417 $attribs = array();
418
419 if ( isset( $this->mSubmitID ) ) {
420 $attribs['id'] = $this->mSubmitID;
421 }
422
423 if ( isset( $this->mSubmitName ) ) {
424 $attribs['name'] = $this->mSubmitName;
425 }
426
427 if ( isset( $this->mSubmitTooltip ) ) {
428 global $wgUser;
429 $attribs += $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip );
430 }
431
432 $attribs['class'] = 'mw-htmlform-submit';
433
434 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
435
436 if ( $this->mShowReset ) {
437 $html .= Html::element(
438 'input',
439 array(
440 'type' => 'reset',
441 'value' => wfMsg( 'htmlform-reset' )
442 )
443 ) . "\n";
444 }
445
446 foreach ( $this->mButtons as $button ) {
447 $attrs = array(
448 'type' => 'submit',
449 'name' => $button['name'],
450 'value' => $button['value']
451 );
452
453 if ( $button['attribs'] ) {
454 $attrs += $button['attribs'];
455 }
456
457 if ( isset( $button['id'] ) ) {
458 $attrs['id'] = $button['id'];
459 }
460
461 $html .= Html::element( 'input', $attrs );
462 }
463
464 return $html;
465 }
466
467 /**
468 * Get the whole body of the form.
469 */
470 function getBody() {
471 return $this->displaySection( $this->mFieldTree );
472 }
473
474 /**
475 * Format and display an error message stack.
476 * @param $errors Mixed String or Array of message keys
477 * @return String
478 */
479 function getErrors( $errors ) {
480 if ( $errors instanceof Status ) {
481 global $wgOut;
482 $errorstr = $wgOut->parse( $errors->getWikiText() );
483 } elseif ( is_array( $errors ) ) {
484 $errorstr = $this->formatErrors( $errors );
485 } else {
486 $errorstr = $errors;
487 }
488
489 return $errorstr
490 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
491 : '';
492 }
493
494 /**
495 * Format a stack of error messages into a single HTML string
496 * @param $errors Array of message keys/values
497 * @return String HTML, a <ul> list of errors
498 */
499 static function formatErrors( $errors ) {
500 $errorstr = '';
501
502 foreach ( $errors as $error ) {
503 if ( is_array( $error ) ) {
504 $msg = array_shift( $error );
505 } else {
506 $msg = $error;
507 $error = array();
508 }
509
510 $errorstr .= Html::rawElement(
511 'li',
512 null,
513 wfMsgExt( $msg, array( 'parseinline' ), $error )
514 );
515 }
516
517 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
518
519 return $errorstr;
520 }
521
522 /**
523 * Set the text for the submit button
524 * @param $t String plaintext.
525 */
526 function setSubmitText( $t ) {
527 $this->mSubmitText = $t;
528 }
529
530 /**
531 * Get the text for the submit button, either customised or a default.
532 * @return unknown_type
533 */
534 function getSubmitText() {
535 return $this->mSubmitText
536 ? $this->mSubmitText
537 : wfMsg( 'htmlform-submit' );
538 }
539
540 public function setSubmitName( $name ) {
541 $this->mSubmitName = $name;
542 }
543
544 public function setSubmitTooltip( $name ) {
545 $this->mSubmitTooltip = $name;
546 }
547
548 /**
549 * Set the id for the submit button.
550 * @param $t String. FIXME: Integrity is *not* validated
551 */
552 function setSubmitID( $t ) {
553 $this->mSubmitID = $t;
554 }
555
556 public function setId( $id ) {
557 $this->mId = $id;
558 }
559 /**
560 * Prompt the whole form to be wrapped in a <fieldset>, with
561 * this text as its <legend> element.
562 * @param $legend String HTML to go inside the <legend> element.
563 * Will be escaped
564 */
565 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
566
567 /**
568 * Set the prefix for various default messages
569 * TODO: currently only used for the <fieldset> legend on forms
570 * with multiple sections; should be used elsewhre?
571 * @param $p String
572 */
573 function setMessagePrefix( $p ) {
574 $this->mMessagePrefix = $p;
575 }
576
577 /**
578 * Set the title for form submission
579 * @param $t Title of page the form is on/should be posted to
580 */
581 function setTitle( $t ) {
582 $this->mTitle = $t;
583 }
584
585 /**
586 * Get the title
587 * @return Title
588 */
589 function getTitle() {
590 return $this->mTitle;
591 }
592
593 /**
594 * Set the method used to submit the form
595 * @param $method String
596 */
597 public function setMethod( $method='post' ){
598 $this->mMethod = $method;
599 }
600
601 public function getMethod(){
602 return $this->mMethod;
603 }
604
605 /**
606 * TODO: Document
607 * @param $fields
608 */
609 function displaySection( $fields, $sectionName = '' ) {
610 $tableHtml = '';
611 $subsectionHtml = '';
612 $hasLeftColumn = false;
613
614 foreach ( $fields as $key => $value ) {
615 if ( is_object( $value ) ) {
616 $v = empty( $value->mParams['nodata'] )
617 ? $this->mFieldData[$key]
618 : $value->getDefault();
619 $tableHtml .= $value->getTableRow( $v );
620
621 if ( $value->getLabel() != '&#160;' )
622 $hasLeftColumn = true;
623 } elseif ( is_array( $value ) ) {
624 $section = $this->displaySection( $value, $key );
625 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
626 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
627 }
628 }
629
630 $classes = array();
631
632 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
633 $classes[] = 'mw-htmlform-nolabel';
634 }
635
636 $attribs = array(
637 'class' => implode( ' ', $classes ),
638 );
639
640 if ( $sectionName ) {
641 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
642 }
643
644 $tableHtml = Html::rawElement( 'table', $attribs,
645 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
646
647 return $subsectionHtml . "\n" . $tableHtml;
648 }
649
650 /**
651 * Construct the form fields from the Descriptor array
652 */
653 function loadData() {
654 global $wgRequest;
655
656 $fieldData = array();
657
658 foreach ( $this->mFlatFields as $fieldname => $field ) {
659 if ( !empty( $field->mParams['nodata'] ) ) {
660 continue;
661 } elseif ( !empty( $field->mParams['disabled'] ) ) {
662 $fieldData[$fieldname] = $field->getDefault();
663 } else {
664 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
665 }
666 }
667
668 # Filter data.
669 foreach ( $fieldData as $name => &$value ) {
670 $field = $this->mFlatFields[$name];
671 $value = $field->filter( $value, $this->mFlatFields );
672 }
673
674 $this->mFieldData = $fieldData;
675 }
676
677 /**
678 * Stop a reset button being shown for this form
679 * @param $suppressReset Bool set to false to re-enable the
680 * button again
681 */
682 function suppressReset( $suppressReset = true ) {
683 $this->mShowReset = !$suppressReset;
684 }
685
686 /**
687 * Overload this if you want to apply special filtration routines
688 * to the form as a whole, after it's submitted but before it's
689 * processed.
690 * @param $data
691 * @return unknown_type
692 */
693 function filterDataForSubmit( $data ) {
694 return $data;
695 }
696 }
697
698 /**
699 * The parent class to generate form fields. Any field type should
700 * be a subclass of this.
701 */
702 abstract class HTMLFormField {
703
704 protected $mValidationCallback;
705 protected $mFilterCallback;
706 protected $mName;
707 public $mParams;
708 protected $mLabel; # String label. Set on construction
709 protected $mID;
710 protected $mClass = '';
711 protected $mDefault;
712 public $mParent;
713
714 /**
715 * This function must be implemented to return the HTML to generate
716 * the input object itself. It should not implement the surrounding
717 * table cells/rows, or labels/help messages.
718 * @param $value String the value to set the input to; eg a default
719 * text for a text input.
720 * @return String valid HTML.
721 */
722 abstract function getInputHTML( $value );
723
724 /**
725 * Override this function to add specific validation checks on the
726 * field input. Don't forget to call parent::validate() to ensure
727 * that the user-defined callback mValidationCallback is still run
728 * @param $value String the value the field was submitted with
729 * @param $alldata Array the data collected from the form
730 * @return Mixed Bool true on success, or String error to display.
731 */
732 function validate( $value, $alldata ) {
733 if ( isset( $this->mValidationCallback ) ) {
734 return call_user_func( $this->mValidationCallback, $value, $alldata );
735 }
736
737 if ( isset( $this->mParams['required'] ) && $value === '' ) {
738 return wfMsgExt( 'htmlform-required', 'parseinline' );
739 }
740
741 return true;
742 }
743
744 function filter( $value, $alldata ) {
745 if ( isset( $this->mFilterCallback ) ) {
746 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
747 }
748
749 return $value;
750 }
751
752 /**
753 * Should this field have a label, or is there no input element with the
754 * appropriate id for the label to point to?
755 *
756 * @return bool True to output a label, false to suppress
757 */
758 protected function needsLabel() {
759 return true;
760 }
761
762 /**
763 * Get the value that this input has been set to from a posted form,
764 * or the input's default value if it has not been set.
765 * @param $request WebRequest
766 * @return String the value
767 */
768 function loadDataFromRequest( $request ) {
769 if ( $request->getCheck( $this->mName ) ) {
770 return $request->getText( $this->mName );
771 } else {
772 return $this->getDefault();
773 }
774 }
775
776 /**
777 * Initialise the object
778 * @param $params Associative Array. See HTMLForm doc for syntax.
779 */
780 function __construct( $params ) {
781 $this->mParams = $params;
782
783 # Generate the label from a message, if possible
784 if ( isset( $params['label-message'] ) ) {
785 $msgInfo = $params['label-message'];
786
787 if ( is_array( $msgInfo ) ) {
788 $msg = array_shift( $msgInfo );
789 } else {
790 $msg = $msgInfo;
791 $msgInfo = array();
792 }
793
794 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
795 } elseif ( isset( $params['label'] ) ) {
796 $this->mLabel = $params['label'];
797 }
798
799 $this->mName = "wp{$params['fieldname']}";
800 if ( isset( $params['name'] ) ) {
801 $this->mName = $params['name'];
802 }
803
804 $validName = Sanitizer::escapeId( $this->mName );
805 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
806 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
807 }
808
809 $this->mID = "mw-input-{$this->mName}";
810
811 if ( isset( $params['default'] ) ) {
812 $this->mDefault = $params['default'];
813 }
814
815 if ( isset( $params['id'] ) ) {
816 $id = $params['id'];
817 $validId = Sanitizer::escapeId( $id );
818
819 if ( $id != $validId ) {
820 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
821 }
822
823 $this->mID = $id;
824 }
825
826 if ( isset( $params['cssclass'] ) ) {
827 $this->mClass = $params['cssclass'];
828 }
829
830 if ( isset( $params['validation-callback'] ) ) {
831 $this->mValidationCallback = $params['validation-callback'];
832 }
833
834 if ( isset( $params['filter-callback'] ) ) {
835 $this->mFilterCallback = $params['filter-callback'];
836 }
837 }
838
839 /**
840 * Get the complete table row for the input, including help text,
841 * labels, and whatever.
842 * @param $value String the value to set the input to.
843 * @return String complete HTML table row.
844 */
845 function getTableRow( $value ) {
846 # Check for invalid data.
847 global $wgRequest;
848
849 $errors = $this->validate( $value, $this->mParent->mFieldData );
850
851 $cellAttributes = array();
852 $verticalLabel = false;
853
854 if ( !empty($this->mParams['vertical-label']) ) {
855 $cellAttributes['colspan'] = 2;
856 $verticalLabel = true;
857 }
858
859 if ( $errors === true || ( !$wgRequest->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
860 $errors = '';
861 } else {
862 $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
863 }
864
865 $label = $this->getLabelHtml( $cellAttributes );
866 $field = Html::rawElement(
867 'td',
868 array( 'class' => 'mw-input' ) + $cellAttributes,
869 $this->getInputHTML( $value ) . "\n$errors"
870 );
871
872 $fieldType = get_class( $this );
873
874 if ($verticalLabel) {
875 $html = Html::rawElement( 'tr',
876 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
877 $html .= Html::rawElement( 'tr',
878 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
879 $field );
880 } else {
881 $html = Html::rawElement( 'tr',
882 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
883 $label . $field );
884 }
885
886 $helptext = null;
887
888 if ( isset( $this->mParams['help-message'] ) ) {
889 $msg = $this->mParams['help-message'];
890 $helptext = wfMsgExt( $msg, 'parseinline' );
891 if ( wfEmptyMsg( $msg, $helptext ) ) {
892 # Never mind
893 $helptext = null;
894 }
895 } elseif ( isset( $this->mParams['help'] ) ) {
896 $helptext = $this->mParams['help'];
897 }
898
899 if ( !is_null( $helptext ) ) {
900 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
901 $helptext );
902 $row = Html::rawElement( 'tr', array(), $row );
903 $html .= "$row\n";
904 }
905
906 return $html;
907 }
908
909 function getLabel() {
910 return $this->mLabel;
911 }
912 function getLabelHtml( $cellAttributes = array() ) {
913 # Don't output a for= attribute for labels with no associated input.
914 # Kind of hacky here, possibly we don't want these to be <label>s at all.
915 $for = array();
916
917 if ( $this->needsLabel() ) {
918 $for['for'] = $this->mID;
919 }
920
921 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
922 Html::rawElement( 'label', $for, $this->getLabel() )
923 );
924 }
925
926 function getDefault() {
927 if ( isset( $this->mDefault ) ) {
928 return $this->mDefault;
929 } else {
930 return null;
931 }
932 }
933
934 /**
935 * Returns the attributes required for the tooltip and accesskey.
936 *
937 * @return array Attributes
938 */
939 public function getTooltipAndAccessKey() {
940 if ( empty( $this->mParams['tooltip'] ) ) {
941 return array();
942 }
943
944 global $wgUser;
945
946 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
947 }
948
949 /**
950 * flatten an array of options to a single array, for instance,
951 * a set of <options> inside <optgroups>.
952 * @param $options Associative Array with values either Strings
953 * or Arrays
954 * @return Array flattened input
955 */
956 public static function flattenOptions( $options ) {
957 $flatOpts = array();
958
959 foreach ( $options as $value ) {
960 if ( is_array( $value ) ) {
961 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
962 } else {
963 $flatOpts[] = $value;
964 }
965 }
966
967 return $flatOpts;
968 }
969 }
970
971 class HTMLTextField extends HTMLFormField {
972 function getSize() {
973 return isset( $this->mParams['size'] )
974 ? $this->mParams['size']
975 : 45;
976 }
977
978 function getInputHTML( $value ) {
979 $attribs = array(
980 'id' => $this->mID,
981 'name' => $this->mName,
982 'size' => $this->getSize(),
983 'value' => $value,
984 ) + $this->getTooltipAndAccessKey();
985
986 if ( isset( $this->mParams['maxlength'] ) ) {
987 $attribs['maxlength'] = $this->mParams['maxlength'];
988 }
989
990 if ( !empty( $this->mParams['disabled'] ) ) {
991 $attribs['disabled'] = 'disabled';
992 }
993
994 # TODO: Enforce pattern, step, required, readonly on the server side as
995 # well
996 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
997 'placeholder' ) as $param ) {
998 if ( isset( $this->mParams[$param] ) ) {
999 $attribs[$param] = $this->mParams[$param];
1000 }
1001 }
1002
1003 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1004 if ( isset( $this->mParams[$param] ) ) {
1005 $attribs[$param] = '';
1006 }
1007 }
1008
1009 # Implement tiny differences between some field variants
1010 # here, rather than creating a new class for each one which
1011 # is essentially just a clone of this one.
1012 if ( isset( $this->mParams['type'] ) ) {
1013 switch ( $this->mParams['type'] ) {
1014 case 'email':
1015 $attribs['type'] = 'email';
1016 break;
1017 case 'int':
1018 $attribs['type'] = 'number';
1019 break;
1020 case 'float':
1021 $attribs['type'] = 'number';
1022 $attribs['step'] = 'any';
1023 break;
1024 # Pass through
1025 case 'password':
1026 case 'file':
1027 $attribs['type'] = $this->mParams['type'];
1028 break;
1029 }
1030 }
1031
1032 return Html::element( 'input', $attribs );
1033 }
1034 }
1035 class HTMLTextAreaField extends HTMLFormField {
1036 function getCols() {
1037 return isset( $this->mParams['cols'] )
1038 ? $this->mParams['cols']
1039 : 80;
1040 }
1041
1042 function getRows() {
1043 return isset( $this->mParams['rows'] )
1044 ? $this->mParams['rows']
1045 : 25;
1046 }
1047
1048 function getInputHTML( $value ) {
1049 $attribs = array(
1050 'id' => $this->mID,
1051 'name' => $this->mName,
1052 'cols' => $this->getCols(),
1053 'rows' => $this->getRows(),
1054 ) + $this->getTooltipAndAccessKey();
1055
1056
1057 if ( !empty( $this->mParams['disabled'] ) ) {
1058 $attribs['disabled'] = 'disabled';
1059 }
1060
1061 if ( !empty( $this->mParams['readonly'] ) ) {
1062 $attribs['readonly'] = 'readonly';
1063 }
1064
1065 foreach ( array( 'required', 'autofocus' ) as $param ) {
1066 if ( isset( $this->mParams[$param] ) ) {
1067 $attribs[$param] = '';
1068 }
1069 }
1070
1071 return Html::element( 'textarea', $attribs, $value );
1072 }
1073 }
1074
1075 /**
1076 * A field that will contain a numeric value
1077 */
1078 class HTMLFloatField extends HTMLTextField {
1079 function getSize() {
1080 return isset( $this->mParams['size'] )
1081 ? $this->mParams['size']
1082 : 20;
1083 }
1084
1085 function validate( $value, $alldata ) {
1086 $p = parent::validate( $value, $alldata );
1087
1088 if ( $p !== true ) {
1089 return $p;
1090 }
1091
1092 $value = trim( $value );
1093
1094 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1095 # with the addition that a leading '+' sign is ok.
1096 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1097 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1098 }
1099
1100 # The "int" part of these message names is rather confusing.
1101 # They make equal sense for all numbers.
1102 if ( isset( $this->mParams['min'] ) ) {
1103 $min = $this->mParams['min'];
1104
1105 if ( $min > $value ) {
1106 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1107 }
1108 }
1109
1110 if ( isset( $this->mParams['max'] ) ) {
1111 $max = $this->mParams['max'];
1112
1113 if ( $max < $value ) {
1114 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1115 }
1116 }
1117
1118 return true;
1119 }
1120 }
1121
1122 /**
1123 * A field that must contain a number
1124 */
1125 class HTMLIntField extends HTMLFloatField {
1126 function validate( $value, $alldata ) {
1127 $p = parent::validate( $value, $alldata );
1128
1129 if ( $p !== true ) {
1130 return $p;
1131 }
1132
1133 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1134 # with the addition that a leading '+' sign is ok. Note that leading zeros
1135 # are fine, and will be left in the input, which is useful for things like
1136 # phone numbers when you know that they are integers (the HTML5 type=tel
1137 # input does not require its value to be numeric). If you want a tidier
1138 # value to, eg, save in the DB, clean it up with intval().
1139 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1140 ) {
1141 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1142 }
1143
1144 return true;
1145 }
1146 }
1147
1148 /**
1149 * A checkbox field
1150 */
1151 class HTMLCheckField extends HTMLFormField {
1152 function getInputHTML( $value ) {
1153 if ( !empty( $this->mParams['invert'] ) ) {
1154 $value = !$value;
1155 }
1156
1157 $attr = $this->getTooltipAndAccessKey();
1158 $attr['id'] = $this->mID;
1159
1160 if ( !empty( $this->mParams['disabled'] ) ) {
1161 $attr['disabled'] = 'disabled';
1162 }
1163
1164 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1165 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1166 }
1167
1168 /**
1169 * For a checkbox, the label goes on the right hand side, and is
1170 * added in getInputHTML(), rather than HTMLFormField::getRow()
1171 */
1172 function getLabel() {
1173 return '&#160;';
1174 }
1175
1176 function loadDataFromRequest( $request ) {
1177 $invert = false;
1178 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1179 $invert = true;
1180 }
1181
1182 // GetCheck won't work like we want for checks.
1183 if ( $request->getCheck( 'wpEditToken' ) ) {
1184 // XOR has the following truth table, which is what we want
1185 // INVERT VALUE | OUTPUT
1186 // true true | false
1187 // false true | true
1188 // false false | false
1189 // true false | true
1190 return $request->getBool( $this->mName ) xor $invert;
1191 } else {
1192 return $this->getDefault();
1193 }
1194 }
1195 }
1196
1197 /**
1198 * A select dropdown field. Basically a wrapper for Xmlselect class
1199 */
1200 class HTMLSelectField extends HTMLFormField {
1201 function validate( $value, $alldata ) {
1202 $p = parent::validate( $value, $alldata );
1203
1204 if ( $p !== true ) {
1205 return $p;
1206 }
1207
1208 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1209
1210 if ( in_array( $value, $validOptions ) )
1211 return true;
1212 else
1213 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1214 }
1215
1216 function getInputHTML( $value ) {
1217 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1218
1219 # If one of the options' 'name' is int(0), it is automatically selected.
1220 # because PHP sucks and things int(0) == 'some string'.
1221 # Working around this by forcing all of them to strings.
1222 $options = array_map( 'strval', $this->mParams['options'] );
1223
1224 if ( !empty( $this->mParams['disabled'] ) ) {
1225 $select->setAttribute( 'disabled', 'disabled' );
1226 }
1227
1228 $select->addOptions( $options );
1229
1230 return $select->getHTML();
1231 }
1232 }
1233
1234 /**
1235 * Select dropdown field, with an additional "other" textbox.
1236 */
1237 class HTMLSelectOrOtherField extends HTMLTextField {
1238 static $jsAdded = false;
1239
1240 function __construct( $params ) {
1241 if ( !in_array( 'other', $params['options'], true ) ) {
1242 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1243 }
1244
1245 parent::__construct( $params );
1246 }
1247
1248 static function forceToStringRecursive( $array ) {
1249 if ( is_array( $array ) ) {
1250 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1251 } else {
1252 return strval( $array );
1253 }
1254 }
1255
1256 function getInputHTML( $value ) {
1257 $valInSelect = false;
1258
1259 if ( $value !== false ) {
1260 $valInSelect = in_array(
1261 $value,
1262 HTMLFormField::flattenOptions( $this->mParams['options'] )
1263 );
1264 }
1265
1266 $selected = $valInSelect ? $value : 'other';
1267
1268 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1269
1270 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1271 $select->addOptions( $opts );
1272
1273 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1274
1275 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1276
1277 if ( !empty( $this->mParams['disabled'] ) ) {
1278 $select->setAttribute( 'disabled', 'disabled' );
1279 $tbAttribs['disabled'] = 'disabled';
1280 }
1281
1282 $select = $select->getHTML();
1283
1284 if ( isset( $this->mParams['maxlength'] ) ) {
1285 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1286 }
1287
1288 $textbox = Html::input(
1289 $this->mName . '-other',
1290 $valInSelect ? '' : $value,
1291 'text',
1292 $tbAttribs
1293 );
1294
1295 return "$select<br />\n$textbox";
1296 }
1297
1298 function loadDataFromRequest( $request ) {
1299 if ( $request->getCheck( $this->mName ) ) {
1300 $val = $request->getText( $this->mName );
1301
1302 if ( $val == 'other' ) {
1303 $val = $request->getText( $this->mName . '-other' );
1304 }
1305
1306 return $val;
1307 } else {
1308 return $this->getDefault();
1309 }
1310 }
1311 }
1312
1313 /**
1314 * Multi-select field
1315 */
1316 class HTMLMultiSelectField extends HTMLFormField {
1317 function validate( $value, $alldata ) {
1318 $p = parent::validate( $value, $alldata );
1319
1320 if ( $p !== true ) {
1321 return $p;
1322 }
1323
1324 if ( !is_array( $value ) ) {
1325 return false;
1326 }
1327
1328 # If all options are valid, array_intersect of the valid options
1329 # and the provided options will return the provided options.
1330 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1331
1332 $validValues = array_intersect( $value, $validOptions );
1333 if ( count( $validValues ) == count( $value ) ) {
1334 return true;
1335 } else {
1336 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1337 }
1338 }
1339
1340 function getInputHTML( $value ) {
1341 $html = $this->formatOptions( $this->mParams['options'], $value );
1342
1343 return $html;
1344 }
1345
1346 function formatOptions( $options, $value ) {
1347 $html = '';
1348
1349 $attribs = array();
1350
1351 if ( !empty( $this->mParams['disabled'] ) ) {
1352 $attribs['disabled'] = 'disabled';
1353 }
1354
1355 foreach ( $options as $label => $info ) {
1356 if ( is_array( $info ) ) {
1357 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1358 $html .= $this->formatOptions( $info, $value );
1359 } else {
1360 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1361
1362 $checkbox = Xml::check(
1363 $this->mName . '[]',
1364 in_array( $info, $value, true ),
1365 $attribs + $thisAttribs );
1366 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1367
1368 $html .= $checkbox . '<br />';
1369 }
1370 }
1371
1372 return $html;
1373 }
1374
1375 function loadDataFromRequest( $request ) {
1376 # won't work with getCheck
1377 if ( $request->getCheck( 'wpEditToken' ) ) {
1378 $arr = $request->getArray( $this->mName );
1379
1380 if ( !$arr ) {
1381 $arr = array();
1382 }
1383
1384 return $arr;
1385 } else {
1386 return $this->getDefault();
1387 }
1388 }
1389
1390 function getDefault() {
1391 if ( isset( $this->mDefault ) ) {
1392 return $this->mDefault;
1393 } else {
1394 return array();
1395 }
1396 }
1397
1398 protected function needsLabel() {
1399 return false;
1400 }
1401 }
1402
1403 /**
1404 * Radio checkbox fields.
1405 */
1406 class HTMLRadioField extends HTMLFormField {
1407 function validate( $value, $alldata ) {
1408 $p = parent::validate( $value, $alldata );
1409
1410 if ( $p !== true ) {
1411 return $p;
1412 }
1413
1414 if ( !is_string( $value ) && !is_int( $value ) ) {
1415 return false;
1416 }
1417
1418 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1419
1420 if ( in_array( $value, $validOptions ) ) {
1421 return true;
1422 } else {
1423 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1424 }
1425 }
1426
1427 /**
1428 * This returns a block of all the radio options, in one cell.
1429 * @see includes/HTMLFormField#getInputHTML()
1430 */
1431 function getInputHTML( $value ) {
1432 $html = $this->formatOptions( $this->mParams['options'], $value );
1433
1434 return $html;
1435 }
1436
1437 function formatOptions( $options, $value ) {
1438 $html = '';
1439
1440 $attribs = array();
1441 if ( !empty( $this->mParams['disabled'] ) ) {
1442 $attribs['disabled'] = 'disabled';
1443 }
1444
1445 # TODO: should this produce an unordered list perhaps?
1446 foreach ( $options as $label => $info ) {
1447 if ( is_array( $info ) ) {
1448 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1449 $html .= $this->formatOptions( $info, $value );
1450 } else {
1451 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1452 $html .= Xml::radio(
1453 $this->mName,
1454 $info,
1455 $info == $value,
1456 $attribs + array( 'id' => $id )
1457 );
1458 $html .= '&#160;' .
1459 Html::rawElement( 'label', array( 'for' => $id ), $label );
1460
1461 $html .= "<br />\n";
1462 }
1463 }
1464
1465 return $html;
1466 }
1467
1468 protected function needsLabel() {
1469 return false;
1470 }
1471 }
1472
1473 /**
1474 * An information field (text blob), not a proper input.
1475 */
1476 class HTMLInfoField extends HTMLFormField {
1477 function __construct( $info ) {
1478 $info['nodata'] = true;
1479
1480 parent::__construct( $info );
1481 }
1482
1483 function getInputHTML( $value ) {
1484 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1485 }
1486
1487 function getTableRow( $value ) {
1488 if ( !empty( $this->mParams['rawrow'] ) ) {
1489 return $value;
1490 }
1491
1492 return parent::getTableRow( $value );
1493 }
1494
1495 protected function needsLabel() {
1496 return false;
1497 }
1498 }
1499
1500 class HTMLHiddenField extends HTMLFormField {
1501 public function __construct( $params ) {
1502 parent::__construct( $params );
1503
1504 # Per HTML5 spec, hidden fields cannot be 'required'
1505 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1506 unset( $this->mParams['required'] );
1507 }
1508
1509 public function getTableRow( $value ) {
1510 $params = array();
1511 if ( $this->mID ) {
1512 $params['id'] = $this->mID;
1513 }
1514
1515 $this->mParent->addHiddenField(
1516 $this->mName,
1517 $this->mDefault,
1518 $params
1519 );
1520
1521 return '';
1522 }
1523
1524 public function getInputHTML( $value ) { return ''; }
1525 }
1526
1527 /**
1528 * Add a submit button inline in the form (as opposed to
1529 * HTMLForm::addButton(), which will add it at the end).
1530 */
1531 class HTMLSubmitField extends HTMLFormField {
1532
1533 function __construct( $info ) {
1534 $info['nodata'] = true;
1535 parent::__construct( $info );
1536 }
1537
1538 function getInputHTML( $value ) {
1539 return Xml::submitButton(
1540 $value,
1541 array(
1542 'class' => 'mw-htmlform-submit',
1543 'name' => $this->mName,
1544 'id' => $this->mID,
1545 )
1546 );
1547 }
1548
1549 protected function needsLabel() {
1550 return false;
1551 }
1552
1553 /**
1554 * Button cannot be invalid
1555 */
1556 public function validate( $value, $alldata ){
1557 return true;
1558 }
1559 }
1560
1561 class HTMLEditTools extends HTMLFormField {
1562 public function getInputHTML( $value ) {
1563 return '';
1564 }
1565
1566 public function getTableRow( $value ) {
1567 return "<tr><td></td><td class=\"mw-input\">"
1568 . '<div class="mw-editTools">'
1569 . wfMsgExt( empty( $this->mParams['message'] )
1570 ? 'edittools' : $this->mParams['message'],
1571 array( 'parse', 'content' ) )
1572 . "</div></td></tr>\n";
1573 }
1574 }