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