4 * Module of static functions for generating XML
9 * Format an XML element with given attributes and, optionally, text content.
10 * Element and attribute names are assumed to be ready for literal inclusion.
11 * Strings are assumed to not contain XML-illegal characters; special
12 * characters (<, >, &) are escaped but illegals are not touched.
14 * @param $element String: element name
15 * @param $attribs Array: Name=>value pairs. Values will be escaped.
16 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
17 * @param $allowShortTag Bool: whether '' in $contents will result in a contentless closed tag
20 public static function element( $element, $attribs = null, $contents = '', $allowShortTag = true ) {
21 $out = '<' . $element;
22 if( !is_null( $attribs ) ) {
23 $out .= self
::expandAttributes( $attribs );
25 if( is_null( $contents ) ) {
28 if( $allowShortTag && $contents === '' ) {
31 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
38 * Given an array of ('attributename' => 'value'), it generates the code
39 * to set the XML attributes : attributename="value".
40 * The values are passed to Sanitizer::encodeAttribute.
41 * Return null if no attributes given.
42 * @param $attribs Array of attributes for an XML element
45 public static function expandAttributes( $attribs ) {
47 if( is_null( $attribs ) ) {
49 } elseif( is_array( $attribs ) ) {
50 foreach( $attribs as $name => $val ) {
51 $out .= " {$name}=\"" . Sanitizer
::encodeAttribute( $val ) . '"';
55 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__
);
60 * Format an XML element as with self::element(), but run text through the
61 * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
64 * @param $element String:
65 * @param $attribs Array: Name=>value pairs. Values will be escaped.
66 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
69 public static function elementClean( $element, $attribs = array(), $contents = '') {
72 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
75 wfProfileIn( __METHOD__
. '-norm' );
76 $contents = $wgContLang->normalize( $contents );
77 wfProfileOut( __METHOD__
. '-norm' );
79 return self
::element( $element, $attribs, $contents );
83 * This opens an XML element
85 * @param $element String name of the element
86 * @param $attribs array of attributes, see Xml::expandAttributes()
89 public static function openElement( $element, $attribs = null ) {
90 return '<' . $element . self
::expandAttributes( $attribs ) . '>';
94 * Shortcut to close an XML element
95 * @param $element String element name
98 public static function closeElement( $element ) { return "</$element>"; }
101 * Same as Xml::element(), but does not escape contents. Handy when the
102 * content you have is already valid xml.
104 * @param $element String element name
105 * @param $attribs array of attributes
106 * @param $contents String content of the element
109 public static function tags( $element, $attribs = null, $contents ) {
110 return self
::openElement( $element, $attribs ) . $contents . "</$element>";
114 * Build a drop-down box for selecting a namespace
116 * @param $selected Mixed: Namespace which should be pre-selected
117 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
118 * @param $element_name String: value of the "name" attribute of the select tag
119 * @param $label String: optional label to add to the field
121 * @deprecated since 1.19
123 public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
124 wfDeprecated( __METHOD__
, '1.19' );
125 return Html
::namespaceSelector( array(
126 'selected' => $selected,
130 'name' => $element_name,
132 'class' => 'namespaceselector',
137 * Create a date selector
139 * @param $selected Mixed: the month which should be selected, default ''
140 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
141 * @param $id String: Element identifier
142 * @return String: Html string containing the month selector
144 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
147 if( is_null( $selected ) )
149 if( !is_null( $allmonths ) )
150 $options[] = self
::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
151 for( $i = 1; $i < 13; $i++
)
152 $options[] = self
::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
153 return self
::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
154 . implode( "\n", $options )
155 . self
::closeElement( 'select' );
159 * @param $year Integer
160 * @param $month Integer
161 * @return string Formatted HTML
163 public static function dateMenu( $year, $month ) {
164 # Offset overrides year/month selection
165 if( $month && $month !== -1 ) {
166 $encMonth = intval( $month );
171 $encYear = intval( $year );
172 } elseif( $encMonth ) {
173 $thisMonth = intval( gmdate( 'n' ) );
174 $thisYear = intval( gmdate( 'Y' ) );
175 if( intval($encMonth) > $thisMonth ) {
178 $encYear = $thisYear;
182 return Xml
::label( wfMsg( 'year' ), 'year' ) . ' '.
183 Xml
::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) . ' '.
184 Xml
::label( wfMsg( 'month' ), 'month' ) . ' '.
185 Xml
::monthSelector( $encMonth, -1 );
189 * Construct a language selector appropriate for use in a form or preferences
191 * @param string $selected The language code of the selected language
192 * @param boolean $customisedOnly If true only languages which have some content are listed
193 * @param string $language The ISO code of the language to display the select list in (optional)
194 * @return array containing 2 items: label HTML and select list HTML
196 public static function languageSelector( $selected, $customisedOnly = true, $language = null ) {
197 global $wgLanguageCode;
199 // If a specific language was requested and CLDR is installed, use it
200 if ( $language && is_callable( array( 'LanguageNames', 'getNames' ) ) ) {
201 if ( $customisedOnly ) {
202 $listType = LanguageNames
::LIST_MW_SUPPORTED
; // Only pull names that have localisation in MediaWiki
204 $listType = LanguageNames
::LIST_MW
; // Pull all languages that are in Names.php
206 // Retrieve the list of languages in the requested language (via CLDR)
207 $languages = LanguageNames
::getNames(
208 $language, // Code of the requested language
209 LanguageNames
::FALLBACK_NORMAL
, // Use fallback chain
213 $languages = Language
::getLanguageNames( $customisedOnly );
216 // Make sure the site language is in the list; a custom language code might not have a
218 if( !array_key_exists( $wgLanguageCode, $languages ) ) {
219 $languages[$wgLanguageCode] = $wgLanguageCode;
225 * If a bogus value is set, default to the content language.
226 * Otherwise, no default is selected and the user ends up
227 * with an Afrikaans interface since it's first in the list.
229 $selected = isset( $languages[$selected] ) ?
$selected : $wgLanguageCode;
231 foreach( $languages as $code => $name ) {
232 $options .= Xml
::option( "$code - $name", $code, ($code == $selected) ) . "\n";
236 Xml
::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
238 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
246 * Shortcut to make a span element
247 * @param $text String content of the element, will be escaped
248 * @param $class String class name of the span element
249 * @param $attribs array other attributes
252 public static function span( $text, $class, $attribs = array() ) {
253 return self
::element( 'span', array( 'class' => $class ) +
$attribs, $text );
257 * Shortcut to make a specific element with a class attribute
258 * @param $text string content of the element, will be escaped
259 * @param $class string class name of the span element
260 * @param $tag string element name
261 * @param $attribs array other attributes
264 public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
265 return self
::tags( $tag, array( 'class' => $class ) +
$attribs, $text );
269 * Convenience function to build an HTML text input field
270 * @param $name String value of the name attribute
271 * @param $size int value of the size attribute
272 * @param $value mixed value of the value attribute
273 * @param $attribs array other attributes
274 * @return string HTML
276 public static function input( $name, $size = false, $value = false, $attribs = array() ) {
277 $attributes = array( 'name' => $name );
280 $attributes['size'] = $size;
283 if( $value !== false ) { // maybe 0
284 $attributes['value'] = $value;
287 return self
::element( 'input', $attributes +
$attribs );
291 * Convenience function to build an HTML password input field
292 * @param $name string value of the name attribute
293 * @param $size int value of the size attribute
294 * @param $value mixed value of the value attribute
295 * @param $attribs array other attributes
296 * @return string HTML
298 public static function password( $name, $size = false, $value = false, $attribs = array() ) {
299 return self
::input( $name, $size, $value, array_merge( $attribs, array( 'type' => 'password' ) ) );
303 * Internal function for use in checkboxes and radio buttons and such.
305 * @param $name string
306 * @param $present bool
310 public static function attrib( $name, $present = true ) {
311 return $present ?
array( $name => $name ) : array();
315 * Convenience function to build an HTML checkbox
316 * @param $name String value of the name attribute
317 * @param $checked Bool Whether the checkbox is checked or not
318 * @param $attribs Array other attributes
319 * @return string HTML
321 public static function check( $name, $checked = false, $attribs=array() ) {
322 return self
::element( 'input', array_merge(
325 'type' => 'checkbox',
327 self
::attrib( 'checked', $checked ),
332 * Convenience function to build an HTML radio button
333 * @param $name String value of the name attribute
334 * @param $value String value of the value attribute
335 * @param $checked Bool Whether the checkbox is checked or not
336 * @param $attribs Array other attributes
337 * @return string HTML
339 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
340 return self
::element( 'input', array(
343 'value' => $value ) + self
::attrib( 'checked', $checked ) +
$attribs );
347 * Convenience function to build an HTML form label
348 * @param $label String text of the label
350 * @param $attribs Array an attribute array. This will usuall be
351 * the same array as is passed to the corresponding input element,
352 * so this function will cherry-pick appropriate attributes to
353 * apply to the label as well; only class and title are applied.
354 * @return string HTML
356 public static function label( $label, $id, $attribs = array() ) {
357 $a = array( 'for' => $id );
359 # FIXME avoid copy pasting below:
360 if( isset( $attribs['class'] ) ){
361 $a['class'] = $attribs['class'];
363 if( isset( $attribs['title'] ) ){
364 $a['title'] = $attribs['title'];
367 return self
::element( 'label', $a, $label );
371 * Convenience function to build an HTML text input field with a label
372 * @param $label String text of the label
373 * @param $name String value of the name attribute
374 * @param $id String id of the input
375 * @param $size Int|Bool value of the size attribute
376 * @param $value String|Bool value of the value attribute
377 * @param $attribs array other attributes
378 * @return string HTML
380 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs = array() ) {
381 list( $label, $input ) = self
::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
382 return $label . ' ' . $input;
386 * Same as Xml::inputLabel() but return input and label in an array
388 * @param $label String
389 * @param $name String
391 * @param $size Int|Bool
392 * @param $value String|Bool
393 * @param $attribs array
397 public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
399 Xml
::label( $label, $id, $attribs ),
400 self
::input( $name, $size, $value, array( 'id' => $id ) +
$attribs )
405 * Convenience function to build an HTML checkbox with a label
410 * @param $checked bool
411 * @param $attribs array
413 * @return string HTML
415 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
416 return self
::check( $name, $checked, array( 'id' => $id ) +
$attribs ) .
418 self
::label( $label, $id, $attribs );
422 * Convenience function to build an HTML radio button with a label
428 * @param $checked bool
429 * @param $attribs array
431 * @return string HTML
433 public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
434 return self
::radio( $name, $value, $checked, array( 'id' => $id ) +
$attribs ) .
436 self
::label( $label, $id, $attribs );
440 * Convenience function to build an HTML submit button
441 * @param $value String: label text for the button
442 * @param $attribs Array: optional custom attributes
443 * @return string HTML
445 public static function submitButton( $value, $attribs = array() ) {
446 return Html
::element( 'input', array( 'type' => 'submit', 'value' => $value ) +
$attribs );
450 * Convenience function to build an HTML drop-down list item.
451 * @param $text String: text for this item
452 * @param $value String: form submission value; if empty, use text
453 * @param $selected boolean: if true, will be the default selected item
454 * @param $attribs array: optional additional HTML attributes
455 * @return string HTML
457 public static function option( $text, $value=null, $selected = false,
458 $attribs = array() ) {
459 if( !is_null( $value ) ) {
460 $attribs['value'] = $value;
463 $attribs['selected'] = 'selected';
465 return Html
::element( 'option', $attribs, $text );
469 * Build a drop-down box from a textual list.
471 * @param $name Mixed: Name and id for the drop-down
472 * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
473 * @param $other Mixed: Text for the "Other reasons" option
474 * @param $selected Mixed: Option which should be pre-selected
475 * @param $class Mixed: CSS classes for the drop-down
476 * @param $tabindex Mixed: Value of the tabindex attribute
479 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
482 $options = self
::option( $other, 'other', $selected === 'other' );
484 foreach ( explode( "\n", $list ) as $option) {
485 $value = trim( $option );
486 if ( $value == '' ) {
488 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
489 // A new group is starting ...
490 $value = trim( substr( $value, 1 ) );
491 if( $optgroup ) $options .= self
::closeElement('optgroup');
492 $options .= self
::openElement( 'optgroup', array( 'label' => $value ) );
494 } elseif ( substr( $value, 0, 2) == '**' ) {
496 $value = trim( substr( $value, 2 ) );
497 $options .= self
::option( $value, $value, $selected === $value );
499 // groupless reason list
500 if( $optgroup ) $options .= self
::closeElement('optgroup');
501 $options .= self
::option( $value, $value, $selected === $value );
506 if( $optgroup ) $options .= self
::closeElement('optgroup');
511 $attribs['id'] = $name;
512 $attribs['name'] = $name;
516 $attribs['class'] = $class;
520 $attribs['tabindex'] = $tabindex;
523 return Xml
::openElement( 'select', $attribs )
527 . Xml
::closeElement( 'select' );
531 * Shortcut for creating fieldsets.
533 * @param $legend string|bool Legend of the fieldset. If evaluates to false, legend is not added.
534 * @param $content string Pre-escaped content for the fieldset. If false, only open fieldset is returned.
535 * @param $attribs array Any attributes to fieldset-element.
539 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
540 $s = Xml
::openElement( 'fieldset', $attribs ) . "\n";
543 $s .= Xml
::element( 'legend', null, $legend ) . "\n";
546 if ( $content !== false ) {
547 $s .= $content . "\n";
548 $s .= Xml
::closeElement( 'fieldset' ) . "\n";
555 * Shortcut for creating textareas.
557 * @param $name string The 'name' for the textarea
558 * @param $content string Content for the textarea
559 * @param $cols int The number of columns for the textarea
560 * @param $rows int The number of rows for the textarea
561 * @param $attribs array Any other attributes for the textarea
565 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
566 return self
::element( 'textarea',
567 array( 'name' => $name,
576 * Returns an escaped string suitable for inclusion in a string literal
577 * for JavaScript source code.
578 * Illegal control characters are assumed not to be present.
580 * @param $string String to escape
583 public static function escapeJsString( $string ) {
584 // See ECMA 262 section 7.8.4 for string literal format
592 # To avoid closing the element or CDATA section
596 # To avoid any complaints about bad entity refs
599 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
600 # Encode certain Unicode formatting chars so affected
601 # versions of Gecko don't misinterpret our strings;
602 # this is a common problem with Farsi text.
603 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
604 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
607 return strtr( $string, $pairs );
611 * Encode a variable of unknown type to JavaScript.
612 * Arrays are converted to JS arrays, objects are converted to JS associative
613 * arrays (objects). So cast your PHP associative arrays to objects before
614 * passing them to here.
620 public static function encodeJsVar( $value ) {
621 if ( is_bool( $value ) ) {
622 $s = $value ?
'true' : 'false';
623 } elseif ( is_null( $value ) ) {
625 } elseif ( is_int( $value ) ||
is_float( $value ) ) {
627 } elseif ( is_array( $value ) && // Make sure it's not associative.
628 array_keys($value) === range( 0, count($value) - 1 ) ||
632 foreach ( $value as $elt ) {
636 $s .= self
::encodeJsVar( $elt );
639 } elseif ( $value instanceof XmlJsCode
) {
641 } elseif ( is_object( $value ) ||
is_array( $value ) ) {
642 // Objects and associative arrays
644 foreach ( (array)$value as $name => $elt ) {
649 $s .= '"' . self
::escapeJsString( $name ) . '":' .
650 self
::encodeJsVar( $elt );
654 $s = '"' . self
::escapeJsString( $value ) . '"';
660 * Create a call to a JavaScript function. The supplied arguments will be
661 * encoded using Xml::encodeJsVar().
663 * @param $name String The name of the function to call, or a JavaScript expression
664 * which evaluates to a function object which is called.
665 * @param $args Array of arguments to pass to the function.
671 public static function encodeJsCall( $name, $args ) {
675 foreach ( $args as $arg ) {
682 $s .= Xml
::encodeJsVar( $arg );
691 * Check if a string is well-formed XML.
692 * Must include the surrounding tag.
694 * @param $text String: string to test.
697 * @todo Error position reporting return
699 public static function isWellFormed( $text ) {
700 $parser = xml_parser_create( "UTF-8" );
702 # case folding violates XML standard, turn it off
703 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
705 if( !xml_parse( $parser, $text, true ) ) {
706 //$err = xml_error_string( xml_get_error_code( $parser ) );
707 //$position = xml_get_current_byte_index( $parser );
708 //$fragment = $this->extractFragment( $html, $position );
709 //$this->mXmlError = "$err at byte $position:\n$fragment";
710 xml_parser_free( $parser );
714 xml_parser_free( $parser );
720 * Check if a string is a well-formed XML fragment.
721 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
722 * and can use HTML named entities.
724 * @param $text String:
727 public static function isWellFormedXmlFragment( $text ) {
729 Sanitizer
::hackDocType() .
734 return Xml
::isWellFormed( $html );
738 * Replace " > and < with their respective HTML entities ( ",
741 * @param $in String: text that might contain HTML tags.
742 * @return string Escaped string
744 public static function escapeTagsOnly( $in ) {
746 array( '"', '>', '<' ),
747 array( '"', '>', '<' ),
752 * Generate a form (without the opening form element).
753 * Output optionally includes a submit button.
754 * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
755 * @param $submitLabel String A message containing a label for the submit button.
756 * @return string HTML form.
758 public static function buildForm( $fields, $submitLabel = null ) {
760 $form .= "<table><tbody>";
762 foreach( $fields as $labelmsg => $input ) {
763 $id = "mw-$labelmsg";
764 $form .= Xml
::openElement( 'tr', array( 'id' => $id ) );
765 $form .= Xml
::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
766 $form .= Xml
::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml
::closeElement( 'td' );
767 $form .= Xml
::closeElement( 'tr' );
771 $form .= Xml
::openElement( 'tr' );
772 $form .= Xml
::tags( 'td', array(), '' );
773 $form .= Xml
::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml
::submitButton( wfMsg( $submitLabel ) ) . Xml
::closeElement( 'td' );
774 $form .= Xml
::closeElement( 'tr' );
777 $form .= "</tbody></table>";
783 * Build a table of data
784 * @param $rows array An array of arrays of strings, each to be a row in a table
785 * @param $attribs array An array of attributes to apply to the table tag [optional]
786 * @param $headers array An array of strings to use as table headers [optional]
789 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
790 $s = Xml
::openElement( 'table', $attribs );
792 if ( is_array( $headers ) ) {
793 $s .= Xml
::openElement( 'thead', $attribs );
795 foreach( $headers as $id => $header ) {
798 if ( is_string( $id ) ) {
799 $attribs['id'] = $id;
802 $s .= Xml
::element( 'th', $attribs, $header );
804 $s .= Xml
::closeElement( 'thead' );
807 foreach( $rows as $id => $row ) {
810 if ( is_string( $id ) ) {
811 $attribs['id'] = $id;
814 $s .= Xml
::buildTableRow( $attribs, $row );
817 $s .= Xml
::closeElement( 'table' );
823 * Build a row for a table
824 * @param $attribs array An array of attributes to apply to the tr tag
825 * @param $cells array An array of strings to put in <td>
828 public static function buildTableRow( $attribs, $cells ) {
829 $s = Xml
::openElement( 'tr', $attribs );
831 foreach( $cells as $id => $cell ) {
835 if ( is_string( $id ) ) {
836 $attribs['id'] = $id;
839 $s .= Xml
::element( 'td', $attribs, $cell );
842 $s .= Xml
::closeElement( 'tr' );
849 protected $options = array();
850 protected $default = false;
851 protected $attributes = array();
853 public function __construct( $name = false, $id = false, $default = false ) {
855 $this->setAttribute( 'name', $name );
859 $this->setAttribute( 'id', $id );
862 if ( $default !== false ) {
863 $this->default = $default;
870 public function setDefault( $default ) {
871 $this->default = $default;
875 * @param $name string
878 public function setAttribute( $name, $value ) {
879 $this->attributes
[$name] = $value;
886 public function getAttribute( $name ) {
887 if ( isset( $this->attributes
[$name] ) ) {
888 return $this->attributes
[$name];
898 public function addOption( $name, $value = false ) {
900 $value = ($value !== false) ?
$value : $name;
902 $this->options
[] = array( $name => $value );
906 * This accepts an array of form
908 * label => ( label => value, label => value )
912 public function addOptions( $options ) {
913 $this->options
[] = $options;
917 * This accepts an array of form
919 * label => ( label => value, label => value )
922 * @param bool $default
925 static function formatOptions( $options, $default = false ) {
928 foreach( $options as $label => $value ) {
929 if ( is_array( $value ) ) {
930 $contents = self
::formatOptions( $value, $default );
931 $data .= Html
::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
933 $data .= Xml
::option( $label, $value, $value === $default ) . "\n";
943 public function getHTML() {
946 foreach ( $this->options
as $options ) {
947 $contents .= self
::formatOptions( $options, $this->default );
950 return Html
::rawElement( 'select', $this->attributes
, rtrim( $contents ) );
955 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
956 * interpret a given string as being a JavaScript expression, instead of string
961 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
969 function __construct( $value ) {
970 $this->value
= $value;