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