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