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:
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 );
78 /** This opens an XML element */
79 public static function openElement( $element, $attribs = null ) {
80 return '<' . $element . self
::expandAttributes( $attribs ) . '>';
84 public static function closeElement( $element ) { return "</$element>"; }
87 * Same as <link>element</link>, but does not escape contents. Handy when the
88 * content you have is already valid xml.
90 public static function tags( $element, $attribs = null, $contents ) {
91 return self
::openElement( $element, $attribs ) . $contents . "</$element>";
95 * Build a drop-down box for selecting a namespace
97 * @param mixed $selected Namespace which should be pre-selected
98 * @param mixed $all Value of an item denoting all namespaces, or null to omit
99 * @param bool $hidden Include hidden namespaces? [WTF? --RC]
102 public static function namespaceSelector( $selected = '', $all = null, $hidden = false, $element_name = 'namespace' ) {
104 $namespaces = $wgContLang->getFormattedNamespaces();
107 // Godawful hack... we'll be frequently passed selected namespaces
108 // as strings since PHP is such a shithole.
109 // But we also don't want blanks and nulls and "all"s matching 0,
110 // so let's convert *just* string ints to clean ints.
111 if( preg_match( '/^\d+$/', $selected ) ) {
112 $selected = intval( $selected );
115 if( !is_null( $all ) )
116 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) +
$namespaces;
117 foreach( $namespaces as $index => $name ) {
118 if( $index < NS_MAIN
)
121 $name = wfMsg( 'blanknamespace' );
122 $options[] = self
::option( $name, $index, $index === $selected );
125 return Xml
::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
126 'class' => 'namespaceselector' ) )
128 . implode( "\n", $options )
130 . Xml
::closeElement( 'select' );
134 * Create a date selector
136 * @param $selected Mixed: the month which should be selected, default ''
137 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
138 * @param string $id Element identifier
139 * @return String: Html string containing the month selector
141 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
144 if( is_null( $selected ) )
146 if( !is_null( $allmonths ) )
147 $options[] = self
::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
148 for( $i = 1; $i < 13; $i++
)
149 $options[] = self
::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
150 return self
::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
151 . implode( "\n", $options )
152 . self
::closeElement( 'select' );
157 * @param $language The language code of the selected language
158 * @param $customisedOnly If true only languages which have some content are listed
159 * @return array of label and select
161 public static function languageSelector( $selected, $customisedOnly = true ) {
162 global $wgContLanguageCode;
164 * Make sure the site language is in the list; a custom language code
165 * might not have a defined name...
167 $languages = Language
::getLanguageNames( $customisedOnly );
168 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
169 $languages[$wgContLanguageCode] = $wgContLanguageCode;
174 * If a bogus value is set, default to the content language.
175 * Otherwise, no default is selected and the user ends up
176 * with an Afrikaans interface since it's first in the list.
178 $selected = isset( $languages[$selected] ) ?
$selected : $wgContLanguageCode;
180 foreach( $languages as $code => $name ) {
181 $options .= Xml
::option( "$code - $name", $code, ($code == $selected) ) . "\n";
185 Xml
::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
187 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
194 public static function span( $text, $class, $attribs=array() ) {
195 return self
::element( 'span', array( 'class' => $class ) +
$attribs, $text );
198 public static function wrapClass( $text, $class, $tag='span', $attribs=array() ) {
199 return self
::tags( $tag, array( 'class' => $class ) +
$attribs, $text );
203 * Convenience function to build an HTML text input field
204 * @return string HTML
206 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
207 return self
::element( 'input', array(
210 'value' => $value ) +
$attribs );
214 * Convenience function to build an HTML password input field
215 * @return string HTML
217 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
218 return self
::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
222 * Internal function for use in checkboxes and radio buttons and such.
225 public static function attrib( $name, $present = true ) {
226 return $present ?
array( $name => $name ) : array();
230 * Convenience function to build an HTML checkbox
231 * @return string HTML
233 public static function check( $name, $checked=false, $attribs=array() ) {
234 return self
::element( 'input', array_merge(
237 'type' => 'checkbox',
239 self
::attrib( 'checked', $checked ),
244 * Convenience function to build an HTML radio button
245 * @return string HTML
247 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
248 return self
::element( 'input', array(
251 'value' => $value ) + self
::attrib( 'checked', $checked ) +
$attribs );
255 * Convenience function to build an HTML form label
256 * @return string HTML
258 public static function label( $label, $id ) {
259 return self
::element( 'label', array( 'for' => $id ), $label );
263 * Convenience function to build an HTML text input field with a label
264 * @return string HTML
266 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
267 list( $label, $input ) = self
::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
268 return $label . ' ' . $input;
271 public static function inputLabelSep( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
273 Xml
::label( $label, $id ),
274 self
::input( $name, $size, $value, array( 'id' => $id ) +
$attribs )
279 * Convenience function to build an HTML checkbox with a label
280 * @return string HTML
282 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
283 return self
::check( $name, $checked, array( 'id' => $id ) +
$attribs ) .
285 self
::label( $label, $id );
289 * Convenience function to build an HTML radio button with a label
290 * @return string HTML
292 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
293 return self
::radio( $name, $value, $checked, array( 'id' => $id ) +
$attribs ) .
295 self
::label( $label, $id );
299 * Convenience function to build an HTML submit button
300 * @param $value String: label text for the button
301 * @param $attribs Array: optional custom attributes
302 * @return string HTML
304 public static function submitButton( $value, $attribs=array() ) {
305 return self
::element( 'input', array( 'type' => 'submit', 'value' => $value ) +
$attribs );
309 * Convenience function to build an HTML hidden form field.
310 * @todo Document $name parameter.
312 * @param $value String: label text for the button
313 * @param $attribs Array: optional custom attributes
314 * @return string HTML
316 public static function hidden( $name, $value, $attribs=array() ) {
317 return self
::element( 'input', array(
320 'value' => $value ) +
$attribs );
324 * Convenience function to build an HTML drop-down list item.
325 * @param $text String: text for this item
326 * @param $value String: form submission value; if empty, use text
327 * @param $selected boolean: if true, will be the default selected item
328 * @param $attribs array: optional additional HTML attributes
329 * @return string HTML
331 public static function option( $text, $value=null, $selected=false,
333 if( !is_null( $value ) ) {
334 $attribs['value'] = $value;
337 $attribs['selected'] = 'selected';
339 return self
::element( 'option', $attribs, $text );
343 * Build a drop-down box from a textual list.
345 * @param mixed $name Name and id for the drop-down
346 * @param mixed $class CSS classes for the drop-down
347 * @param mixed $other Text for the "Other reasons" option
348 * @param mixed $list Correctly formatted text to be used to generate the options
349 * @param mixed $selected Option which should be pre-selected
352 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = Null ) {
356 $options = self
::option( $other, 'other', $selected === 'other' );
358 foreach ( explode( "\n", $list ) as $option) {
359 $value = trim( $option );
360 if ( $value == '' ) {
362 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
363 // A new group is starting ...
364 $value = trim( substr( $value, 1 ) );
365 if( $optgroup ) $options .= self
::closeElement('optgroup');
366 $options .= self
::openElement( 'optgroup', array( 'label' => $value ) );
368 } elseif ( substr( $value, 0, 2) == '**' ) {
370 $value = trim( substr( $value, 2 ) );
371 $options .= self
::option( $value, $value, $selected === $value );
373 // groupless reason list
374 if( $optgroup ) $options .= self
::closeElement('optgroup');
375 $options .= self
::option( $value, $value, $selected === $value );
379 if( $optgroup ) $options .= self
::closeElement('optgroup');
383 $attribs['id'] = $name;
384 $attribs['name'] = $name;
387 $attribs['class'] = $class;
390 $attribs['tabindex'] = $tabindex;
392 return Xml
::openElement( 'select', $attribs )
396 . Xml
::closeElement( 'select' );
400 * Shortcut for creating fieldsets.
402 * @param mixed $legend Legend of the fieldset. If evaluates to false, legend is not added.
403 * @param mixed $content Pre-escaped content for the fieldset. If null, only open fieldset is returned.
404 * @param mixed $attribs Any attributes to fieldset-element.
406 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
407 $s = Xml
::openElement( 'fieldset', $attribs ) . "\n";
409 $s .= Xml
::element( 'legend', null, $legend ) . "\n";
411 if ( $content !== false ) {
412 $s .= $content . "\n";
413 $s .= Xml
::closeElement( 'fieldset' ) . "\n";
420 * Returns an escaped string suitable for inclusion in a string literal
421 * for JavaScript source code.
422 * Illegal control characters are assumed not to be present.
424 * @param string $string
427 public static function escapeJsString( $string ) {
428 // See ECMA 262 section 7.8.4 for string literal format
436 # To avoid closing the element or CDATA section
440 # To avoid any complaints about bad entity refs
443 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
444 # Encode certain Unicode formatting chars so affected
445 # versions of Gecko don't misinterpret our strings;
446 # this is a common problem with Farsi text.
447 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
448 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
450 return strtr( $string, $pairs );
454 * Encode a variable of unknown type to JavaScript.
455 * Arrays are converted to JS arrays, objects are converted to JS associative
456 * arrays (objects). So cast your PHP associative arrays to objects before
457 * passing them to here.
459 public static function encodeJsVar( $value ) {
460 if ( is_bool( $value ) ) {
461 $s = $value ?
'true' : 'false';
462 } elseif ( is_null( $value ) ) {
464 } elseif ( is_int( $value ) ) {
466 } elseif ( is_array( $value ) ) {
468 foreach ( $value as $elt ) {
472 $s .= self
::encodeJsVar( $elt );
475 } elseif ( is_object( $value ) ) {
477 foreach ( (array)$value as $name => $elt ) {
481 $s .= '"' . self
::escapeJsString( $name ) . '": ' .
482 self
::encodeJsVar( $elt );
486 $s = '"' . self
::escapeJsString( $value ) . '"';
493 * Check if a string is well-formed XML.
494 * Must include the surrounding tag.
496 * @param $text String: string to test.
499 * @todo Error position reporting return
501 public static function isWellFormed( $text ) {
502 $parser = xml_parser_create( "UTF-8" );
504 # case folding violates XML standard, turn it off
505 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
507 if( !xml_parse( $parser, $text, true ) ) {
508 //$err = xml_error_string( xml_get_error_code( $parser ) );
509 //$position = xml_get_current_byte_index( $parser );
510 //$fragment = $this->extractFragment( $html, $position );
511 //$this->mXmlError = "$err at byte $position:\n$fragment";
512 xml_parser_free( $parser );
515 xml_parser_free( $parser );
520 * Check if a string is a well-formed XML fragment.
521 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
522 * and can use HTML named entities.
524 * @param $text String:
527 public static function isWellFormedXmlFragment( $text ) {
529 Sanitizer
::hackDocType() .
533 return Xml
::isWellFormed( $html );
537 * Replace " > and < with their respective HTML entities ( ",
540 * @param $in String: text that might contain HTML tags.
541 * @return string Escaped string
543 public static function escapeTagsOnly( $in ) {
545 array( '"', '>', '<' ),
546 array( '"', '>', '<' ),
551 * Generate a form (without the opening form element).
552 * Output DOES include a submit button.
553 * @param array $fields Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
554 * @param string $submitLabel A message containing a label for the submit button.
555 * @return string HTML form.
557 public static function buildForm( $fields, $submitLabel ) {
559 $form .= "<table><tbody>";
561 foreach( $fields as $labelmsg => $input ) {
562 $id = "mw-$labelmsg";
563 $form .= Xml
::openElement( 'tr', array( 'id' => $id ) );
565 $form .= Xml
::element( 'td', array('valign' => 'top'), wfMsg( $labelmsg ) );
567 $form .= Xml
::openElement( 'td' ) . $input . Xml
::closeElement( 'td' );
569 $form .= Xml
::closeElement( 'tr' );
572 $form .= "</tbody></table>";
574 $form .= Xml
::submitButton( wfMsg($submitLabel) );
581 protected $options = array();
582 protected $default = false;
583 protected $attributes = array();
585 public function __construct( $name = false, $id = false, $default = false ) {
586 if ( $name ) $this->setAttribute( 'name', $name );
587 if ( $id ) $this->setAttribute( 'id', $id );
588 if ( $default ) $this->default = $default;
591 public function setDefault( $default ) {
592 $this->default = $default;
595 public function setAttribute( $name, $value ) {
596 $this->attributes
[$name] = $value;
599 public function addOption( $name, $value = false ) {
600 $value = $value ?
$value : $name;
601 $this->options
[] = Xml
::option( $name, $value, $value === $this->default );
604 public function getHTML() {
605 return Xml
::tags( 'select', $this->attributes
, implode( "\n", $this->options
) );