-rakkaus/#mediawiki-i18n- (1 lines skipped) [06-Oct-2011 16:12:26] PHP Fatal error...
[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; // <! IContextSource
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 IContextSource 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, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
123 if( $context instanceof IContextSource ){
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 global $wgUsePathInfo;
434
435 $html = '';
436 if( $this->getMethod() == 'post' ){
437 $html .= Html::hidden( 'wpEditToken', $this->getUser()->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
438 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
439 }
440
441 if ( !$wgUsePathInfo && $this->getMethod() == 'get' ) {
442 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
443 }
444
445 foreach ( $this->mHiddenFields as $data ) {
446 list( $value, $attribs ) = $data;
447 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
448 }
449
450 return $html;
451 }
452
453 /**
454 * Get the submit and (potentially) reset buttons.
455 * @return String HTML.
456 */
457 function getButtons() {
458 $html = '';
459 $attribs = array();
460
461 if ( isset( $this->mSubmitID ) ) {
462 $attribs['id'] = $this->mSubmitID;
463 }
464
465 if ( isset( $this->mSubmitName ) ) {
466 $attribs['name'] = $this->mSubmitName;
467 }
468
469 if ( isset( $this->mSubmitTooltip ) ) {
470 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
471 }
472
473 $attribs['class'] = 'mw-htmlform-submit';
474
475 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
476
477 if ( $this->mShowReset ) {
478 $html .= Html::element(
479 'input',
480 array(
481 'type' => 'reset',
482 'value' => wfMsg( 'htmlform-reset' )
483 )
484 ) . "\n";
485 }
486
487 foreach ( $this->mButtons as $button ) {
488 $attrs = array(
489 'type' => 'submit',
490 'name' => $button['name'],
491 'value' => $button['value']
492 );
493
494 if ( $button['attribs'] ) {
495 $attrs += $button['attribs'];
496 }
497
498 if ( isset( $button['id'] ) ) {
499 $attrs['id'] = $button['id'];
500 }
501
502 $html .= Html::element( 'input', $attrs );
503 }
504
505 return $html;
506 }
507
508 /**
509 * Get the whole body of the form.
510 */
511 function getBody() {
512 return $this->displaySection( $this->mFieldTree );
513 }
514
515 /**
516 * Format and display an error message stack.
517 * @param $errors String|Array|Status
518 * @return String
519 */
520 function getErrors( $errors ) {
521 if ( $errors instanceof Status ) {
522 if ( $errors->isOK() ) {
523 $errorstr = '';
524 } else {
525 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
526 }
527 } elseif ( is_array( $errors ) ) {
528 $errorstr = $this->formatErrors( $errors );
529 } else {
530 $errorstr = $errors;
531 }
532
533 return $errorstr
534 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
535 : '';
536 }
537
538 /**
539 * Format a stack of error messages into a single HTML string
540 * @param $errors Array of message keys/values
541 * @return String HTML, a <ul> list of errors
542 */
543 public static function formatErrors( $errors ) {
544 $errorstr = '';
545
546 foreach ( $errors as $error ) {
547 if ( is_array( $error ) ) {
548 $msg = array_shift( $error );
549 } else {
550 $msg = $error;
551 $error = array();
552 }
553
554 $errorstr .= Html::rawElement(
555 'li',
556 array(),
557 wfMsgExt( $msg, array( 'parseinline' ), $error )
558 );
559 }
560
561 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
562
563 return $errorstr;
564 }
565
566 /**
567 * Set the text for the submit button
568 * @param $t String plaintext.
569 */
570 function setSubmitText( $t ) {
571 $this->mSubmitText = $t;
572 }
573
574 /**
575 * Get the text for the submit button, either customised or a default.
576 * @return unknown_type
577 */
578 function getSubmitText() {
579 return $this->mSubmitText
580 ? $this->mSubmitText
581 : wfMsg( 'htmlform-submit' );
582 }
583
584 public function setSubmitName( $name ) {
585 $this->mSubmitName = $name;
586 }
587
588 public function setSubmitTooltip( $name ) {
589 $this->mSubmitTooltip = $name;
590 }
591
592 /**
593 * Set the id for the submit button.
594 * @param $t String.
595 * @todo FIXME: Integrity of $t is *not* validated
596 */
597 function setSubmitID( $t ) {
598 $this->mSubmitID = $t;
599 }
600
601 public function setId( $id ) {
602 $this->mId = $id;
603 }
604 /**
605 * Prompt the whole form to be wrapped in a <fieldset>, with
606 * this text as its <legend> element.
607 * @param $legend String HTML to go inside the <legend> element.
608 * Will be escaped
609 */
610 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
611
612 /**
613 * Set the prefix for various default messages
614 * TODO: currently only used for the <fieldset> legend on forms
615 * with multiple sections; should be used elsewhre?
616 * @param $p String
617 */
618 function setMessagePrefix( $p ) {
619 $this->mMessagePrefix = $p;
620 }
621
622 /**
623 * Set the title for form submission
624 * @param $t Title of page the form is on/should be posted to
625 */
626 function setTitle( $t ) {
627 $this->mTitle = $t;
628 }
629
630 /**
631 * Get the title
632 * @return Title
633 */
634 function getTitle() {
635 return $this->mTitle === false
636 ? $this->getContext()->getTitle()
637 : $this->mTitle;
638 }
639
640 /**
641 * @return IContextSource
642 */
643 public function getContext(){
644 return $this->mContext instanceof IContextSource
645 ? $this->mContext
646 : RequestContext::getMain();
647 }
648
649 /**
650 * @return OutputPage
651 */
652 public function getOutput(){
653 return $this->getContext()->getOutput();
654 }
655
656 /**
657 * @return WebRequest
658 */
659 public function getRequest(){
660 return $this->getContext()->getRequest();
661 }
662
663 /**
664 * @return User
665 */
666 public function getUser(){
667 return $this->getContext()->getUser();
668 }
669
670 /**
671 * Set the method used to submit the form
672 * @param $method String
673 */
674 public function setMethod( $method='post' ){
675 $this->mMethod = $method;
676 }
677
678 public function getMethod(){
679 return $this->mMethod;
680 }
681
682 /**
683 * TODO: Document
684 * @param $fields array of fields (either arrays or objects)
685 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
686 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
687 */
688 function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
689 $tableHtml = '';
690 $subsectionHtml = '';
691 $hasLeftColumn = false;
692
693 foreach ( $fields as $key => $value ) {
694 if ( is_object( $value ) ) {
695 $v = empty( $value->mParams['nodata'] )
696 ? $this->mFieldData[$key]
697 : $value->getDefault();
698 $tableHtml .= $value->getTableRow( $v );
699
700 if ( $value->getLabel() != '&#160;' ) {
701 $hasLeftColumn = true;
702 }
703 } elseif ( is_array( $value ) ) {
704 $section = $this->displaySection( $value, $key );
705 $legend = $this->getLegend( $key );
706 if ( isset( $this->mSectionHeaders[$key] ) ) {
707 $section = $this->mSectionHeaders[$key] . $section;
708 }
709 if ( isset( $this->mSectionFooters[$key] ) ) {
710 $section .= $this->mSectionFooters[$key];
711 }
712 $attributes = array();
713 if ( $fieldsetIDPrefix ) {
714 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
715 }
716 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
717 }
718 }
719
720 $classes = array();
721
722 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
723 $classes[] = 'mw-htmlform-nolabel';
724 }
725
726 $attribs = array(
727 'class' => implode( ' ', $classes ),
728 );
729
730 if ( $sectionName ) {
731 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
732 }
733
734 $tableHtml = Html::rawElement( 'table', $attribs,
735 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
736
737 return $subsectionHtml . "\n" . $tableHtml;
738 }
739
740 /**
741 * Construct the form fields from the Descriptor array
742 */
743 function loadData() {
744 $fieldData = array();
745
746 foreach ( $this->mFlatFields as $fieldname => $field ) {
747 if ( !empty( $field->mParams['nodata'] ) ) {
748 continue;
749 } elseif ( !empty( $field->mParams['disabled'] ) ) {
750 $fieldData[$fieldname] = $field->getDefault();
751 } else {
752 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
753 }
754 }
755
756 # Filter data.
757 foreach ( $fieldData as $name => &$value ) {
758 $field = $this->mFlatFields[$name];
759 $value = $field->filter( $value, $this->mFlatFields );
760 }
761
762 $this->mFieldData = $fieldData;
763 }
764
765 /**
766 * Stop a reset button being shown for this form
767 * @param $suppressReset Bool set to false to re-enable the
768 * button again
769 */
770 function suppressReset( $suppressReset = true ) {
771 $this->mShowReset = !$suppressReset;
772 }
773
774 /**
775 * Overload this if you want to apply special filtration routines
776 * to the form as a whole, after it's submitted but before it's
777 * processed.
778 * @param $data
779 * @return unknown_type
780 */
781 function filterDataForSubmit( $data ) {
782 return $data;
783 }
784
785 /**
786 * Get a string to go in the <legend> of a section fieldset. Override this if you
787 * want something more complicated
788 * @param $key String
789 * @return String
790 */
791 public function getLegend( $key ) {
792 return wfMsg( "{$this->mMessagePrefix}-$key" );
793 }
794 }
795
796 /**
797 * The parent class to generate form fields. Any field type should
798 * be a subclass of this.
799 */
800 abstract class HTMLFormField {
801
802 protected $mValidationCallback;
803 protected $mFilterCallback;
804 protected $mName;
805 public $mParams;
806 protected $mLabel; # String label. Set on construction
807 protected $mID;
808 protected $mClass = '';
809 protected $mDefault;
810
811 /**
812 * @var HTMLForm
813 */
814 public $mParent;
815
816 /**
817 * This function must be implemented to return the HTML to generate
818 * the input object itself. It should not implement the surrounding
819 * table cells/rows, or labels/help messages.
820 * @param $value String the value to set the input to; eg a default
821 * text for a text input.
822 * @return String valid HTML.
823 */
824 abstract function getInputHTML( $value );
825
826 /**
827 * Override this function to add specific validation checks on the
828 * field input. Don't forget to call parent::validate() to ensure
829 * that the user-defined callback mValidationCallback is still run
830 * @param $value String the value the field was submitted with
831 * @param $alldata Array the data collected from the form
832 * @return Mixed Bool true on success, or String error to display.
833 */
834 function validate( $value, $alldata ) {
835 if ( isset( $this->mValidationCallback ) ) {
836 return call_user_func( $this->mValidationCallback, $value, $alldata );
837 }
838
839 if ( isset( $this->mParams['required'] ) && $value === '' ) {
840 return wfMsgExt( 'htmlform-required', 'parseinline' );
841 }
842
843 return true;
844 }
845
846 function filter( $value, $alldata ) {
847 if ( isset( $this->mFilterCallback ) ) {
848 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
849 }
850
851 return $value;
852 }
853
854 /**
855 * Should this field have a label, or is there no input element with the
856 * appropriate id for the label to point to?
857 *
858 * @return bool True to output a label, false to suppress
859 */
860 protected function needsLabel() {
861 return true;
862 }
863
864 /**
865 * Get the value that this input has been set to from a posted form,
866 * or the input's default value if it has not been set.
867 * @param $request WebRequest
868 * @return String the value
869 */
870 function loadDataFromRequest( $request ) {
871 if ( $request->getCheck( $this->mName ) ) {
872 return $request->getText( $this->mName );
873 } else {
874 return $this->getDefault();
875 }
876 }
877
878 /**
879 * Initialise the object
880 * @param $params array Associative Array. See HTMLForm doc for syntax.
881 */
882 function __construct( $params ) {
883 $this->mParams = $params;
884
885 # Generate the label from a message, if possible
886 if ( isset( $params['label-message'] ) ) {
887 $msgInfo = $params['label-message'];
888
889 if ( is_array( $msgInfo ) ) {
890 $msg = array_shift( $msgInfo );
891 } else {
892 $msg = $msgInfo;
893 $msgInfo = array();
894 }
895
896 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
897 } elseif ( isset( $params['label'] ) ) {
898 $this->mLabel = $params['label'];
899 }
900
901 $this->mName = "wp{$params['fieldname']}";
902 if ( isset( $params['name'] ) ) {
903 $this->mName = $params['name'];
904 }
905
906 $validName = Sanitizer::escapeId( $this->mName );
907 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
908 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
909 }
910
911 $this->mID = "mw-input-{$this->mName}";
912
913 if ( isset( $params['default'] ) ) {
914 $this->mDefault = $params['default'];
915 }
916
917 if ( isset( $params['id'] ) ) {
918 $id = $params['id'];
919 $validId = Sanitizer::escapeId( $id );
920
921 if ( $id != $validId ) {
922 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
923 }
924
925 $this->mID = $id;
926 }
927
928 if ( isset( $params['cssclass'] ) ) {
929 $this->mClass = $params['cssclass'];
930 }
931
932 if ( isset( $params['validation-callback'] ) ) {
933 $this->mValidationCallback = $params['validation-callback'];
934 }
935
936 if ( isset( $params['filter-callback'] ) ) {
937 $this->mFilterCallback = $params['filter-callback'];
938 }
939 }
940
941 /**
942 * Get the complete table row for the input, including help text,
943 * labels, and whatever.
944 * @param $value String the value to set the input to.
945 * @return String complete HTML table row.
946 */
947 function getTableRow( $value ) {
948 # Check for invalid data.
949
950 $errors = $this->validate( $value, $this->mParent->mFieldData );
951
952 $cellAttributes = array();
953 $verticalLabel = false;
954
955 if ( !empty($this->mParams['vertical-label']) ) {
956 $cellAttributes['colspan'] = 2;
957 $verticalLabel = true;
958 }
959
960 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
961 $errors = '';
962 $errorClass = '';
963 } else {
964 $errors = self::formatErrors( $errors );
965 $errorClass = 'mw-htmlform-invalid-input';
966 }
967
968 $label = $this->getLabelHtml( $cellAttributes );
969 $field = Html::rawElement(
970 'td',
971 array( 'class' => 'mw-input' ) + $cellAttributes,
972 $this->getInputHTML( $value ) . "\n$errors"
973 );
974
975 $fieldType = get_class( $this );
976
977 if ( $verticalLabel ) {
978 $html = Html::rawElement( 'tr',
979 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
980 $html .= Html::rawElement( 'tr',
981 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
982 $field );
983 } else {
984 $html = Html::rawElement( 'tr',
985 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
986 $label . $field );
987 }
988
989 $helptext = null;
990
991 if ( isset( $this->mParams['help-message'] ) ) {
992 $msg = wfMessage( $this->mParams['help-message'] );
993 if ( $msg->exists() ) {
994 $helptext = $msg->parse();
995 }
996 } elseif ( isset( $this->mParams['help-messages'] ) ) {
997 # help-message can be passed a message key (string) or an array containing
998 # a message key and additional parameters. This makes it impossible to pass
999 # an array of message key
1000 foreach( $this->mParams['help-messages'] as $name ) {
1001 $msg = wfMessage( $name );
1002 if( $msg->exists() ) {
1003 $helptext .= $msg->parse(); // append message
1004 }
1005 }
1006 } elseif ( isset( $this->mParams['help'] ) ) {
1007 $helptext = $this->mParams['help'];
1008 }
1009
1010 if ( !is_null( $helptext ) ) {
1011 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1012 $helptext );
1013 $row = Html::rawElement( 'tr', array(), $row );
1014 $html .= "$row\n";
1015 }
1016
1017 return $html;
1018 }
1019
1020 function getLabel() {
1021 return $this->mLabel;
1022 }
1023 function getLabelHtml( $cellAttributes = array() ) {
1024 # Don't output a for= attribute for labels with no associated input.
1025 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1026 $for = array();
1027
1028 if ( $this->needsLabel() ) {
1029 $for['for'] = $this->mID;
1030 }
1031
1032 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1033 Html::rawElement( 'label', $for, $this->getLabel() )
1034 );
1035 }
1036
1037 function getDefault() {
1038 if ( isset( $this->mDefault ) ) {
1039 return $this->mDefault;
1040 } else {
1041 return null;
1042 }
1043 }
1044
1045 /**
1046 * Returns the attributes required for the tooltip and accesskey.
1047 *
1048 * @return array Attributes
1049 */
1050 public function getTooltipAndAccessKey() {
1051 if ( empty( $this->mParams['tooltip'] ) ) {
1052 return array();
1053 }
1054 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1055 }
1056
1057 /**
1058 * flatten an array of options to a single array, for instance,
1059 * a set of <options> inside <optgroups>.
1060 * @param $options Associative Array with values either Strings
1061 * or Arrays
1062 * @return Array flattened input
1063 */
1064 public static function flattenOptions( $options ) {
1065 $flatOpts = array();
1066
1067 foreach ( $options as $value ) {
1068 if ( is_array( $value ) ) {
1069 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1070 } else {
1071 $flatOpts[] = $value;
1072 }
1073 }
1074
1075 return $flatOpts;
1076 }
1077
1078 /**
1079 * Formats one or more errors as accepted by field validation-callback.
1080 * @param $errors String|Message|Array of strings or Message instances
1081 * @return String html
1082 * @since 1.18
1083 */
1084 protected static function formatErrors( $errors ) {
1085 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1086 $errors = array_shift( $errors );
1087 }
1088
1089 if ( is_array( $errors ) ) {
1090 $lines = array();
1091 foreach ( $errors as $error ) {
1092 if ( $error instanceof Message ) {
1093 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1094 } else {
1095 $lines[] = Html::rawElement( 'li', array(), $error );
1096 }
1097 }
1098 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1099 } else {
1100 if ( $errors instanceof Message ) {
1101 $errors = $errors->parse();
1102 }
1103 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1104 }
1105 }
1106 }
1107
1108 class HTMLTextField extends HTMLFormField {
1109 function getSize() {
1110 return isset( $this->mParams['size'] )
1111 ? $this->mParams['size']
1112 : 45;
1113 }
1114
1115 function getInputHTML( $value ) {
1116 $attribs = array(
1117 'id' => $this->mID,
1118 'name' => $this->mName,
1119 'size' => $this->getSize(),
1120 'value' => $value,
1121 ) + $this->getTooltipAndAccessKey();
1122
1123 if ( isset( $this->mParams['maxlength'] ) ) {
1124 $attribs['maxlength'] = $this->mParams['maxlength'];
1125 }
1126
1127 if ( !empty( $this->mParams['disabled'] ) ) {
1128 $attribs['disabled'] = 'disabled';
1129 }
1130
1131 # TODO: Enforce pattern, step, required, readonly on the server side as
1132 # well
1133 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1134 'placeholder' ) as $param ) {
1135 if ( isset( $this->mParams[$param] ) ) {
1136 $attribs[$param] = $this->mParams[$param];
1137 }
1138 }
1139
1140 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1141 if ( isset( $this->mParams[$param] ) ) {
1142 $attribs[$param] = '';
1143 }
1144 }
1145
1146 # Implement tiny differences between some field variants
1147 # here, rather than creating a new class for each one which
1148 # is essentially just a clone of this one.
1149 if ( isset( $this->mParams['type'] ) ) {
1150 switch ( $this->mParams['type'] ) {
1151 case 'email':
1152 $attribs['type'] = 'email';
1153 break;
1154 case 'int':
1155 $attribs['type'] = 'number';
1156 break;
1157 case 'float':
1158 $attribs['type'] = 'number';
1159 $attribs['step'] = 'any';
1160 break;
1161 # Pass through
1162 case 'password':
1163 case 'file':
1164 $attribs['type'] = $this->mParams['type'];
1165 break;
1166 }
1167 }
1168
1169 return Html::element( 'input', $attribs );
1170 }
1171 }
1172 class HTMLTextAreaField extends HTMLFormField {
1173 function getCols() {
1174 return isset( $this->mParams['cols'] )
1175 ? $this->mParams['cols']
1176 : 80;
1177 }
1178
1179 function getRows() {
1180 return isset( $this->mParams['rows'] )
1181 ? $this->mParams['rows']
1182 : 25;
1183 }
1184
1185 function getInputHTML( $value ) {
1186 $attribs = array(
1187 'id' => $this->mID,
1188 'name' => $this->mName,
1189 'cols' => $this->getCols(),
1190 'rows' => $this->getRows(),
1191 ) + $this->getTooltipAndAccessKey();
1192
1193
1194 if ( !empty( $this->mParams['disabled'] ) ) {
1195 $attribs['disabled'] = 'disabled';
1196 }
1197
1198 if ( !empty( $this->mParams['readonly'] ) ) {
1199 $attribs['readonly'] = 'readonly';
1200 }
1201
1202 foreach ( array( 'required', 'autofocus' ) as $param ) {
1203 if ( isset( $this->mParams[$param] ) ) {
1204 $attribs[$param] = '';
1205 }
1206 }
1207
1208 return Html::element( 'textarea', $attribs, $value );
1209 }
1210 }
1211
1212 /**
1213 * A field that will contain a numeric value
1214 */
1215 class HTMLFloatField extends HTMLTextField {
1216 function getSize() {
1217 return isset( $this->mParams['size'] )
1218 ? $this->mParams['size']
1219 : 20;
1220 }
1221
1222 function validate( $value, $alldata ) {
1223 $p = parent::validate( $value, $alldata );
1224
1225 if ( $p !== true ) {
1226 return $p;
1227 }
1228
1229 $value = trim( $value );
1230
1231 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1232 # with the addition that a leading '+' sign is ok.
1233 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1234 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1235 }
1236
1237 # The "int" part of these message names is rather confusing.
1238 # They make equal sense for all numbers.
1239 if ( isset( $this->mParams['min'] ) ) {
1240 $min = $this->mParams['min'];
1241
1242 if ( $min > $value ) {
1243 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1244 }
1245 }
1246
1247 if ( isset( $this->mParams['max'] ) ) {
1248 $max = $this->mParams['max'];
1249
1250 if ( $max < $value ) {
1251 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1252 }
1253 }
1254
1255 return true;
1256 }
1257 }
1258
1259 /**
1260 * A field that must contain a number
1261 */
1262 class HTMLIntField extends HTMLFloatField {
1263 function validate( $value, $alldata ) {
1264 $p = parent::validate( $value, $alldata );
1265
1266 if ( $p !== true ) {
1267 return $p;
1268 }
1269
1270 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1271 # with the addition that a leading '+' sign is ok. Note that leading zeros
1272 # are fine, and will be left in the input, which is useful for things like
1273 # phone numbers when you know that they are integers (the HTML5 type=tel
1274 # input does not require its value to be numeric). If you want a tidier
1275 # value to, eg, save in the DB, clean it up with intval().
1276 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1277 ) {
1278 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1279 }
1280
1281 return true;
1282 }
1283 }
1284
1285 /**
1286 * A checkbox field
1287 */
1288 class HTMLCheckField extends HTMLFormField {
1289 function getInputHTML( $value ) {
1290 if ( !empty( $this->mParams['invert'] ) ) {
1291 $value = !$value;
1292 }
1293
1294 $attr = $this->getTooltipAndAccessKey();
1295 $attr['id'] = $this->mID;
1296
1297 if ( !empty( $this->mParams['disabled'] ) ) {
1298 $attr['disabled'] = 'disabled';
1299 }
1300
1301 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1302 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1303 }
1304
1305 /**
1306 * For a checkbox, the label goes on the right hand side, and is
1307 * added in getInputHTML(), rather than HTMLFormField::getRow()
1308 */
1309 function getLabel() {
1310 return '&#160;';
1311 }
1312
1313 /**
1314 * @param $request WebRequest
1315 * @return String
1316 */
1317 function loadDataFromRequest( $request ) {
1318 $invert = false;
1319 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1320 $invert = true;
1321 }
1322
1323 // GetCheck won't work like we want for checks.
1324 if ( $request->getCheck( 'wpEditToken' ) || $this->mParent->getMethod() != 'post' ) {
1325 // XOR has the following truth table, which is what we want
1326 // INVERT VALUE | OUTPUT
1327 // true true | false
1328 // false true | true
1329 // false false | false
1330 // true false | true
1331 return $request->getBool( $this->mName ) xor $invert;
1332 } else {
1333 return $this->getDefault();
1334 }
1335 }
1336 }
1337
1338 /**
1339 * A select dropdown field. Basically a wrapper for Xmlselect class
1340 */
1341 class HTMLSelectField extends HTMLFormField {
1342 function validate( $value, $alldata ) {
1343 $p = parent::validate( $value, $alldata );
1344
1345 if ( $p !== true ) {
1346 return $p;
1347 }
1348
1349 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1350
1351 if ( in_array( $value, $validOptions ) )
1352 return true;
1353 else
1354 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1355 }
1356
1357 function getInputHTML( $value ) {
1358 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1359
1360 # If one of the options' 'name' is int(0), it is automatically selected.
1361 # because PHP sucks and thinks int(0) == 'some string'.
1362 # Working around this by forcing all of them to strings.
1363 foreach( $this->mParams['options'] as &$opt ){
1364 if( is_int( $opt ) ){
1365 $opt = strval( $opt );
1366 }
1367 }
1368 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1369
1370 if ( !empty( $this->mParams['disabled'] ) ) {
1371 $select->setAttribute( 'disabled', 'disabled' );
1372 }
1373
1374 $select->addOptions( $this->mParams['options'] );
1375
1376 return $select->getHTML();
1377 }
1378 }
1379
1380 /**
1381 * Select dropdown field, with an additional "other" textbox.
1382 */
1383 class HTMLSelectOrOtherField extends HTMLTextField {
1384 static $jsAdded = false;
1385
1386 function __construct( $params ) {
1387 if ( !in_array( 'other', $params['options'], true ) ) {
1388 $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
1389 $params['options'][$msg] = 'other';
1390 }
1391
1392 parent::__construct( $params );
1393 }
1394
1395 static function forceToStringRecursive( $array ) {
1396 if ( is_array( $array ) ) {
1397 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1398 } else {
1399 return strval( $array );
1400 }
1401 }
1402
1403 function getInputHTML( $value ) {
1404 $valInSelect = false;
1405
1406 if ( $value !== false ) {
1407 $valInSelect = in_array(
1408 $value,
1409 HTMLFormField::flattenOptions( $this->mParams['options'] )
1410 );
1411 }
1412
1413 $selected = $valInSelect ? $value : 'other';
1414
1415 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1416
1417 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1418 $select->addOptions( $opts );
1419
1420 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1421
1422 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1423
1424 if ( !empty( $this->mParams['disabled'] ) ) {
1425 $select->setAttribute( 'disabled', 'disabled' );
1426 $tbAttribs['disabled'] = 'disabled';
1427 }
1428
1429 $select = $select->getHTML();
1430
1431 if ( isset( $this->mParams['maxlength'] ) ) {
1432 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1433 }
1434
1435 $textbox = Html::input(
1436 $this->mName . '-other',
1437 $valInSelect ? '' : $value,
1438 'text',
1439 $tbAttribs
1440 );
1441
1442 return "$select<br />\n$textbox";
1443 }
1444
1445 /**
1446 * @param $request WebRequest
1447 * @return String
1448 */
1449 function loadDataFromRequest( $request ) {
1450 if ( $request->getCheck( $this->mName ) ) {
1451 $val = $request->getText( $this->mName );
1452
1453 if ( $val == 'other' ) {
1454 $val = $request->getText( $this->mName . '-other' );
1455 }
1456
1457 return $val;
1458 } else {
1459 return $this->getDefault();
1460 }
1461 }
1462 }
1463
1464 /**
1465 * Multi-select field
1466 */
1467 class HTMLMultiSelectField extends HTMLFormField {
1468
1469 public function __construct( $params ){
1470 parent::__construct( $params );
1471 if( isset( $params['flatlist'] ) ){
1472 $this->mClass .= ' mw-htmlform-multiselect-flatlist';
1473 }
1474 }
1475
1476 function validate( $value, $alldata ) {
1477 $p = parent::validate( $value, $alldata );
1478
1479 if ( $p !== true ) {
1480 return $p;
1481 }
1482
1483 if ( !is_array( $value ) ) {
1484 return false;
1485 }
1486
1487 # If all options are valid, array_intersect of the valid options
1488 # and the provided options will return the provided options.
1489 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1490
1491 $validValues = array_intersect( $value, $validOptions );
1492 if ( count( $validValues ) == count( $value ) ) {
1493 return true;
1494 } else {
1495 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1496 }
1497 }
1498
1499 function getInputHTML( $value ) {
1500 $html = $this->formatOptions( $this->mParams['options'], $value );
1501
1502 return $html;
1503 }
1504
1505 function formatOptions( $options, $value ) {
1506 $html = '';
1507
1508 $attribs = array();
1509
1510 if ( !empty( $this->mParams['disabled'] ) ) {
1511 $attribs['disabled'] = 'disabled';
1512 }
1513
1514 foreach ( $options as $label => $info ) {
1515 if ( is_array( $info ) ) {
1516 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1517 $html .= $this->formatOptions( $info, $value );
1518 } else {
1519 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1520
1521 $checkbox = Xml::check(
1522 $this->mName . '[]',
1523 in_array( $info, $value, true ),
1524 $attribs + $thisAttribs );
1525 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1526
1527 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-multiselect-item' ), $checkbox );
1528 }
1529 }
1530
1531 return $html;
1532 }
1533
1534 /**
1535 * @param $request WebRequest
1536 * @return String
1537 */
1538 function loadDataFromRequest( $request ) {
1539 if ( $this->mParent->getMethod() == 'post' ) {
1540 if( $request->wasPosted() ){
1541 # Checkboxes are just not added to the request arrays if they're not checked,
1542 # so it's perfectly possible for there not to be an entry at all
1543 return $request->getArray( $this->mName, array() );
1544 } else {
1545 # That's ok, the user has not yet submitted the form, so show the defaults
1546 return $this->getDefault();
1547 }
1548 } else {
1549 # This is the impossible case: if we look at $_GET and see no data for our
1550 # field, is it because the user has not yet submitted the form, or that they
1551 # have submitted it with all the options unchecked? We will have to assume the
1552 # latter, which basically means that you can't specify 'positive' defaults
1553 # for GET forms.
1554 # @todo FIXME...
1555 return $request->getArray( $this->mName, array() );
1556 }
1557 }
1558
1559 function getDefault() {
1560 if ( isset( $this->mDefault ) ) {
1561 return $this->mDefault;
1562 } else {
1563 return array();
1564 }
1565 }
1566
1567 protected function needsLabel() {
1568 return false;
1569 }
1570 }
1571
1572 /**
1573 * Double field with a dropdown list constructed from a system message in the format
1574 * * Optgroup header
1575 * ** <option value>
1576 * * New Optgroup header
1577 * Plus a text field underneath for an additional reason. The 'value' of the field is
1578 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1579 * select dropdown.
1580 * @todo FIXME: If made 'required', only the text field should be compulsory.
1581 */
1582 class HTMLSelectAndOtherField extends HTMLSelectField {
1583
1584 function __construct( $params ) {
1585 if ( array_key_exists( 'other', $params ) ) {
1586 } elseif( array_key_exists( 'other-message', $params ) ){
1587 $params['other'] = wfMessage( $params['other-message'] )->plain();
1588 } else {
1589 $params['other'] = null;
1590 }
1591
1592 if ( array_key_exists( 'options', $params ) ) {
1593 # Options array already specified
1594 } elseif( array_key_exists( 'options-message', $params ) ){
1595 # Generate options array from a system message
1596 $params['options'] = self::parseMessage(
1597 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1598 $params['other']
1599 );
1600 } else {
1601 # Sulk
1602 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1603 }
1604 $this->mFlatOptions = self::flattenOptions( $params['options'] );
1605
1606 parent::__construct( $params );
1607 }
1608
1609 /**
1610 * Build a drop-down box from a textual list.
1611 * @param $string String message text
1612 * @param $otherName String name of "other reason" option
1613 * @return Array
1614 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1615 */
1616 public static function parseMessage( $string, $otherName=null ) {
1617 if( $otherName === null ){
1618 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1619 }
1620
1621 $optgroup = false;
1622 $options = array( $otherName => 'other' );
1623
1624 foreach ( explode( "\n", $string ) as $option ) {
1625 $value = trim( $option );
1626 if ( $value == '' ) {
1627 continue;
1628 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
1629 # A new group is starting...
1630 $value = trim( substr( $value, 1 ) );
1631 $optgroup = $value;
1632 } elseif ( substr( $value, 0, 2) == '**' ) {
1633 # groupmember
1634 $opt = trim( substr( $value, 2 ) );
1635 if( $optgroup === false ){
1636 $options[$opt] = $opt;
1637 } else {
1638 $options[$optgroup][$opt] = $opt;
1639 }
1640 } else {
1641 # groupless reason list
1642 $optgroup = false;
1643 $options[$option] = $option;
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 }