5af813ba947071ddee9cedb8820b2d5c53609b48
[lhc/web/wiklou.git] / includes / HTMLForm.php
1 <?php
2 /**
3 * HTML form generation and submission handling.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Object handling generic submission, CSRF protection, layout and
25 * other logic for UI forms. in a reusable manner.
26 *
27 * In order to generate the form, the HTMLForm object takes an array
28 * structure detailing the form fields available. Each element of the
29 * array is a basic property-list, including the type of field, the
30 * label it is to be given in the form, callbacks for validation and
31 * 'filtering', and other pertinent information.
32 *
33 * Field types are implemented as subclasses of the generic HTMLFormField
34 * object, and typically implement at least getInputHTML, which generates
35 * the HTML for the input field to be placed in the table.
36 *
37 * You can find extensive documentation on the www.mediawiki.org wiki:
38 * - http://www.mediawiki.org/wiki/HTMLForm
39 * - http://www.mediawiki.org/wiki/HTMLForm/tutorial
40 *
41 * The constructor input is an associative array of $fieldname => $info,
42 * where $info is an Associative Array with any of the following:
43 *
44 * 'class' -- the subclass of HTMLFormField that will be used
45 * to create the object. *NOT* the CSS class!
46 * 'type' -- roughly translates into the <select> type attribute.
47 * if 'class' is not specified, this is used as a map
48 * through HTMLForm::$typeMappings to get the class name.
49 * 'default' -- default value when the form is displayed
50 * 'id' -- HTML id attribute
51 * 'cssclass' -- CSS class
52 * 'options' -- varies according to the specific object.
53 * 'label-message' -- message key for a message to use as the label.
54 * can be an array of msg key and then parameters to
55 * the message.
56 * 'label' -- alternatively, a raw text message. Overridden by
57 * label-message
58 * 'help' -- message text for a message to use as a help text.
59 * 'help-message' -- message key for a message to use as a help text.
60 * can be an array of msg key and then parameters to
61 * the message.
62 * Overwrites 'help-messages' and 'help'.
63 * 'help-messages' -- array of message key. As above, each item can
64 * be an array of msg key and then parameters.
65 * Overwrites 'help'.
66 * 'required' -- passed through to the object, indicating that it
67 * is a required field.
68 * 'size' -- the length of text fields
69 * 'filter-callback -- a function name to give you the chance to
70 * massage the inputted value before it's processed.
71 * @see HTMLForm::filter()
72 * 'validation-callback' -- a function name to give you the chance
73 * to impose extra validation on the field input.
74 * @see HTMLForm::validate()
75 * 'name' -- By default, the 'name' attribute of the input field
76 * is "wp{$fieldname}". If you want a different name
77 * (eg one without the "wp" prefix), specify it here and
78 * it will be used without modification.
79 *
80 * Since 1.20, you can chain mutators to ease the form generation:
81 * @par Example:
82 * @code
83 * $form = new HTMLForm( $someFields );
84 * $form->setMethod( 'get' )
85 * ->setWrapperLegendMsg( 'message-key' )
86 * ->suppressReset()
87 * ->prepareForm()
88 * ->displayForm();
89 * @endcode
90 * Note that you will have prepareForm and displayForm at the end. Other
91 * methods call done after that would simply not be part of the form :(
92 *
93 * TODO: Document 'section' / 'subsection' stuff
94 */
95 class HTMLForm extends ContextSource {
96
97 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
98 static $typeMappings = array(
99 'api' => 'HTMLApiField',
100 'text' => 'HTMLTextField',
101 'textarea' => 'HTMLTextAreaField',
102 'select' => 'HTMLSelectField',
103 'radio' => 'HTMLRadioField',
104 'multiselect' => 'HTMLMultiSelectField',
105 'check' => 'HTMLCheckField',
106 'toggle' => 'HTMLCheckField',
107 'int' => 'HTMLIntField',
108 'float' => 'HTMLFloatField',
109 'info' => 'HTMLInfoField',
110 'selectorother' => 'HTMLSelectOrOtherField',
111 'selectandother' => 'HTMLSelectAndOtherField',
112 'submit' => 'HTMLSubmitField',
113 'hidden' => 'HTMLHiddenField',
114 'edittools' => 'HTMLEditTools',
115 'checkmatrix' => 'HTMLCheckMatrix',
116
117 // HTMLTextField will output the correct type="" attribute automagically.
118 // There are about four zillion other HTML5 input types, like url, but
119 // we don't use those at the moment, so no point in adding all of them.
120 'email' => 'HTMLTextField',
121 'password' => 'HTMLTextField',
122 );
123
124 protected $mMessagePrefix;
125
126 /** @var HTMLFormField[] */
127 protected $mFlatFields;
128
129 protected $mFieldTree;
130 protected $mShowReset = false;
131 public $mFieldData;
132
133 protected $mSubmitCallback;
134 protected $mValidationErrorMessage;
135
136 protected $mPre = '';
137 protected $mHeader = '';
138 protected $mFooter = '';
139 protected $mSectionHeaders = array();
140 protected $mSectionFooters = array();
141 protected $mPost = '';
142 protected $mId;
143
144 protected $mSubmitID;
145 protected $mSubmitName;
146 protected $mSubmitText;
147 protected $mSubmitTooltip;
148
149 protected $mTitle;
150 protected $mMethod = 'post';
151
152 /**
153 * Form action URL. false means we will use the URL to set Title
154 * @since 1.19
155 * @var bool|string
156 */
157 protected $mAction = false;
158
159 protected $mUseMultipart = false;
160 protected $mHiddenFields = array();
161 protected $mButtons = array();
162
163 protected $mWrapperLegend = false;
164
165 /**
166 * If true, sections that contain both fields and subsections will
167 * render their subsections before their fields.
168 *
169 * Subclasses may set this to false to render subsections after fields
170 * instead.
171 */
172 protected $mSubSectionBeforeFields = true;
173
174 /**
175 * Format in which to display form. For viable options,
176 * @see $availableDisplayFormats
177 * @var String
178 */
179 protected $displayFormat = 'table';
180
181 /**
182 * Available formats in which to display the form
183 * @var Array
184 */
185 protected $availableDisplayFormats = array(
186 'table',
187 'div',
188 'raw',
189 );
190
191 /**
192 * Build a new HTMLForm from an array of field attributes
193 * @param $descriptor Array of Field constructs, as described above
194 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
195 * Obviates the need to call $form->setTitle()
196 * @param $messagePrefix String a prefix to go in front of default messages
197 */
198 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
199 if ( $context instanceof IContextSource ) {
200 $this->setContext( $context );
201 $this->mTitle = false; // We don't need them to set a title
202 $this->mMessagePrefix = $messagePrefix;
203 } else {
204 // B/C since 1.18
205 if ( is_string( $context ) && $messagePrefix === '' ) {
206 // it's actually $messagePrefix
207 $this->mMessagePrefix = $context;
208 }
209 }
210
211 // Expand out into a tree.
212 $loadedDescriptor = array();
213 $this->mFlatFields = array();
214
215 foreach ( $descriptor as $fieldname => $info ) {
216 $section = isset( $info['section'] )
217 ? $info['section']
218 : '';
219
220 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
221 $this->mUseMultipart = true;
222 }
223
224 $field = self::loadInputFromParameters( $fieldname, $info );
225 $field->mParent = $this;
226
227 $setSection =& $loadedDescriptor;
228 if ( $section ) {
229 $sectionParts = explode( '/', $section );
230
231 while ( count( $sectionParts ) ) {
232 $newName = array_shift( $sectionParts );
233
234 if ( !isset( $setSection[$newName] ) ) {
235 $setSection[$newName] = array();
236 }
237
238 $setSection =& $setSection[$newName];
239 }
240 }
241
242 $setSection[$fieldname] = $field;
243 $this->mFlatFields[$fieldname] = $field;
244 }
245
246 $this->mFieldTree = $loadedDescriptor;
247 }
248
249 /**
250 * Set format in which to display the form
251 * @param $format String the name of the format to use, must be one of
252 * $this->availableDisplayFormats
253 * @throws MWException
254 * @since 1.20
255 * @return HTMLForm $this for chaining calls (since 1.20)
256 */
257 public function setDisplayFormat( $format ) {
258 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
259 throw new MWException ( 'Display format must be one of ' . print_r( $this->availableDisplayFormats, true ) );
260 }
261 $this->displayFormat = $format;
262 return $this;
263 }
264
265 /**
266 * Getter for displayFormat
267 * @since 1.20
268 * @return String
269 */
270 public function getDisplayFormat() {
271 return $this->displayFormat;
272 }
273
274 /**
275 * Add the HTMLForm-specific JavaScript, if it hasn't been
276 * done already.
277 * @deprecated since 1.18 load modules with ResourceLoader instead
278 */
279 static function addJS() { wfDeprecated( __METHOD__, '1.18' ); }
280
281 /**
282 * Initialise a new Object for the field
283 * @param $fieldname string
284 * @param $descriptor string input Descriptor, as described above
285 * @throws MWException
286 * @return HTMLFormField subclass
287 */
288 static function loadInputFromParameters( $fieldname, $descriptor ) {
289 if ( isset( $descriptor['class'] ) ) {
290 $class = $descriptor['class'];
291 } elseif ( isset( $descriptor['type'] ) ) {
292 $class = self::$typeMappings[$descriptor['type']];
293 $descriptor['class'] = $class;
294 } else {
295 $class = null;
296 }
297
298 if ( !$class ) {
299 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
300 }
301
302 $descriptor['fieldname'] = $fieldname;
303
304 # TODO
305 # This will throw a fatal error whenever someone try to use
306 # 'class' to feed a CSS class instead of 'cssclass'. Would be
307 # great to avoid the fatal error and show a nice error.
308 $obj = new $class( $descriptor );
309
310 return $obj;
311 }
312
313 /**
314 * Prepare form for submission.
315 *
316 * @attention When doing method chaining, that should be the very last
317 * method call before displayForm().
318 *
319 * @throws MWException
320 * @return HTMLForm $this for chaining calls (since 1.20)
321 */
322 function prepareForm() {
323 # Check if we have the info we need
324 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
325 throw new MWException( "You must call setTitle() on an HTMLForm" );
326 }
327
328 # Load data from the request.
329 $this->loadData();
330 return $this;
331 }
332
333 /**
334 * Try submitting, with edit token check first
335 * @return Status|boolean
336 */
337 function tryAuthorizedSubmit() {
338 $result = false;
339
340 $submit = false;
341 if ( $this->getMethod() != 'post' ) {
342 $submit = true; // no session check needed
343 } elseif ( $this->getRequest()->wasPosted() ) {
344 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
345 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
346 // Session tokens for logged-out users have no security value.
347 // However, if the user gave one, check it in order to give a nice
348 // "session expired" error instead of "permission denied" or such.
349 $submit = $this->getUser()->matchEditToken( $editToken );
350 } else {
351 $submit = true;
352 }
353 }
354
355 if ( $submit ) {
356 $result = $this->trySubmit();
357 }
358
359 return $result;
360 }
361
362 /**
363 * The here's-one-I-made-earlier option: do the submission if
364 * posted, or display the form with or without funky validation
365 * errors
366 * @return Bool or Status whether submission was successful.
367 */
368 function show() {
369 $this->prepareForm();
370
371 $result = $this->tryAuthorizedSubmit();
372 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
373 return $result;
374 }
375
376 $this->displayForm( $result );
377 return false;
378 }
379
380 /**
381 * Validate all the fields, and call the submision callback
382 * function if everything is kosher.
383 * @throws MWException
384 * @return Mixed Bool true == Successful submission, Bool false
385 * == No submission attempted, anything else == Error to
386 * display.
387 */
388 function trySubmit() {
389 # Check for validation
390 foreach ( $this->mFlatFields as $fieldname => $field ) {
391 if ( !empty( $field->mParams['nodata'] ) ) {
392 continue;
393 }
394 if ( $field->validate(
395 $this->mFieldData[$fieldname],
396 $this->mFieldData )
397 !== true
398 ) {
399 return isset( $this->mValidationErrorMessage )
400 ? $this->mValidationErrorMessage
401 : array( 'htmlform-invalid-input' );
402 }
403 }
404
405 $callback = $this->mSubmitCallback;
406 if ( !is_callable( $callback ) ) {
407 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
408 }
409
410 $data = $this->filterDataForSubmit( $this->mFieldData );
411
412 $res = call_user_func( $callback, $data, $this );
413
414 return $res;
415 }
416
417 /**
418 * Set a callback to a function to do something with the form
419 * once it's been successfully validated.
420 * @param $cb String function name. The function will be passed
421 * the output from HTMLForm::filterDataForSubmit, and must
422 * return Bool true on success, Bool false if no submission
423 * was attempted, or String HTML output to display on error.
424 * @return HTMLForm $this for chaining calls (since 1.20)
425 */
426 function setSubmitCallback( $cb ) {
427 $this->mSubmitCallback = $cb;
428 return $this;
429 }
430
431 /**
432 * Set a message to display on a validation error.
433 * @param $msg Mixed String or Array of valid inputs to wfMessage()
434 * (so each entry can be either a String or Array)
435 * @return HTMLForm $this for chaining calls (since 1.20)
436 */
437 function setValidationErrorMessage( $msg ) {
438 $this->mValidationErrorMessage = $msg;
439 return $this;
440 }
441
442 /**
443 * Set the introductory message, overwriting any existing message.
444 * @param $msg String complete text of message to display
445 * @return HTMLForm $this for chaining calls (since 1.20)
446 */
447 function setIntro( $msg ) {
448 $this->setPreText( $msg );
449 return $this;
450 }
451
452 /**
453 * Set the introductory message, overwriting any existing message.
454 * @since 1.19
455 * @param $msg String complete text of message to display
456 * @return HTMLForm $this for chaining calls (since 1.20)
457 */
458 function setPreText( $msg ) {
459 $this->mPre = $msg;
460 return $this;
461 }
462
463 /**
464 * Add introductory text.
465 * @param $msg String complete text of message to display
466 * @return HTMLForm $this for chaining calls (since 1.20)
467 */
468 function addPreText( $msg ) {
469 $this->mPre .= $msg;
470 return $this;
471 }
472
473 /**
474 * Add header text, inside the form.
475 * @param $msg String complete text of message to display
476 * @param $section string The section to add the header to
477 * @return HTMLForm $this for chaining calls (since 1.20)
478 */
479 function addHeaderText( $msg, $section = null ) {
480 if ( is_null( $section ) ) {
481 $this->mHeader .= $msg;
482 } else {
483 if ( !isset( $this->mSectionHeaders[$section] ) ) {
484 $this->mSectionHeaders[$section] = '';
485 }
486 $this->mSectionHeaders[$section] .= $msg;
487 }
488 return $this;
489 }
490
491 /**
492 * Set header text, inside the form.
493 * @since 1.19
494 * @param $msg String complete text of message to display
495 * @param $section The section to add the header to
496 * @return HTMLForm $this for chaining calls (since 1.20)
497 */
498 function setHeaderText( $msg, $section = null ) {
499 if ( is_null( $section ) ) {
500 $this->mHeader = $msg;
501 } else {
502 $this->mSectionHeaders[$section] = $msg;
503 }
504 return $this;
505 }
506
507 /**
508 * Add footer text, inside the form.
509 * @param $msg String complete text of message to display
510 * @param $section string The section to add the footer text to
511 * @return HTMLForm $this for chaining calls (since 1.20)
512 */
513 function addFooterText( $msg, $section = null ) {
514 if ( is_null( $section ) ) {
515 $this->mFooter .= $msg;
516 } else {
517 if ( !isset( $this->mSectionFooters[$section] ) ) {
518 $this->mSectionFooters[$section] = '';
519 }
520 $this->mSectionFooters[$section] .= $msg;
521 }
522 return $this;
523 }
524
525 /**
526 * Set footer text, inside the form.
527 * @since 1.19
528 * @param $msg String complete text of message to display
529 * @param $section string The section to add the footer text to
530 * @return HTMLForm $this for chaining calls (since 1.20)
531 */
532 function setFooterText( $msg, $section = null ) {
533 if ( is_null( $section ) ) {
534 $this->mFooter = $msg;
535 } else {
536 $this->mSectionFooters[$section] = $msg;
537 }
538 return $this;
539 }
540
541 /**
542 * Add text to the end of the display.
543 * @param $msg String complete text of message to display
544 * @return HTMLForm $this for chaining calls (since 1.20)
545 */
546 function addPostText( $msg ) {
547 $this->mPost .= $msg;
548 return $this;
549 }
550
551 /**
552 * Set text at the end of the display.
553 * @param $msg String complete text of message to display
554 * @return HTMLForm $this for chaining calls (since 1.20)
555 */
556 function setPostText( $msg ) {
557 $this->mPost = $msg;
558 return $this;
559 }
560
561 /**
562 * Add a hidden field to the output
563 * @param $name String field name. This will be used exactly as entered
564 * @param $value String field value
565 * @param $attribs Array
566 * @return HTMLForm $this for chaining calls (since 1.20)
567 */
568 public function addHiddenField( $name, $value, $attribs = array() ) {
569 $attribs += array( 'name' => $name );
570 $this->mHiddenFields[] = array( $value, $attribs );
571 return $this;
572 }
573
574 /**
575 * Add a button to the form
576 * @param $name String field name.
577 * @param $value String field value
578 * @param $id String DOM id for the button (default: null)
579 * @param $attribs Array
580 * @return HTMLForm $this for chaining calls (since 1.20)
581 */
582 public function addButton( $name, $value, $id = null, $attribs = null ) {
583 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
584 return $this;
585 }
586
587 /**
588 * Display the form (sending to $wgOut), with an appropriate error
589 * message or stack of messages, and any validation errors, etc.
590 *
591 * @attention You should call prepareForm() before calling this function.
592 * Moreover, when doing method chaining this should be the very last method
593 * call just after prepareForm().
594 *
595 * @param $submitResult Mixed output from HTMLForm::trySubmit()
596 * @return Nothing, should be last call
597 */
598 function displayForm( $submitResult ) {
599 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
600 }
601
602 /**
603 * Returns the raw HTML generated by the form
604 * @param $submitResult Mixed output from HTMLForm::trySubmit()
605 * @return string
606 */
607 function getHTML( $submitResult ) {
608 # For good measure (it is the default)
609 $this->getOutput()->preventClickjacking();
610 $this->getOutput()->addModules( 'mediawiki.htmlform' );
611
612 $html = ''
613 . $this->getErrors( $submitResult )
614 . $this->mHeader
615 . $this->getBody()
616 . $this->getHiddenFields()
617 . $this->getButtons()
618 . $this->mFooter
619 ;
620
621 $html = $this->wrapForm( $html );
622
623 return '' . $this->mPre . $html . $this->mPost;
624 }
625
626 /**
627 * Wrap the form innards in an actual "<form>" element
628 * @param $html String HTML contents to wrap.
629 * @return String wrapped HTML.
630 */
631 function wrapForm( $html ) {
632
633 # Include a <fieldset> wrapper for style, if requested.
634 if ( $this->mWrapperLegend !== false ) {
635 $html = Xml::fieldset( $this->mWrapperLegend, $html );
636 }
637 # Use multipart/form-data
638 $encType = $this->mUseMultipart
639 ? 'multipart/form-data'
640 : 'application/x-www-form-urlencoded';
641 # Attributes
642 $attribs = array(
643 'action' => $this->mAction === false ? $this->getTitle()->getFullURL() : $this->mAction,
644 'method' => $this->mMethod,
645 'class' => 'visualClear',
646 'enctype' => $encType,
647 );
648 if ( !empty( $this->mId ) ) {
649 $attribs['id'] = $this->mId;
650 }
651
652 return Html::rawElement( 'form', $attribs, $html );
653 }
654
655 /**
656 * Get the hidden fields that should go inside the form.
657 * @return String HTML.
658 */
659 function getHiddenFields() {
660 global $wgArticlePath;
661
662 $html = '';
663 if ( $this->getMethod() == 'post' ) {
664 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
665 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
666 }
667
668 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
669 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
670 }
671
672 foreach ( $this->mHiddenFields as $data ) {
673 list( $value, $attribs ) = $data;
674 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
675 }
676
677 return $html;
678 }
679
680 /**
681 * Get the submit and (potentially) reset buttons.
682 * @return String HTML.
683 */
684 function getButtons() {
685 $html = '';
686 $attribs = array();
687
688 if ( isset( $this->mSubmitID ) ) {
689 $attribs['id'] = $this->mSubmitID;
690 }
691
692 if ( isset( $this->mSubmitName ) ) {
693 $attribs['name'] = $this->mSubmitName;
694 }
695
696 if ( isset( $this->mSubmitTooltip ) ) {
697 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
698 }
699
700 $attribs['class'] = 'mw-htmlform-submit';
701
702 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
703
704 if ( $this->mShowReset ) {
705 $html .= Html::element(
706 'input',
707 array(
708 'type' => 'reset',
709 'value' => $this->msg( 'htmlform-reset' )->text()
710 )
711 ) . "\n";
712 }
713
714 foreach ( $this->mButtons as $button ) {
715 $attrs = array(
716 'type' => 'submit',
717 'name' => $button['name'],
718 'value' => $button['value']
719 );
720
721 if ( $button['attribs'] ) {
722 $attrs += $button['attribs'];
723 }
724
725 if ( isset( $button['id'] ) ) {
726 $attrs['id'] = $button['id'];
727 }
728
729 $html .= Html::element( 'input', $attrs );
730 }
731
732 return $html;
733 }
734
735 /**
736 * Get the whole body of the form.
737 * @return String
738 */
739 function getBody() {
740 return $this->displaySection( $this->mFieldTree );
741 }
742
743 /**
744 * Format and display an error message stack.
745 * @param $errors String|Array|Status
746 * @return String
747 */
748 function getErrors( $errors ) {
749 if ( $errors instanceof Status ) {
750 if ( $errors->isOK() ) {
751 $errorstr = '';
752 } else {
753 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
754 }
755 } elseif ( is_array( $errors ) ) {
756 $errorstr = $this->formatErrors( $errors );
757 } else {
758 $errorstr = $errors;
759 }
760
761 return $errorstr
762 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
763 : '';
764 }
765
766 /**
767 * Format a stack of error messages into a single HTML string
768 * @param $errors Array of message keys/values
769 * @return String HTML, a "<ul>" list of errors
770 */
771 public static function formatErrors( $errors ) {
772 $errorstr = '';
773
774 foreach ( $errors as $error ) {
775 if ( is_array( $error ) ) {
776 $msg = array_shift( $error );
777 } else {
778 $msg = $error;
779 $error = array();
780 }
781
782 $errorstr .= Html::rawElement(
783 'li',
784 array(),
785 wfMessage( $msg, $error )->parse()
786 );
787 }
788
789 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
790
791 return $errorstr;
792 }
793
794 /**
795 * Set the text for the submit button
796 * @param $t String plaintext.
797 * @return HTMLForm $this for chaining calls (since 1.20)
798 */
799 function setSubmitText( $t ) {
800 $this->mSubmitText = $t;
801 return $this;
802 }
803
804 /**
805 * Set the text for the submit button to a message
806 * @since 1.19
807 * @param $msg String message key
808 * @return HTMLForm $this for chaining calls (since 1.20)
809 */
810 public function setSubmitTextMsg( $msg ) {
811 $this->setSubmitText( $this->msg( $msg )->text() );
812 return $this;
813 }
814
815 /**
816 * Get the text for the submit button, either customised or a default.
817 * @return string
818 */
819 function getSubmitText() {
820 return $this->mSubmitText
821 ? $this->mSubmitText
822 : $this->msg( 'htmlform-submit' )->text();
823 }
824
825 /**
826 * @param $name String Submit button name
827 * @return HTMLForm $this for chaining calls (since 1.20)
828 */
829 public function setSubmitName( $name ) {
830 $this->mSubmitName = $name;
831 return $this;
832 }
833
834 /**
835 * @param $name String Tooltip for the submit button
836 * @return HTMLForm $this for chaining calls (since 1.20)
837 */
838 public function setSubmitTooltip( $name ) {
839 $this->mSubmitTooltip = $name;
840 return $this;
841 }
842
843 /**
844 * Set the id for the submit button.
845 * @param $t String.
846 * @todo FIXME: Integrity of $t is *not* validated
847 * @return HTMLForm $this for chaining calls (since 1.20)
848 */
849 function setSubmitID( $t ) {
850 $this->mSubmitID = $t;
851 return $this;
852 }
853
854 /**
855 * @param $id String DOM id for the form
856 * @return HTMLForm $this for chaining calls (since 1.20)
857 */
858 public function setId( $id ) {
859 $this->mId = $id;
860 return $this;
861 }
862 /**
863 * Prompt the whole form to be wrapped in a "<fieldset>", with
864 * this text as its "<legend>" element.
865 * @param $legend String HTML to go inside the "<legend>" element.
866 * Will be escaped
867 * @return HTMLForm $this for chaining calls (since 1.20)
868 */
869 public function setWrapperLegend( $legend ) {
870 $this->mWrapperLegend = $legend;
871 return $this;
872 }
873
874 /**
875 * Prompt the whole form to be wrapped in a "<fieldset>", with
876 * this message as its "<legend>" element.
877 * @since 1.19
878 * @param $msg String message key
879 * @return HTMLForm $this for chaining calls (since 1.20)
880 */
881 public function setWrapperLegendMsg( $msg ) {
882 $this->setWrapperLegend( $this->msg( $msg )->text() );
883 return $this;
884 }
885
886 /**
887 * Set the prefix for various default messages
888 * @todo currently only used for the "<fieldset>" legend on forms
889 * with multiple sections; should be used elsewhre?
890 * @param $p String
891 * @return HTMLForm $this for chaining calls (since 1.20)
892 */
893 function setMessagePrefix( $p ) {
894 $this->mMessagePrefix = $p;
895 return $this;
896 }
897
898 /**
899 * Set the title for form submission
900 * @param $t Title of page the form is on/should be posted to
901 * @return HTMLForm $this for chaining calls (since 1.20)
902 */
903 function setTitle( $t ) {
904 $this->mTitle = $t;
905 return $this;
906 }
907
908 /**
909 * Get the title
910 * @return Title
911 */
912 function getTitle() {
913 return $this->mTitle === false
914 ? $this->getContext()->getTitle()
915 : $this->mTitle;
916 }
917
918 /**
919 * Set the method used to submit the form
920 * @param $method String
921 * @return HTMLForm $this for chaining calls (since 1.20)
922 */
923 public function setMethod( $method = 'post' ) {
924 $this->mMethod = $method;
925 return $this;
926 }
927
928 public function getMethod() {
929 return $this->mMethod;
930 }
931
932 /**
933 * @todo Document
934 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
935 * @param $sectionName string ID attribute of the "<table>" tag for this section, ignored if empty
936 * @param $fieldsetIDPrefix string ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
937 * @return String
938 */
939 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
940 $displayFormat = $this->getDisplayFormat();
941
942 $html = '';
943 $subsectionHtml = '';
944 $hasLabel = false;
945
946 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ? 'getTableRow' : 'get' . ucfirst( $displayFormat );
947
948 foreach ( $fields as $key => $value ) {
949 if ( $value instanceof HTMLFormField ) {
950 $v = empty( $value->mParams['nodata'] )
951 ? $this->mFieldData[$key]
952 : $value->getDefault();
953 $html .= $value->$getFieldHtmlMethod( $v );
954
955 $labelValue = trim( $value->getLabel() );
956 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
957 $hasLabel = true;
958 }
959 } elseif ( is_array( $value ) ) {
960 $section = $this->displaySection( $value, $key, "$fieldsetIDPrefix$key-" );
961 $legend = $this->getLegend( $key );
962 if ( isset( $this->mSectionHeaders[$key] ) ) {
963 $section = $this->mSectionHeaders[$key] . $section;
964 }
965 if ( isset( $this->mSectionFooters[$key] ) ) {
966 $section .= $this->mSectionFooters[$key];
967 }
968 $attributes = array();
969 if ( $fieldsetIDPrefix ) {
970 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
971 }
972 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
973 }
974 }
975
976 if ( $displayFormat !== 'raw' ) {
977 $classes = array();
978
979 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
980 $classes[] = 'mw-htmlform-nolabel';
981 }
982
983 $attribs = array(
984 'class' => implode( ' ', $classes ),
985 );
986
987 if ( $sectionName ) {
988 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
989 }
990
991 if ( $displayFormat === 'table' ) {
992 $html = Html::rawElement( 'table', $attribs,
993 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
994 } elseif ( $displayFormat === 'div' ) {
995 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
996 }
997 }
998
999 if ( $this->mSubSectionBeforeFields ) {
1000 return $subsectionHtml . "\n" . $html;
1001 } else {
1002 return $html . "\n" . $subsectionHtml;
1003 }
1004 }
1005
1006 /**
1007 * Construct the form fields from the Descriptor array
1008 */
1009 function loadData() {
1010 $fieldData = array();
1011
1012 foreach ( $this->mFlatFields as $fieldname => $field ) {
1013 if ( !empty( $field->mParams['nodata'] ) ) {
1014 continue;
1015 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1016 $fieldData[$fieldname] = $field->getDefault();
1017 } else {
1018 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1019 }
1020 }
1021
1022 # Filter data.
1023 foreach ( $fieldData as $name => &$value ) {
1024 $field = $this->mFlatFields[$name];
1025 $value = $field->filter( $value, $this->mFlatFields );
1026 }
1027
1028 $this->mFieldData = $fieldData;
1029 }
1030
1031 /**
1032 * Stop a reset button being shown for this form
1033 * @param $suppressReset Bool set to false to re-enable the
1034 * button again
1035 * @return HTMLForm $this for chaining calls (since 1.20)
1036 */
1037 function suppressReset( $suppressReset = true ) {
1038 $this->mShowReset = !$suppressReset;
1039 return $this;
1040 }
1041
1042 /**
1043 * Overload this if you want to apply special filtration routines
1044 * to the form as a whole, after it's submitted but before it's
1045 * processed.
1046 * @param $data
1047 * @return
1048 */
1049 function filterDataForSubmit( $data ) {
1050 return $data;
1051 }
1052
1053 /**
1054 * Get a string to go in the "<legend>" of a section fieldset.
1055 * Override this if you want something more complicated.
1056 * @param $key String
1057 * @return String
1058 */
1059 public function getLegend( $key ) {
1060 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1061 }
1062
1063 /**
1064 * Set the value for the action attribute of the form.
1065 * When set to false (which is the default state), the set title is used.
1066 *
1067 * @since 1.19
1068 *
1069 * @param string|bool $action
1070 * @return HTMLForm $this for chaining calls (since 1.20)
1071 */
1072 public function setAction( $action ) {
1073 $this->mAction = $action;
1074 return $this;
1075 }
1076
1077 }
1078
1079 /**
1080 * The parent class to generate form fields. Any field type should
1081 * be a subclass of this.
1082 */
1083 abstract class HTMLFormField {
1084
1085 protected $mValidationCallback;
1086 protected $mFilterCallback;
1087 protected $mName;
1088 public $mParams;
1089 protected $mLabel; # String label. Set on construction
1090 protected $mID;
1091 protected $mClass = '';
1092 protected $mDefault;
1093
1094 /**
1095 * @var HTMLForm
1096 */
1097 public $mParent;
1098
1099 /**
1100 * This function must be implemented to return the HTML to generate
1101 * the input object itself. It should not implement the surrounding
1102 * table cells/rows, or labels/help messages.
1103 * @param $value String the value to set the input to; eg a default
1104 * text for a text input.
1105 * @return String valid HTML.
1106 */
1107 abstract function getInputHTML( $value );
1108
1109 /**
1110 * Get a translated interface message
1111 *
1112 * This is a wrapper arround $this->mParent->msg() if $this->mParent is set
1113 * and wfMessage() otherwise.
1114 *
1115 * Parameters are the same as wfMessage().
1116 *
1117 * @return Message object
1118 */
1119 function msg() {
1120 $args = func_get_args();
1121
1122 if ( $this->mParent ) {
1123 $callback = array( $this->mParent, 'msg' );
1124 } else {
1125 $callback = 'wfMessage';
1126 }
1127
1128 return call_user_func_array( $callback, $args );
1129 }
1130
1131 /**
1132 * Override this function to add specific validation checks on the
1133 * field input. Don't forget to call parent::validate() to ensure
1134 * that the user-defined callback mValidationCallback is still run
1135 * @param $value String the value the field was submitted with
1136 * @param $alldata Array the data collected from the form
1137 * @return Mixed Bool true on success, or String error to display.
1138 */
1139 function validate( $value, $alldata ) {
1140 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1141 return $this->msg( 'htmlform-required' )->parse();
1142 }
1143
1144 if ( isset( $this->mValidationCallback ) ) {
1145 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1146 }
1147
1148 return true;
1149 }
1150
1151 function filter( $value, $alldata ) {
1152 if ( isset( $this->mFilterCallback ) ) {
1153 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1154 }
1155
1156 return $value;
1157 }
1158
1159 /**
1160 * Should this field have a label, or is there no input element with the
1161 * appropriate id for the label to point to?
1162 *
1163 * @return bool True to output a label, false to suppress
1164 */
1165 protected function needsLabel() {
1166 return true;
1167 }
1168
1169 /**
1170 * Get the value that this input has been set to from a posted form,
1171 * or the input's default value if it has not been set.
1172 * @param $request WebRequest
1173 * @return String the value
1174 */
1175 function loadDataFromRequest( $request ) {
1176 if ( $request->getCheck( $this->mName ) ) {
1177 return $request->getText( $this->mName );
1178 } else {
1179 return $this->getDefault();
1180 }
1181 }
1182
1183 /**
1184 * Initialise the object
1185 * @param $params array Associative Array. See HTMLForm doc for syntax.
1186 * @throws MWException
1187 */
1188 function __construct( $params ) {
1189 $this->mParams = $params;
1190
1191 # Generate the label from a message, if possible
1192 if ( isset( $params['label-message'] ) ) {
1193 $msgInfo = $params['label-message'];
1194
1195 if ( is_array( $msgInfo ) ) {
1196 $msg = array_shift( $msgInfo );
1197 } else {
1198 $msg = $msgInfo;
1199 $msgInfo = array();
1200 }
1201
1202 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1203 } elseif ( isset( $params['label'] ) ) {
1204 $this->mLabel = $params['label'];
1205 }
1206
1207 $this->mName = "wp{$params['fieldname']}";
1208 if ( isset( $params['name'] ) ) {
1209 $this->mName = $params['name'];
1210 }
1211
1212 $validName = Sanitizer::escapeId( $this->mName );
1213 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1214 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1215 }
1216
1217 $this->mID = "mw-input-{$this->mName}";
1218
1219 if ( isset( $params['default'] ) ) {
1220 $this->mDefault = $params['default'];
1221 }
1222
1223 if ( isset( $params['id'] ) ) {
1224 $id = $params['id'];
1225 $validId = Sanitizer::escapeId( $id );
1226
1227 if ( $id != $validId ) {
1228 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1229 }
1230
1231 $this->mID = $id;
1232 }
1233
1234 if ( isset( $params['cssclass'] ) ) {
1235 $this->mClass = $params['cssclass'];
1236 }
1237
1238 if ( isset( $params['validation-callback'] ) ) {
1239 $this->mValidationCallback = $params['validation-callback'];
1240 }
1241
1242 if ( isset( $params['filter-callback'] ) ) {
1243 $this->mFilterCallback = $params['filter-callback'];
1244 }
1245
1246 if ( isset( $params['flatlist'] ) ) {
1247 $this->mClass .= ' mw-htmlform-flatlist';
1248 }
1249 }
1250
1251 /**
1252 * Get the complete table row for the input, including help text,
1253 * labels, and whatever.
1254 * @param $value String the value to set the input to.
1255 * @return String complete HTML table row.
1256 */
1257 function getTableRow( $value ) {
1258 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1259 $inputHtml = $this->getInputHTML( $value );
1260 $fieldType = get_class( $this );
1261 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1262 $cellAttributes = array();
1263
1264 if ( !empty( $this->mParams['vertical-label'] ) ) {
1265 $cellAttributes['colspan'] = 2;
1266 $verticalLabel = true;
1267 } else {
1268 $verticalLabel = false;
1269 }
1270
1271 $label = $this->getLabelHtml( $cellAttributes );
1272
1273 $field = Html::rawElement(
1274 'td',
1275 array( 'class' => 'mw-input' ) + $cellAttributes,
1276 $inputHtml . "\n$errors"
1277 );
1278
1279 if ( $verticalLabel ) {
1280 $html = Html::rawElement( 'tr',
1281 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1282 $html .= Html::rawElement( 'tr',
1283 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1284 $field );
1285 } else {
1286 $html = Html::rawElement( 'tr',
1287 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1288 $label . $field );
1289 }
1290
1291 return $html . $helptext;
1292 }
1293
1294 /**
1295 * Get the complete div for the input, including help text,
1296 * labels, and whatever.
1297 * @since 1.20
1298 * @param $value String the value to set the input to.
1299 * @return String complete HTML table row.
1300 */
1301 public function getDiv( $value ) {
1302 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1303 $inputHtml = $this->getInputHTML( $value );
1304 $fieldType = get_class( $this );
1305 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1306 $cellAttributes = array();
1307 $label = $this->getLabelHtml( $cellAttributes );
1308
1309 $field = Html::rawElement(
1310 'div',
1311 array( 'class' => 'mw-input' ) + $cellAttributes,
1312 $inputHtml . "\n$errors"
1313 );
1314 $html = Html::rawElement( 'div',
1315 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1316 $label . $field );
1317 $html .= $helptext;
1318 return $html;
1319 }
1320
1321 /**
1322 * Get the complete raw fields for the input, including help text,
1323 * labels, and whatever.
1324 * @since 1.20
1325 * @param $value String the value to set the input to.
1326 * @return String complete HTML table row.
1327 */
1328 public function getRaw( $value ) {
1329 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1330 $inputHtml = $this->getInputHTML( $value );
1331 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1332 $cellAttributes = array();
1333 $label = $this->getLabelHtml( $cellAttributes );
1334
1335 $html = "\n$errors";
1336 $html .= $label;
1337 $html .= $inputHtml;
1338 $html .= $helptext;
1339 return $html;
1340 }
1341
1342 /**
1343 * Generate help text HTML in table format
1344 * @since 1.20
1345 * @param $helptext String|null
1346 * @return String
1347 */
1348 public function getHelpTextHtmlTable( $helptext ) {
1349 if ( is_null( $helptext ) ) {
1350 return '';
1351 }
1352
1353 $row = Html::rawElement(
1354 'td',
1355 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1356 $helptext
1357 );
1358 $row = Html::rawElement( 'tr', array(), $row );
1359 return $row;
1360 }
1361
1362 /**
1363 * Generate help text HTML in div format
1364 * @since 1.20
1365 * @param $helptext String|null
1366 * @return String
1367 */
1368 public function getHelpTextHtmlDiv( $helptext ) {
1369 if ( is_null( $helptext ) ) {
1370 return '';
1371 }
1372
1373 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1374 return $div;
1375 }
1376
1377 /**
1378 * Generate help text HTML formatted for raw output
1379 * @since 1.20
1380 * @param $helptext String|null
1381 * @return String
1382 */
1383 public function getHelpTextHtmlRaw( $helptext ) {
1384 return $this->getHelpTextHtmlDiv( $helptext );
1385 }
1386
1387 /**
1388 * Determine the help text to display
1389 * @since 1.20
1390 * @return String
1391 */
1392 public function getHelpText() {
1393 $helptext = null;
1394
1395 if ( isset( $this->mParams['help-message'] ) ) {
1396 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1397 }
1398
1399 if ( isset( $this->mParams['help-messages'] ) ) {
1400 foreach ( $this->mParams['help-messages'] as $name ) {
1401 $helpMessage = (array)$name;
1402 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1403
1404 if ( $msg->exists() ) {
1405 if ( is_null( $helptext ) ) {
1406 $helptext = '';
1407 } else {
1408 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1409 }
1410 $helptext .= $msg->parse(); // Append message
1411 }
1412 }
1413 }
1414 elseif ( isset( $this->mParams['help'] ) ) {
1415 $helptext = $this->mParams['help'];
1416 }
1417 return $helptext;
1418 }
1419
1420 /**
1421 * Determine form errors to display and their classes
1422 * @since 1.20
1423 * @param $value String the value of the input
1424 * @return Array
1425 */
1426 public function getErrorsAndErrorClass( $value ) {
1427 $errors = $this->validate( $value, $this->mParent->mFieldData );
1428
1429 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1430 $errors = '';
1431 $errorClass = '';
1432 } else {
1433 $errors = self::formatErrors( $errors );
1434 $errorClass = 'mw-htmlform-invalid-input';
1435 }
1436 return array( $errors, $errorClass );
1437 }
1438
1439 function getLabel() {
1440 return $this->mLabel;
1441 }
1442
1443 function getLabelHtml( $cellAttributes = array() ) {
1444 # Don't output a for= attribute for labels with no associated input.
1445 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1446 $for = array();
1447
1448 if ( $this->needsLabel() ) {
1449 $for['for'] = $this->mID;
1450 }
1451
1452 $displayFormat = $this->mParent->getDisplayFormat();
1453 $labelElement = Html::rawElement( 'label', $for, $this->getLabel() );
1454
1455 if ( $displayFormat == 'table' ) {
1456 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1457 Html::rawElement( 'label', $for, $this->getLabel() )
1458 );
1459 } elseif ( $displayFormat == 'div' ) {
1460 return Html::rawElement( 'div', array( 'class' => 'mw-label' ) + $cellAttributes,
1461 Html::rawElement( 'label', $for, $this->getLabel() )
1462 );
1463 } else {
1464 return $labelElement;
1465 }
1466 }
1467
1468 function getDefault() {
1469 if ( isset( $this->mDefault ) ) {
1470 return $this->mDefault;
1471 } else {
1472 return null;
1473 }
1474 }
1475
1476 /**
1477 * Returns the attributes required for the tooltip and accesskey.
1478 *
1479 * @return array Attributes
1480 */
1481 public function getTooltipAndAccessKey() {
1482 if ( empty( $this->mParams['tooltip'] ) ) {
1483 return array();
1484 }
1485 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1486 }
1487
1488 /**
1489 * flatten an array of options to a single array, for instance,
1490 * a set of "<options>" inside "<optgroups>".
1491 * @param $options array Associative Array with values either Strings
1492 * or Arrays
1493 * @return Array flattened input
1494 */
1495 public static function flattenOptions( $options ) {
1496 $flatOpts = array();
1497
1498 foreach ( $options as $value ) {
1499 if ( is_array( $value ) ) {
1500 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1501 } else {
1502 $flatOpts[] = $value;
1503 }
1504 }
1505
1506 return $flatOpts;
1507 }
1508
1509 /**
1510 * Formats one or more errors as accepted by field validation-callback.
1511 * @param $errors String|Message|Array of strings or Message instances
1512 * @return String html
1513 * @since 1.18
1514 */
1515 protected static function formatErrors( $errors ) {
1516 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1517 $errors = array_shift( $errors );
1518 }
1519
1520 if ( is_array( $errors ) ) {
1521 $lines = array();
1522 foreach ( $errors as $error ) {
1523 if ( $error instanceof Message ) {
1524 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1525 } else {
1526 $lines[] = Html::rawElement( 'li', array(), $error );
1527 }
1528 }
1529 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1530 } else {
1531 if ( $errors instanceof Message ) {
1532 $errors = $errors->parse();
1533 }
1534 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1535 }
1536 }
1537 }
1538
1539 class HTMLTextField extends HTMLFormField {
1540 function getSize() {
1541 return isset( $this->mParams['size'] )
1542 ? $this->mParams['size']
1543 : 45;
1544 }
1545
1546 function getInputHTML( $value ) {
1547 $attribs = array(
1548 'id' => $this->mID,
1549 'name' => $this->mName,
1550 'size' => $this->getSize(),
1551 'value' => $value,
1552 ) + $this->getTooltipAndAccessKey();
1553
1554 if ( $this->mClass !== '' ) {
1555 $attribs['class'] = $this->mClass;
1556 }
1557
1558 if ( !empty( $this->mParams['disabled'] ) ) {
1559 $attribs['disabled'] = 'disabled';
1560 }
1561
1562 # TODO: Enforce pattern, step, required, readonly on the server side as
1563 # well
1564 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1565 'placeholder', 'list', 'maxlength' );
1566 foreach ( $allowedParams as $param ) {
1567 if ( isset( $this->mParams[$param] ) ) {
1568 $attribs[$param] = $this->mParams[$param];
1569 }
1570 }
1571
1572 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1573 if ( isset( $this->mParams[$param] ) ) {
1574 $attribs[$param] = '';
1575 }
1576 }
1577
1578 # Implement tiny differences between some field variants
1579 # here, rather than creating a new class for each one which
1580 # is essentially just a clone of this one.
1581 if ( isset( $this->mParams['type'] ) ) {
1582 switch ( $this->mParams['type'] ) {
1583 case 'email':
1584 $attribs['type'] = 'email';
1585 break;
1586 case 'int':
1587 $attribs['type'] = 'number';
1588 break;
1589 case 'float':
1590 $attribs['type'] = 'number';
1591 $attribs['step'] = 'any';
1592 break;
1593 # Pass through
1594 case 'password':
1595 case 'file':
1596 $attribs['type'] = $this->mParams['type'];
1597 break;
1598 }
1599 }
1600
1601 return Html::element( 'input', $attribs );
1602 }
1603 }
1604 class HTMLTextAreaField extends HTMLFormField {
1605 function getCols() {
1606 return isset( $this->mParams['cols'] )
1607 ? $this->mParams['cols']
1608 : 80;
1609 }
1610
1611 function getRows() {
1612 return isset( $this->mParams['rows'] )
1613 ? $this->mParams['rows']
1614 : 25;
1615 }
1616
1617 function getInputHTML( $value ) {
1618 $attribs = array(
1619 'id' => $this->mID,
1620 'name' => $this->mName,
1621 'cols' => $this->getCols(),
1622 'rows' => $this->getRows(),
1623 ) + $this->getTooltipAndAccessKey();
1624
1625 if ( $this->mClass !== '' ) {
1626 $attribs['class'] = $this->mClass;
1627 }
1628
1629 if ( !empty( $this->mParams['disabled'] ) ) {
1630 $attribs['disabled'] = 'disabled';
1631 }
1632
1633 if ( !empty( $this->mParams['readonly'] ) ) {
1634 $attribs['readonly'] = 'readonly';
1635 }
1636
1637 if ( isset( $this->mParams['placeholder'] ) ) {
1638 $attribs['placeholder'] = $this->mParams['placeholder'];
1639 }
1640
1641 foreach ( array( 'required', 'autofocus' ) as $param ) {
1642 if ( isset( $this->mParams[$param] ) ) {
1643 $attribs[$param] = '';
1644 }
1645 }
1646
1647 return Html::element( 'textarea', $attribs, $value );
1648 }
1649 }
1650
1651 /**
1652 * A field that will contain a numeric value
1653 */
1654 class HTMLFloatField extends HTMLTextField {
1655 function getSize() {
1656 return isset( $this->mParams['size'] )
1657 ? $this->mParams['size']
1658 : 20;
1659 }
1660
1661 function validate( $value, $alldata ) {
1662 $p = parent::validate( $value, $alldata );
1663
1664 if ( $p !== true ) {
1665 return $p;
1666 }
1667
1668 $value = trim( $value );
1669
1670 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1671 # with the addition that a leading '+' sign is ok.
1672 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1673 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1674 }
1675
1676 # The "int" part of these message names is rather confusing.
1677 # They make equal sense for all numbers.
1678 if ( isset( $this->mParams['min'] ) ) {
1679 $min = $this->mParams['min'];
1680
1681 if ( $min > $value ) {
1682 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1683 }
1684 }
1685
1686 if ( isset( $this->mParams['max'] ) ) {
1687 $max = $this->mParams['max'];
1688
1689 if ( $max < $value ) {
1690 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1691 }
1692 }
1693
1694 return true;
1695 }
1696 }
1697
1698 /**
1699 * A field that must contain a number
1700 */
1701 class HTMLIntField extends HTMLFloatField {
1702 function validate( $value, $alldata ) {
1703 $p = parent::validate( $value, $alldata );
1704
1705 if ( $p !== true ) {
1706 return $p;
1707 }
1708
1709 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1710 # with the addition that a leading '+' sign is ok. Note that leading zeros
1711 # are fine, and will be left in the input, which is useful for things like
1712 # phone numbers when you know that they are integers (the HTML5 type=tel
1713 # input does not require its value to be numeric). If you want a tidier
1714 # value to, eg, save in the DB, clean it up with intval().
1715 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1716 ) {
1717 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1718 }
1719
1720 return true;
1721 }
1722 }
1723
1724 /**
1725 * A checkbox field
1726 */
1727 class HTMLCheckField extends HTMLFormField {
1728 function getInputHTML( $value ) {
1729 if ( !empty( $this->mParams['invert'] ) ) {
1730 $value = !$value;
1731 }
1732
1733 $attr = $this->getTooltipAndAccessKey();
1734 $attr['id'] = $this->mID;
1735
1736 if ( !empty( $this->mParams['disabled'] ) ) {
1737 $attr['disabled'] = 'disabled';
1738 }
1739
1740 if ( $this->mClass !== '' ) {
1741 $attr['class'] = $this->mClass;
1742 }
1743
1744 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1745 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1746 }
1747
1748 /**
1749 * For a checkbox, the label goes on the right hand side, and is
1750 * added in getInputHTML(), rather than HTMLFormField::getRow()
1751 * @return String
1752 */
1753 function getLabel() {
1754 return '&#160;';
1755 }
1756
1757 /**
1758 * @param $request WebRequest
1759 * @return String
1760 */
1761 function loadDataFromRequest( $request ) {
1762 $invert = false;
1763 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1764 $invert = true;
1765 }
1766
1767 // GetCheck won't work like we want for checks.
1768 // Fetch the value in either one of the two following case:
1769 // - we have a valid token (form got posted or GET forged by the user)
1770 // - checkbox name has a value (false or true), ie is not null
1771 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1772 // XOR has the following truth table, which is what we want
1773 // INVERT VALUE | OUTPUT
1774 // true true | false
1775 // false true | true
1776 // false false | false
1777 // true false | true
1778 return $request->getBool( $this->mName ) xor $invert;
1779 } else {
1780 return $this->getDefault();
1781 }
1782 }
1783 }
1784
1785 /**
1786 * A checkbox matrix
1787 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1788 * options, uses an array of rows and an array of columns to dynamically
1789 * construct a matrix of options.
1790 */
1791 class HTMLCheckMatrix extends HTMLFormField {
1792
1793 function validate( $value, $alldata ) {
1794 $rows = $this->mParams['rows'];
1795 $columns = $this->mParams['columns'];
1796
1797 // Make sure user-defined validation callback is run
1798 $p = parent::validate( $value, $alldata );
1799 if ( $p !== true ) {
1800 return $p;
1801 }
1802
1803 // Make sure submitted value is an array
1804 if ( !is_array( $value ) ) {
1805 return false;
1806 }
1807
1808 // If all options are valid, array_intersect of the valid options
1809 // and the provided options will return the provided options.
1810 $validOptions = array();
1811 foreach ( $rows as $rowTag ) {
1812 foreach ( $columns as $columnTag ) {
1813 $validOptions[] = $columnTag . '-' . $rowTag;
1814 }
1815 }
1816 $validValues = array_intersect( $value, $validOptions );
1817 if ( count( $validValues ) == count( $value ) ) {
1818 return true;
1819 } else {
1820 return $this->msg( 'htmlform-select-badoption' )->parse();
1821 }
1822 }
1823
1824 /**
1825 * Build a table containing a matrix of checkbox options.
1826 * The value of each option is a combination of the row tag and column tag.
1827 * mParams['rows'] is an array with row labels as keys and row tags as values.
1828 * mParams['columns'] is an array with column labels as keys and column tags as values.
1829 * @param $value Array of the options that should be checked
1830 * @return String
1831 */
1832 function getInputHTML( $value ) {
1833 $html = '';
1834 $tableContents = '';
1835 $attribs = array();
1836 $rows = $this->mParams['rows'];
1837 $columns = $this->mParams['columns'];
1838
1839 // If the disabled param is set, disable all the options
1840 if ( !empty( $this->mParams['disabled'] ) ) {
1841 $attribs['disabled'] = 'disabled';
1842 }
1843
1844 // Build the column headers
1845 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
1846 foreach ( $columns as $columnLabel => $columnTag ) {
1847 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
1848 }
1849 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
1850
1851 // Build the options matrix
1852 foreach ( $rows as $rowLabel => $rowTag ) {
1853 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
1854 foreach ( $columns as $columnTag ) {
1855 // Knock out any options that are not wanted
1856 if ( isset( $this->mParams['remove-options'] )
1857 && in_array( "$columnTag-$rowTag", $this->mParams['remove-options'] ) )
1858 {
1859 $rowContents .= Html::rawElement( 'td', array(), '&#160;' );
1860 } else {
1861 // Construct the checkbox
1862 $thisAttribs = array(
1863 'id' => "{$this->mID}-$columnTag-$rowTag",
1864 'value' => $columnTag . '-' . $rowTag
1865 );
1866 $checkbox = Xml::check(
1867 $this->mName . '[]',
1868 in_array( $columnTag . '-' . $rowTag, (array)$value, true ),
1869 $attribs + $thisAttribs );
1870 $rowContents .= Html::rawElement( 'td', array(), $checkbox );
1871 }
1872 }
1873 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
1874 }
1875
1876 // Put it all in a table
1877 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
1878 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
1879
1880 return $html;
1881 }
1882
1883 /**
1884 * Get the complete table row for the input, including help text,
1885 * labels, and whatever.
1886 * We override this function since the label should always be on a separate
1887 * line above the options in the case of a checkbox matrix, i.e. it's always
1888 * a "vertical-label".
1889 * @param $value String the value to set the input to
1890 * @return String complete HTML table row
1891 */
1892 function getTableRow( $value ) {
1893 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1894 $inputHtml = $this->getInputHTML( $value );
1895 $fieldType = get_class( $this );
1896 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1897 $cellAttributes = array( 'colspan' => 2 );
1898
1899 $label = $this->getLabelHtml( $cellAttributes );
1900
1901 $field = Html::rawElement(
1902 'td',
1903 array( 'class' => 'mw-input' ) + $cellAttributes,
1904 $inputHtml . "\n$errors"
1905 );
1906
1907 $html = Html::rawElement( 'tr',
1908 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1909 $html .= Html::rawElement( 'tr',
1910 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1911 $field );
1912
1913 return $html . $helptext;
1914 }
1915
1916 /**
1917 * @param $request WebRequest
1918 * @return Array
1919 */
1920 function loadDataFromRequest( $request ) {
1921 if ( $this->mParent->getMethod() == 'post' ) {
1922 if ( $request->wasPosted() ) {
1923 // Checkboxes are not added to the request arrays if they're not checked,
1924 // so it's perfectly possible for there not to be an entry at all
1925 return $request->getArray( $this->mName, array() );
1926 } else {
1927 // That's ok, the user has not yet submitted the form, so show the defaults
1928 return $this->getDefault();
1929 }
1930 } else {
1931 // This is the impossible case: if we look at $_GET and see no data for our
1932 // field, is it because the user has not yet submitted the form, or that they
1933 // have submitted it with all the options unchecked. We will have to assume the
1934 // latter, which basically means that you can't specify 'positive' defaults
1935 // for GET forms.
1936 return $request->getArray( $this->mName, array() );
1937 }
1938 }
1939
1940 function getDefault() {
1941 if ( isset( $this->mDefault ) ) {
1942 return $this->mDefault;
1943 } else {
1944 return array();
1945 }
1946 }
1947 }
1948
1949 /**
1950 * A select dropdown field. Basically a wrapper for Xmlselect class
1951 */
1952 class HTMLSelectField extends HTMLFormField {
1953 function validate( $value, $alldata ) {
1954 $p = parent::validate( $value, $alldata );
1955
1956 if ( $p !== true ) {
1957 return $p;
1958 }
1959
1960 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1961
1962 if ( in_array( $value, $validOptions ) )
1963 return true;
1964 else
1965 return $this->msg( 'htmlform-select-badoption' )->parse();
1966 }
1967
1968 function getInputHTML( $value ) {
1969 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1970
1971 # If one of the options' 'name' is int(0), it is automatically selected.
1972 # because PHP sucks and thinks int(0) == 'some string'.
1973 # Working around this by forcing all of them to strings.
1974 foreach ( $this->mParams['options'] as &$opt ) {
1975 if ( is_int( $opt ) ) {
1976 $opt = strval( $opt );
1977 }
1978 }
1979 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1980
1981 if ( !empty( $this->mParams['disabled'] ) ) {
1982 $select->setAttribute( 'disabled', 'disabled' );
1983 }
1984
1985 if ( $this->mClass !== '' ) {
1986 $select->setAttribute( 'class', $this->mClass );
1987 }
1988
1989 $select->addOptions( $this->mParams['options'] );
1990
1991 return $select->getHTML();
1992 }
1993 }
1994
1995 /**
1996 * Select dropdown field, with an additional "other" textbox.
1997 */
1998 class HTMLSelectOrOtherField extends HTMLTextField {
1999 static $jsAdded = false;
2000
2001 function __construct( $params ) {
2002 if ( !in_array( 'other', $params['options'], true ) ) {
2003 $msg = isset( $params['other'] ) ?
2004 $params['other'] :
2005 wfMessage( 'htmlform-selectorother-other' )->text();
2006 $params['options'][$msg] = 'other';
2007 }
2008
2009 parent::__construct( $params );
2010 }
2011
2012 static function forceToStringRecursive( $array ) {
2013 if ( is_array( $array ) ) {
2014 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2015 } else {
2016 return strval( $array );
2017 }
2018 }
2019
2020 function getInputHTML( $value ) {
2021 $valInSelect = false;
2022
2023 if ( $value !== false ) {
2024 $valInSelect = in_array(
2025 $value,
2026 HTMLFormField::flattenOptions( $this->mParams['options'] )
2027 );
2028 }
2029
2030 $selected = $valInSelect ? $value : 'other';
2031
2032 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2033
2034 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2035 $select->addOptions( $opts );
2036
2037 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2038
2039 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2040
2041 if ( !empty( $this->mParams['disabled'] ) ) {
2042 $select->setAttribute( 'disabled', 'disabled' );
2043 $tbAttribs['disabled'] = 'disabled';
2044 }
2045
2046 $select = $select->getHTML();
2047
2048 if ( isset( $this->mParams['maxlength'] ) ) {
2049 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2050 }
2051
2052 if ( $this->mClass !== '' ) {
2053 $tbAttribs['class'] = $this->mClass;
2054 }
2055
2056 $textbox = Html::input(
2057 $this->mName . '-other',
2058 $valInSelect ? '' : $value,
2059 'text',
2060 $tbAttribs
2061 );
2062
2063 return "$select<br />\n$textbox";
2064 }
2065
2066 /**
2067 * @param $request WebRequest
2068 * @return String
2069 */
2070 function loadDataFromRequest( $request ) {
2071 if ( $request->getCheck( $this->mName ) ) {
2072 $val = $request->getText( $this->mName );
2073
2074 if ( $val == 'other' ) {
2075 $val = $request->getText( $this->mName . '-other' );
2076 }
2077
2078 return $val;
2079 } else {
2080 return $this->getDefault();
2081 }
2082 }
2083 }
2084
2085 /**
2086 * Multi-select field
2087 */
2088 class HTMLMultiSelectField extends HTMLFormField {
2089
2090 function validate( $value, $alldata ) {
2091 $p = parent::validate( $value, $alldata );
2092
2093 if ( $p !== true ) {
2094 return $p;
2095 }
2096
2097 if ( !is_array( $value ) ) {
2098 return false;
2099 }
2100
2101 # If all options are valid, array_intersect of the valid options
2102 # and the provided options will return the provided options.
2103 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2104
2105 $validValues = array_intersect( $value, $validOptions );
2106 if ( count( $validValues ) == count( $value ) ) {
2107 return true;
2108 } else {
2109 return $this->msg( 'htmlform-select-badoption' )->parse();
2110 }
2111 }
2112
2113 function getInputHTML( $value ) {
2114 $html = $this->formatOptions( $this->mParams['options'], $value );
2115
2116 return $html;
2117 }
2118
2119 function formatOptions( $options, $value ) {
2120 $html = '';
2121
2122 $attribs = array();
2123
2124 if ( !empty( $this->mParams['disabled'] ) ) {
2125 $attribs['disabled'] = 'disabled';
2126 }
2127
2128 foreach ( $options as $label => $info ) {
2129 if ( is_array( $info ) ) {
2130 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2131 $html .= $this->formatOptions( $info, $value );
2132 } else {
2133 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2134
2135 $checkbox = Xml::check(
2136 $this->mName . '[]',
2137 in_array( $info, $value, true ),
2138 $attribs + $thisAttribs );
2139 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2140
2141 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2142 }
2143 }
2144
2145 return $html;
2146 }
2147
2148 /**
2149 * @param $request WebRequest
2150 * @return String
2151 */
2152 function loadDataFromRequest( $request ) {
2153 if ( $this->mParent->getMethod() == 'post' ) {
2154 if ( $request->wasPosted() ) {
2155 # Checkboxes are just not added to the request arrays if they're not checked,
2156 # so it's perfectly possible for there not to be an entry at all
2157 return $request->getArray( $this->mName, array() );
2158 } else {
2159 # That's ok, the user has not yet submitted the form, so show the defaults
2160 return $this->getDefault();
2161 }
2162 } else {
2163 # This is the impossible case: if we look at $_GET and see no data for our
2164 # field, is it because the user has not yet submitted the form, or that they
2165 # have submitted it with all the options unchecked? We will have to assume the
2166 # latter, which basically means that you can't specify 'positive' defaults
2167 # for GET forms.
2168 # @todo FIXME...
2169 return $request->getArray( $this->mName, array() );
2170 }
2171 }
2172
2173 function getDefault() {
2174 if ( isset( $this->mDefault ) ) {
2175 return $this->mDefault;
2176 } else {
2177 return array();
2178 }
2179 }
2180
2181 protected function needsLabel() {
2182 return false;
2183 }
2184 }
2185
2186 /**
2187 * Double field with a dropdown list constructed from a system message in the format
2188 * * Optgroup header
2189 * ** <option value>
2190 * * New Optgroup header
2191 * Plus a text field underneath for an additional reason. The 'value' of the field is
2192 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2193 * select dropdown.
2194 * @todo FIXME: If made 'required', only the text field should be compulsory.
2195 */
2196 class HTMLSelectAndOtherField extends HTMLSelectField {
2197
2198 function __construct( $params ) {
2199 if ( array_key_exists( 'other', $params ) ) {
2200 } elseif ( array_key_exists( 'other-message', $params ) ) {
2201 $params['other'] = wfMessage( $params['other-message'] )->plain();
2202 } else {
2203 $params['other'] = null;
2204 }
2205
2206 if ( array_key_exists( 'options', $params ) ) {
2207 # Options array already specified
2208 } elseif ( array_key_exists( 'options-message', $params ) ) {
2209 # Generate options array from a system message
2210 $params['options'] = self::parseMessage(
2211 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2212 $params['other']
2213 );
2214 } else {
2215 # Sulk
2216 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2217 }
2218 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2219
2220 parent::__construct( $params );
2221 }
2222
2223 /**
2224 * Build a drop-down box from a textual list.
2225 * @param $string String message text
2226 * @param $otherName String name of "other reason" option
2227 * @return Array
2228 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2229 */
2230 public static function parseMessage( $string, $otherName = null ) {
2231 if ( $otherName === null ) {
2232 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2233 }
2234
2235 $optgroup = false;
2236 $options = array( $otherName => 'other' );
2237
2238 foreach ( explode( "\n", $string ) as $option ) {
2239 $value = trim( $option );
2240 if ( $value == '' ) {
2241 continue;
2242 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2243 # A new group is starting...
2244 $value = trim( substr( $value, 1 ) );
2245 $optgroup = $value;
2246 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2247 # groupmember
2248 $opt = trim( substr( $value, 2 ) );
2249 if ( $optgroup === false ) {
2250 $options[$opt] = $opt;
2251 } else {
2252 $options[$optgroup][$opt] = $opt;
2253 }
2254 } else {
2255 # groupless reason list
2256 $optgroup = false;
2257 $options[$option] = $option;
2258 }
2259 }
2260
2261 return $options;
2262 }
2263
2264 function getInputHTML( $value ) {
2265 $select = parent::getInputHTML( $value[1] );
2266
2267 $textAttribs = array(
2268 'id' => $this->mID . '-other',
2269 'size' => $this->getSize(),
2270 );
2271
2272 if ( $this->mClass !== '' ) {
2273 $textAttribs['class'] = $this->mClass;
2274 }
2275
2276 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2277 if ( isset( $this->mParams[$param] ) ) {
2278 $textAttribs[$param] = '';
2279 }
2280 }
2281
2282 $textbox = Html::input(
2283 $this->mName . '-other',
2284 $value[2],
2285 'text',
2286 $textAttribs
2287 );
2288
2289 return "$select<br />\n$textbox";
2290 }
2291
2292 /**
2293 * @param $request WebRequest
2294 * @return Array("<overall message>","<select value>","<text field value>")
2295 */
2296 function loadDataFromRequest( $request ) {
2297 if ( $request->getCheck( $this->mName ) ) {
2298
2299 $list = $request->getText( $this->mName );
2300 $text = $request->getText( $this->mName . '-other' );
2301
2302 if ( $list == 'other' ) {
2303 $final = $text;
2304 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2305 # User has spoofed the select form to give an option which wasn't
2306 # in the original offer. Sulk...
2307 $final = $text;
2308 } elseif ( $text == '' ) {
2309 $final = $list;
2310 } else {
2311 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2312 }
2313
2314 } else {
2315 $final = $this->getDefault();
2316
2317 $list = 'other';
2318 $text = $final;
2319 foreach ( $this->mFlatOptions as $option ) {
2320 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2321 if ( strpos( $text, $match ) === 0 ) {
2322 $list = $option;
2323 $text = substr( $text, strlen( $match ) );
2324 break;
2325 }
2326 }
2327 }
2328 return array( $final, $list, $text );
2329 }
2330
2331 function getSize() {
2332 return isset( $this->mParams['size'] )
2333 ? $this->mParams['size']
2334 : 45;
2335 }
2336
2337 function validate( $value, $alldata ) {
2338 # HTMLSelectField forces $value to be one of the options in the select
2339 # field, which is not useful here. But we do want the validation further up
2340 # the chain
2341 $p = parent::validate( $value[1], $alldata );
2342
2343 if ( $p !== true ) {
2344 return $p;
2345 }
2346
2347 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2348 return $this->msg( 'htmlform-required' )->parse();
2349 }
2350
2351 return true;
2352 }
2353 }
2354
2355 /**
2356 * Radio checkbox fields.
2357 */
2358 class HTMLRadioField extends HTMLFormField {
2359
2360
2361 function validate( $value, $alldata ) {
2362 $p = parent::validate( $value, $alldata );
2363
2364 if ( $p !== true ) {
2365 return $p;
2366 }
2367
2368 if ( !is_string( $value ) && !is_int( $value ) ) {
2369 return false;
2370 }
2371
2372 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2373
2374 if ( in_array( $value, $validOptions ) ) {
2375 return true;
2376 } else {
2377 return $this->msg( 'htmlform-select-badoption' )->parse();
2378 }
2379 }
2380
2381 /**
2382 * This returns a block of all the radio options, in one cell.
2383 * @see includes/HTMLFormField#getInputHTML()
2384 * @param $value String
2385 * @return String
2386 */
2387 function getInputHTML( $value ) {
2388 $html = $this->formatOptions( $this->mParams['options'], $value );
2389
2390 return $html;
2391 }
2392
2393 function formatOptions( $options, $value ) {
2394 $html = '';
2395
2396 $attribs = array();
2397 if ( !empty( $this->mParams['disabled'] ) ) {
2398 $attribs['disabled'] = 'disabled';
2399 }
2400
2401 # TODO: should this produce an unordered list perhaps?
2402 foreach ( $options as $label => $info ) {
2403 if ( is_array( $info ) ) {
2404 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2405 $html .= $this->formatOptions( $info, $value );
2406 } else {
2407 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2408 $radio = Xml::radio(
2409 $this->mName,
2410 $info,
2411 $info == $value,
2412 $attribs + array( 'id' => $id )
2413 );
2414 $radio .= '&#160;' .
2415 Html::rawElement( 'label', array( 'for' => $id ), $label );
2416
2417 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2418 }
2419 }
2420
2421 return $html;
2422 }
2423
2424 protected function needsLabel() {
2425 return false;
2426 }
2427 }
2428
2429 /**
2430 * An information field (text blob), not a proper input.
2431 */
2432 class HTMLInfoField extends HTMLFormField {
2433 public function __construct( $info ) {
2434 $info['nodata'] = true;
2435
2436 parent::__construct( $info );
2437 }
2438
2439 public function getInputHTML( $value ) {
2440 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2441 }
2442
2443 public function getTableRow( $value ) {
2444 if ( !empty( $this->mParams['rawrow'] ) ) {
2445 return $value;
2446 }
2447
2448 return parent::getTableRow( $value );
2449 }
2450
2451 /**
2452 * @since 1.20
2453 */
2454 public function getDiv( $value ) {
2455 if ( !empty( $this->mParams['rawrow'] ) ) {
2456 return $value;
2457 }
2458
2459 return parent::getDiv( $value );
2460 }
2461
2462 /**
2463 * @since 1.20
2464 */
2465 public function getRaw( $value ) {
2466 if ( !empty( $this->mParams['rawrow'] ) ) {
2467 return $value;
2468 }
2469
2470 return parent::getRaw( $value );
2471 }
2472
2473 protected function needsLabel() {
2474 return false;
2475 }
2476 }
2477
2478 class HTMLHiddenField extends HTMLFormField {
2479 public function __construct( $params ) {
2480 parent::__construct( $params );
2481
2482 # Per HTML5 spec, hidden fields cannot be 'required'
2483 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2484 unset( $this->mParams['required'] );
2485 }
2486
2487 public function getTableRow( $value ) {
2488 $params = array();
2489 if ( $this->mID ) {
2490 $params['id'] = $this->mID;
2491 }
2492
2493 $this->mParent->addHiddenField(
2494 $this->mName,
2495 $this->mDefault,
2496 $params
2497 );
2498
2499 return '';
2500 }
2501
2502 /**
2503 * @since 1.20
2504 */
2505 public function getDiv( $value ) {
2506 return $this->getTableRow( $value );
2507 }
2508
2509 /**
2510 * @since 1.20
2511 */
2512 public function getRaw( $value ) {
2513 return $this->getTableRow( $value );
2514 }
2515
2516 public function getInputHTML( $value ) { return ''; }
2517 }
2518
2519 /**
2520 * Add a submit button inline in the form (as opposed to
2521 * HTMLForm::addButton(), which will add it at the end).
2522 */
2523 class HTMLSubmitField extends HTMLFormField {
2524
2525 public function __construct( $info ) {
2526 $info['nodata'] = true;
2527 parent::__construct( $info );
2528 }
2529
2530 public function getInputHTML( $value ) {
2531 return Xml::submitButton(
2532 $value,
2533 array(
2534 'class' => 'mw-htmlform-submit ' . $this->mClass,
2535 'name' => $this->mName,
2536 'id' => $this->mID,
2537 )
2538 );
2539 }
2540
2541 protected function needsLabel() {
2542 return false;
2543 }
2544
2545 /**
2546 * Button cannot be invalid
2547 * @param $value String
2548 * @param $alldata Array
2549 * @return Bool
2550 */
2551 public function validate( $value, $alldata ) {
2552 return true;
2553 }
2554 }
2555
2556 class HTMLEditTools extends HTMLFormField {
2557 public function getInputHTML( $value ) {
2558 return '';
2559 }
2560
2561 public function getTableRow( $value ) {
2562 $msg = $this->formatMsg();
2563
2564 return '<tr><td></td><td class="mw-input">'
2565 . '<div class="mw-editTools">'
2566 . $msg->parseAsBlock()
2567 . "</div></td></tr>\n";
2568 }
2569
2570 /**
2571 * @since 1.20
2572 */
2573 public function getDiv( $value ) {
2574 $msg = $this->formatMsg();
2575 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2576 }
2577
2578 /**
2579 * @since 1.20
2580 */
2581 public function getRaw( $value ) {
2582 return $this->getDiv( $value );
2583 }
2584
2585 protected function formatMsg() {
2586 if ( empty( $this->mParams['message'] ) ) {
2587 $msg = $this->msg( 'edittools' );
2588 } else {
2589 $msg = $this->msg( $this->mParams['message'] );
2590 if ( $msg->isDisabled() ) {
2591 $msg = $this->msg( 'edittools' );
2592 }
2593 }
2594 $msg->inContentLanguage();
2595 return $msg;
2596 }
2597 }
2598
2599 class HTMLApiField extends HTMLFormField {
2600 public function getTableRow( $value ) {
2601 return '';
2602 }
2603
2604 public function getDiv( $value ) {
2605 return $this->getTableRow( $value );
2606 }
2607
2608 public function getRaw( $value ) {
2609 return $this->getTableRow( $value );
2610 }
2611
2612 public function getInputHTML( $value ) {
2613 return '';
2614 }
2615 }