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