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