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