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)
19 public static function element( $element, $attribs = null, $contents = '') {
20 $out = '<' . $element;
21 if( !is_null( $attribs ) ) {
22 $out .= self
::expandAttributes( $attribs );
24 if( is_null( $contents ) ) {
27 if( $contents === '' ) {
30 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
37 * Given an array of ('attributename' => 'value'), it generates the code
38 * to set the XML attributes : attributename="value".
39 * The values are passed to Sanitizer::encodeAttribute.
40 * Return null if no attributes given.
41 * @param $attribs Array of attributes for an XML element
43 private static function expandAttributes( $attribs ) {
45 if( is_null( $attribs ) ) {
47 } elseif( is_array( $attribs ) ) {
48 foreach( $attribs as $name => $val )
49 $out .= " {$name}=\"" . Sanitizer
::encodeAttribute( $val ) . '"';
52 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__
);
57 * Format an XML element as with self::element(), but run text through the
58 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
61 * @param $element String:
62 * @param $attribs Array: Name=>value pairs. Values will be escaped.
63 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
66 public static function elementClean( $element, $attribs = array(), $contents = '') {
68 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
71 wfProfileIn( __METHOD__
. '-norm' );
72 $contents = UtfNormal
::cleanUp( $contents );
73 wfProfileOut( __METHOD__
. '-norm' );
75 return self
::element( $element, $attribs, $contents );
79 * This opens an XML element
81 * @param $element name of the element
82 * @param $attribs array of attributes, see Xml::expandAttributes()
85 public static function openElement( $element, $attribs = null ) {
86 return '<' . $element . self
::expandAttributes( $attribs ) . '>';
90 * Shortcut to close an XML element
91 * @param $element element name
94 public static function closeElement( $element ) { return "</$element>"; }
97 * Same as Xml::element(), but does not escape contents. Handy when the
98 * content you have is already valid xml.
100 * @param $element element name
101 * @param $attribs array of attributes
102 * @param $contents content of the element
105 public static function tags( $element, $attribs = null, $contents ) {
106 return self
::openElement( $element, $attribs ) . $contents . "</$element>";
110 * Build a drop-down box for selecting a namespace
112 * @param $selected Mixed: Namespace which should be pre-selected
113 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
114 * @param $hidden Mixed: Include hidden namespaces? [WTF? --RC]
115 * @param $element_name String: value of the "name" attribute of the select tag
118 public static function namespaceSelector( $selected = '', $all = null, $hidden = false, $element_name = 'namespace' ) {
120 $namespaces = $wgContLang->getFormattedNamespaces();
123 // Godawful hack... we'll be frequently passed selected namespaces
124 // as strings since PHP is such a shithole.
125 // But we also don't want blanks and nulls and "all"s matching 0,
126 // so let's convert *just* string ints to clean ints.
127 if( preg_match( '/^\d+$/', $selected ) ) {
128 $selected = intval( $selected );
131 if( !is_null( $all ) )
132 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) +
$namespaces;
133 foreach( $namespaces as $index => $name ) {
134 if( $index < NS_MAIN
)
137 $name = wfMsg( 'blanknamespace' );
138 $options[] = self
::option( $name, $index, $index === $selected );
141 return Xml
::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
142 'class' => 'namespaceselector' ) )
144 . implode( "\n", $options )
146 . Xml
::closeElement( 'select' );
150 * Create a date selector
152 * @param $selected Mixed: the month which should be selected, default ''
153 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
154 * @param $id String: Element identifier
155 * @return String: Html string containing the month selector
157 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
160 if( is_null( $selected ) )
162 if( !is_null( $allmonths ) )
163 $options[] = self
::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
164 for( $i = 1; $i < 13; $i++
)
165 $options[] = self
::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
166 return self
::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
167 . implode( "\n", $options )
168 . self
::closeElement( 'select' );
173 * @param $selected The language code of the selected language
174 * @param $customisedOnly If true only languages which have some content are listed
175 * @return array of label and select
177 public static function languageSelector( $selected, $customisedOnly = true ) {
178 global $wgContLanguageCode;
180 * Make sure the site language is in the list; a custom language code
181 * might not have a defined name...
183 $languages = Language
::getLanguageNames( $customisedOnly );
184 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
185 $languages[$wgContLanguageCode] = $wgContLanguageCode;
190 * If a bogus value is set, default to the content language.
191 * Otherwise, no default is selected and the user ends up
192 * with an Afrikaans interface since it's first in the list.
194 $selected = isset( $languages[$selected] ) ?
$selected : $wgContLanguageCode;
196 foreach( $languages as $code => $name ) {
197 $options .= Xml
::option( "$code - $name", $code, ($code == $selected) ) . "\n";
201 Xml
::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
203 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
211 * Shortcut to make a span element
212 * @param $text content of the element, will be escaped
213 * @param $class class name of the span element
214 * @param $attribs other attributes
217 public static function span( $text, $class, $attribs=array() ) {
218 return self
::element( 'span', array( 'class' => $class ) +
$attribs, $text );
222 * Shortcut to make a specific element with a class attribute
223 * @param $text content of the element, will be escaped
224 * @param $class class name of the span element
225 * @param $tag element name
226 * @param $attribs other attributes
229 public static function wrapClass( $text, $class, $tag='span', $attribs=array() ) {
230 return self
::tags( $tag, array( 'class' => $class ) +
$attribs, $text );
234 * Convenience function to build an HTML text input field
235 * @param $name value of the name attribute
236 * @param $size value of the size attribute
237 * @param $value value of the value attribute
238 * @param $attribs other attributes
239 * @return string HTML
241 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
242 return self
::element( 'input', array(
245 'value' => $value ) +
$attribs );
249 * Convenience function to build an HTML password input field
250 * @param $name value of the name attribute
251 * @param $size value of the size attribute
252 * @param $value value of the value attribute
253 * @param $attribs other attributes
254 * @return string HTML
256 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
257 return self
::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
261 * Internal function for use in checkboxes and radio buttons and such.
264 public static function attrib( $name, $present = true ) {
265 return $present ?
array( $name => $name ) : array();
269 * Convenience function to build an HTML checkbox
270 * @param $name value of the name attribute
271 * @param $checked Whether the checkbox is checked or not
272 * @param $attribs other attributes
273 * @return string HTML
275 public static function check( $name, $checked=false, $attribs=array() ) {
276 return self
::element( 'input', array_merge(
279 'type' => 'checkbox',
281 self
::attrib( 'checked', $checked ),
286 * Convenience function to build an HTML radio button
287 * @param $name value of the name attribute
288 * @param $value value of the value attribute
289 * @param $checked Whether the checkbox is checked or not
290 * @param $attribs other attributes
291 * @return string HTML
293 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
294 return self
::element( 'input', array(
297 'value' => $value ) + self
::attrib( 'checked', $checked ) +
$attribs );
301 * Convenience function to build an HTML form label
302 * @param $label text of the label
304 * @return string HTML
306 public static function label( $label, $id ) {
307 return self
::element( 'label', array( 'for' => $id ), $label );
311 * Convenience function to build an HTML text input field with a label
312 * @param $label text of the label
313 * @param $name value of the name attribute
314 * @param $id id of the input
315 * @param $size value of the size attribute
316 * @param $value value of the value attribute
317 * @param $attribs other attributes
318 * @return string HTML
320 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
321 list( $label, $input ) = self
::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
322 return $label . ' ' . $input;
326 * Same as Xml::inputLabel() but return input and label in an array
328 public static function inputLabelSep( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
330 Xml
::label( $label, $id ),
331 self
::input( $name, $size, $value, array( 'id' => $id ) +
$attribs )
336 * Convenience function to build an HTML checkbox with a label
337 * @return string HTML
339 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
340 return self
::check( $name, $checked, array( 'id' => $id ) +
$attribs ) .
342 self
::label( $label, $id );
346 * Convenience function to build an HTML radio button with a label
347 * @return string HTML
349 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
350 return self
::radio( $name, $value, $checked, array( 'id' => $id ) +
$attribs ) .
352 self
::label( $label, $id );
356 * Convenience function to build an HTML submit button
357 * @param $value String: label text for the button
358 * @param $attribs Array: optional custom attributes
359 * @return string HTML
361 public static function submitButton( $value, $attribs=array() ) {
362 return self
::element( 'input', array( 'type' => 'submit', 'value' => $value ) +
$attribs );
366 * Convenience function to build an HTML hidden form field.
367 * @todo Document $name parameter.
369 * @param $value String: label text for the button
370 * @param $attribs Array: optional custom attributes
371 * @return string HTML
373 public static function hidden( $name, $value, $attribs=array() ) {
374 return self
::element( 'input', array(
377 'value' => $value ) +
$attribs );
381 * Convenience function to build an HTML drop-down list item.
382 * @param $text String: text for this item
383 * @param $value String: form submission value; if empty, use text
384 * @param $selected boolean: if true, will be the default selected item
385 * @param $attribs array: optional additional HTML attributes
386 * @return string HTML
388 public static function option( $text, $value=null, $selected=false,
390 if( !is_null( $value ) ) {
391 $attribs['value'] = $value;
394 $attribs['selected'] = 'selected';
396 return self
::element( 'option', $attribs, $text );
400 * Build a drop-down box from a textual list.
402 * @param $name Mixed: Name and id for the drop-down
403 * @param $class Mixed: CSS classes for the drop-down
404 * @param $other Mixed: Text for the "Other reasons" option
405 * @param $list Mixed: Correctly formatted text to be used to generate the options
406 * @param $selected Mixed: Option which should be pre-selected
407 * @param $tabindex Mixed: Value of the tabindex attribute
410 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = Null ) {
414 $options = self
::option( $other, 'other', $selected === 'other' );
416 foreach ( explode( "\n", $list ) as $option) {
417 $value = trim( $option );
418 if ( $value == '' ) {
420 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
421 // A new group is starting ...
422 $value = trim( substr( $value, 1 ) );
423 if( $optgroup ) $options .= self
::closeElement('optgroup');
424 $options .= self
::openElement( 'optgroup', array( 'label' => $value ) );
426 } elseif ( substr( $value, 0, 2) == '**' ) {
428 $value = trim( substr( $value, 2 ) );
429 $options .= self
::option( $value, $value, $selected === $value );
431 // groupless reason list
432 if( $optgroup ) $options .= self
::closeElement('optgroup');
433 $options .= self
::option( $value, $value, $selected === $value );
437 if( $optgroup ) $options .= self
::closeElement('optgroup');
441 $attribs['id'] = $name;
442 $attribs['name'] = $name;
445 $attribs['class'] = $class;
448 $attribs['tabindex'] = $tabindex;
450 return Xml
::openElement( 'select', $attribs )
454 . Xml
::closeElement( 'select' );
458 * Shortcut for creating fieldsets.
460 * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
461 * @param $content Pre-escaped content for the fieldset. If null, only open fieldset is returned.
462 * @param $attribs Any attributes to fieldset-element.
464 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
465 $s = Xml
::openElement( 'fieldset', $attribs ) . "\n";
467 $s .= Xml
::element( 'legend', null, $legend ) . "\n";
469 if ( $content !== false ) {
470 $s .= $content . "\n";
471 $s .= Xml
::closeElement( 'fieldset' ) . "\n";
478 * Returns an escaped string suitable for inclusion in a string literal
479 * for JavaScript source code.
480 * Illegal control characters are assumed not to be present.
482 * @param $string String to escape
485 public static function escapeJsString( $string ) {
486 // See ECMA 262 section 7.8.4 for string literal format
494 # To avoid closing the element or CDATA section
498 # To avoid any complaints about bad entity refs
501 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
502 # Encode certain Unicode formatting chars so affected
503 # versions of Gecko don't misinterpret our strings;
504 # this is a common problem with Farsi text.
505 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
506 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
508 return strtr( $string, $pairs );
512 * Encode a variable of unknown type to JavaScript.
513 * Arrays are converted to JS arrays, objects are converted to JS associative
514 * arrays (objects). So cast your PHP associative arrays to objects before
515 * passing them to here.
517 public static function encodeJsVar( $value ) {
518 if ( is_bool( $value ) ) {
519 $s = $value ?
'true' : 'false';
520 } elseif ( is_null( $value ) ) {
522 } elseif ( is_int( $value ) ) {
524 } elseif ( is_array( $value ) ) {
526 foreach ( $value as $elt ) {
530 $s .= self
::encodeJsVar( $elt );
533 } elseif ( is_object( $value ) ) {
535 foreach ( (array)$value as $name => $elt ) {
539 $s .= '"' . self
::escapeJsString( $name ) . '": ' .
540 self
::encodeJsVar( $elt );
544 $s = '"' . self
::escapeJsString( $value ) . '"';
551 * Check if a string is well-formed XML.
552 * Must include the surrounding tag.
554 * @param $text String: string to test.
557 * @todo Error position reporting return
559 public static function isWellFormed( $text ) {
560 $parser = xml_parser_create( "UTF-8" );
562 # case folding violates XML standard, turn it off
563 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
565 if( !xml_parse( $parser, $text, true ) ) {
566 //$err = xml_error_string( xml_get_error_code( $parser ) );
567 //$position = xml_get_current_byte_index( $parser );
568 //$fragment = $this->extractFragment( $html, $position );
569 //$this->mXmlError = "$err at byte $position:\n$fragment";
570 xml_parser_free( $parser );
573 xml_parser_free( $parser );
578 * Check if a string is a well-formed XML fragment.
579 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
580 * and can use HTML named entities.
582 * @param $text String:
585 public static function isWellFormedXmlFragment( $text ) {
587 Sanitizer
::hackDocType() .
591 return Xml
::isWellFormed( $html );
595 * Replace " > and < with their respective HTML entities ( ",
598 * @param $in String: text that might contain HTML tags.
599 * @return string Escaped string
601 public static function escapeTagsOnly( $in ) {
603 array( '"', '>', '<' ),
604 array( '"', '>', '<' ),
609 * Generate a form (without the opening form element).
610 * Output DOES include a submit button.
611 * @param $fields Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
612 * @param $submitLabel A message containing a label for the submit button.
613 * @return string HTML form.
615 public static function buildForm( $fields, $submitLabel ) {
617 $form .= "<table><tbody>";
619 foreach( $fields as $labelmsg => $input ) {
620 $id = "mw-$labelmsg";
621 $form .= Xml
::openElement( 'tr', array( 'id' => $id ) );
623 $form .= Xml
::element( 'td', array('valign' => 'top'), wfMsg( $labelmsg ) );
625 $form .= Xml
::openElement( 'td' ) . $input . Xml
::closeElement( 'td' );
627 $form .= Xml
::closeElement( 'tr' );
630 $form .= "</tbody></table>";
632 $form .= Xml
::submitButton( wfMsg($submitLabel) );
639 protected $options = array();
640 protected $default = false;
641 protected $attributes = array();
643 public function __construct( $name = false, $id = false, $default = false ) {
644 if ( $name ) $this->setAttribute( 'name', $name );
645 if ( $id ) $this->setAttribute( 'id', $id );
646 if ( $default ) $this->default = $default;
649 public function setDefault( $default ) {
650 $this->default = $default;
653 public function setAttribute( $name, $value ) {
654 $this->attributes
[$name] = $value;
657 public function addOption( $name, $value = false ) {
658 $value = $value ?
$value : $name;
659 $this->options
[] = Xml
::option( $name, $value, $value === $this->default );
662 public function getHTML() {
663 return Xml
::tags( 'select', $this->attributes
, implode( "\n", $this->options
) );