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