Non-word characters don't terminate tag names.
[mediawiki.git] / includes / Xml.php
blobac0539d16ca9efb7238ac4f26f188b84eead372f
1 <?php
2 /**
3 * Methods to generate XML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Module of static functions for generating XML
26 class Xml {
27 /**
28 * Format an XML element with given attributes and, optionally, text content.
29 * Element and attribute names are assumed to be ready for literal inclusion.
30 * Strings are assumed to not contain XML-illegal characters; special
31 * characters (<, >, &) are escaped but illegals are not touched.
33 * @param string $element element name
34 * @param array $attribs Name=>value pairs. Values will be escaped.
35 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
36 * @param bool $allowShortTag whether '' in $contents will result in a contentless closed tag
37 * @return string
39 public static function element( $element, $attribs = null, $contents = '', $allowShortTag = true ) {
40 $out = '<' . $element;
41 if ( !is_null( $attribs ) ) {
42 $out .= self::expandAttributes( $attribs );
44 if ( is_null( $contents ) ) {
45 $out .= '>';
46 } else {
47 if ( $allowShortTag && $contents === '' ) {
48 $out .= ' />';
49 } else {
50 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
53 return $out;
56 /**
57 * Given an array of ('attributename' => 'value'), it generates the code
58 * to set the XML attributes : attributename="value".
59 * The values are passed to Sanitizer::encodeAttribute.
60 * Return null if no attributes given.
61 * @param array $attribs of attributes for an XML element
62 * @throws MWException
63 * @return null|string
65 public static function expandAttributes( $attribs ) {
66 $out = '';
67 if ( is_null( $attribs ) ) {
68 return null;
69 } elseif ( is_array( $attribs ) ) {
70 foreach ( $attribs as $name => $val ) {
71 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
73 return $out;
74 } else {
75 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
79 /**
80 * Format an XML element as with self::element(), but run text through the
81 * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
82 * is passed.
84 * @param $element String:
85 * @param array $attribs Name=>value pairs. Values will be escaped.
86 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
87 * @return string
89 public static function elementClean( $element, $attribs = array(), $contents = '' ) {
90 global $wgContLang;
91 if ( $attribs ) {
92 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
94 if ( $contents ) {
95 wfProfileIn( __METHOD__ . '-norm' );
96 $contents = $wgContLang->normalize( $contents );
97 wfProfileOut( __METHOD__ . '-norm' );
99 return self::element( $element, $attribs, $contents );
103 * This opens an XML element
105 * @param string $element name of the element
106 * @param array $attribs of attributes, see Xml::expandAttributes()
107 * @return string
109 public static function openElement( $element, $attribs = null ) {
110 return '<' . $element . self::expandAttributes( $attribs ) . '>';
114 * Shortcut to close an XML element
115 * @param string $element element name
116 * @return string
118 public static function closeElement( $element ) {
119 return "</$element>";
123 * Same as Xml::element(), but does not escape contents. Handy when the
124 * content you have is already valid xml.
126 * @param string $element element name
127 * @param array $attribs of attributes
128 * @param string $contents content of the element
129 * @return string
131 public static function tags( $element, $attribs = null, $contents ) {
132 return self::openElement( $element, $attribs ) . $contents . "</$element>";
136 * Build a drop-down box for selecting a namespace
138 * @param $selected Mixed: Namespace which should be pre-selected
139 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
140 * @param $element_name String: value of the "name" attribute of the select tag
141 * @param string $label optional label to add to the field
142 * @return string
143 * @deprecated since 1.19
145 public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
146 wfDeprecated( __METHOD__, '1.19' );
147 return Html::namespaceSelector( array(
148 'selected' => $selected,
149 'all' => $all,
150 'label' => $label,
151 ), array(
152 'name' => $element_name,
153 'id' => 'namespace',
154 'class' => 'namespaceselector',
155 ) );
159 * Create a date selector
161 * @param $selected Mixed: the month which should be selected, default ''
162 * @param string $allmonths value of a special item denoting all month. Null to not include (default)
163 * @param string $id Element identifier
164 * @return String: Html string containing the month selector
166 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
167 global $wgLang;
168 $options = array();
169 if ( is_null( $selected ) ) {
170 $selected = '';
172 if ( !is_null( $allmonths ) ) {
173 $options[] = self::option( wfMessage( 'monthsall' )->text(), $allmonths, $selected === $allmonths );
175 for ( $i = 1; $i < 13; $i++ ) {
176 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
178 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
179 . implode( "\n", $options )
180 . self::closeElement( 'select' );
184 * @param $year Integer
185 * @param $month Integer
186 * @return string Formatted HTML
188 public static function dateMenu( $year, $month ) {
189 # Offset overrides year/month selection
190 if ( $month && $month !== -1 ) {
191 $encMonth = intval( $month );
192 } else {
193 $encMonth = '';
195 if ( $year ) {
196 $encYear = intval( $year );
197 } elseif ( $encMonth ) {
198 $timestamp = MWTimestamp::getInstance();
199 $thisMonth = intval( $timestamp->format( 'n' ) );
200 $thisYear = intval( $timestamp->format( 'Y' ) );
201 if ( intval( $encMonth ) > $thisMonth ) {
202 $thisYear--;
204 $encYear = $thisYear;
205 } else {
206 $encYear = '';
208 $inputAttribs = array( 'id' => 'year', 'maxlength' => 4, 'size' => 7 );
209 return self::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
210 Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
211 self::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
212 self::monthSelector( $encMonth, -1 );
216 * Construct a language selector appropriate for use in a form or preferences
218 * @param string $selected The language code of the selected language
219 * @param boolean $customisedOnly If true only languages which have some content are listed
220 * @param string $inLanguage The ISO code of the language to display the select list in (optional)
221 * @param array $overrideAttrs Override the attributes of the select tag (since 1.20)
222 * @param Message|null $msg Label message key (since 1.20)
223 * @return array containing 2 items: label HTML and select list HTML
225 public static function languageSelector( $selected, $customisedOnly = true, $inLanguage = null, $overrideAttrs = array(), Message $msg = null ) {
226 global $wgLanguageCode;
228 $include = $customisedOnly ? 'mwfile' : 'mw';
229 $languages = Language::fetchLanguageNames( $inLanguage, $include );
231 // Make sure the site language is in the list;
232 // a custom language code might not have a defined name...
233 if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
234 $languages[$wgLanguageCode] = $wgLanguageCode;
237 ksort( $languages );
240 * If a bogus value is set, default to the content language.
241 * Otherwise, no default is selected and the user ends up
242 * with Afrikaans since it's first in the list.
244 $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
245 $options = "\n";
246 foreach ( $languages as $code => $name ) {
247 $options .= Xml::option( "$code - $name", $code, $code == $selected ) . "\n";
250 $attrs = array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' );
251 $attrs = array_merge( $attrs, $overrideAttrs );
253 if ( $msg === null ) {
254 $msg = wfMessage( 'yourlanguage' );
256 return array(
257 Xml::label( $msg->text(), $attrs['id'] ),
258 Xml::tags( 'select', $attrs, $options )
264 * Shortcut to make a span element
265 * @param string $text content of the element, will be escaped
266 * @param string $class class name of the span element
267 * @param array $attribs other attributes
268 * @return string
270 public static function span( $text, $class, $attribs = array() ) {
271 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
275 * Shortcut to make a specific element with a class attribute
276 * @param string $text content of the element, will be escaped
277 * @param string $class class name of the span element
278 * @param string $tag element name
279 * @param array $attribs other attributes
280 * @return string
282 public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
283 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
287 * Convenience function to build an HTML text input field
288 * @param string $name value of the name attribute
289 * @param int $size value of the size attribute
290 * @param $value mixed value of the value attribute
291 * @param array $attribs other attributes
292 * @return string HTML
294 public static function input( $name, $size = false, $value = false, $attribs = array() ) {
295 $attributes = array( 'name' => $name );
297 if ( $size ) {
298 $attributes['size'] = $size;
301 if ( $value !== false ) { // maybe 0
302 $attributes['value'] = $value;
305 return self::element( 'input', $attributes + $attribs );
309 * Convenience function to build an HTML password input field
310 * @param string $name value of the name attribute
311 * @param int $size value of the size attribute
312 * @param $value mixed value of the value attribute
313 * @param array $attribs other attributes
314 * @return string HTML
316 public static function password( $name, $size = false, $value = false, $attribs = array() ) {
317 return self::input( $name, $size, $value, array_merge( $attribs, array( 'type' => 'password' ) ) );
321 * Internal function for use in checkboxes and radio buttons and such.
323 * @param $name string
324 * @param $present bool
326 * @return array
328 public static function attrib( $name, $present = true ) {
329 return $present ? array( $name => $name ) : array();
333 * Convenience function to build an HTML checkbox
334 * @param string $name value of the name attribute
335 * @param bool $checked Whether the checkbox is checked or not
336 * @param array $attribs other attributes
337 * @return string HTML
339 public static function check( $name, $checked = false, $attribs = array() ) {
340 return self::element( 'input', array_merge(
341 array(
342 'name' => $name,
343 'type' => 'checkbox',
344 'value' => 1 ),
345 self::attrib( 'checked', $checked ),
346 $attribs ) );
350 * Convenience function to build an HTML radio button
351 * @param string $name value of the name attribute
352 * @param string $value value of the value attribute
353 * @param bool $checked Whether the checkbox is checked or not
354 * @param array $attribs other attributes
355 * @return string HTML
357 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
358 return self::element( 'input', array(
359 'name' => $name,
360 'type' => 'radio',
361 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
365 * Convenience function to build an HTML form label
366 * @param string $label text of the label
367 * @param $id
368 * @param array $attribs an attribute array. This will usually be
369 * the same array as is passed to the corresponding input element,
370 * so this function will cherry-pick appropriate attributes to
371 * apply to the label as well; only class and title are applied.
372 * @return string HTML
374 public static function label( $label, $id, $attribs = array() ) {
375 $a = array( 'for' => $id );
377 # FIXME avoid copy pasting below:
378 if ( isset( $attribs['class'] ) ) {
379 $a['class'] = $attribs['class'];
381 if ( isset( $attribs['title'] ) ) {
382 $a['title'] = $attribs['title'];
385 return self::element( 'label', $a, $label );
389 * Convenience function to build an HTML text input field with a label
390 * @param string $label text of the label
391 * @param string $name value of the name attribute
392 * @param string $id id of the input
393 * @param int|Bool $size value of the size attribute
394 * @param string|Bool $value value of the value attribute
395 * @param array $attribs other attributes
396 * @return string HTML
398 public static function inputLabel( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
399 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
400 return $label . '&#160;' . $input;
404 * Same as Xml::inputLabel() but return input and label in an array
406 * @param $label String
407 * @param $name String
408 * @param $id String
409 * @param $size Int|Bool
410 * @param $value String|Bool
411 * @param $attribs array
413 * @return array
415 public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
416 return array(
417 Xml::label( $label, $id, $attribs ),
418 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
423 * Convenience function to build an HTML checkbox with a label
425 * @param $label
426 * @param $name
427 * @param $id
428 * @param $checked bool
429 * @param $attribs array
431 * @return string HTML
433 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
434 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
435 '&#160;' .
436 self::label( $label, $id, $attribs );
440 * Convenience function to build an HTML radio button with a label
442 * @param $label
443 * @param $name
444 * @param $value
445 * @param $id
446 * @param $checked bool
447 * @param $attribs array
449 * @return string HTML
451 public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
452 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
453 '&#160;' .
454 self::label( $label, $id, $attribs );
458 * Convenience function to build an HTML submit button
459 * @param string $value label text for the button
460 * @param array $attribs optional custom attributes
461 * @return string HTML
463 public static function submitButton( $value, $attribs = array() ) {
464 return Html::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
468 * Convenience function to build an HTML drop-down list item.
469 * @param string $text text for this item. Will be HTML escaped
470 * @param string $value form submission value; if empty, use text
471 * @param $selected boolean: if true, will be the default selected item
472 * @param array $attribs optional additional HTML attributes
473 * @return string HTML
475 public static function option( $text, $value = null, $selected = false,
476 $attribs = array() ) {
477 if ( !is_null( $value ) ) {
478 $attribs['value'] = $value;
480 if ( $selected ) {
481 $attribs['selected'] = 'selected';
483 return Html::element( 'option', $attribs, $text );
487 * Build a drop-down box from a textual list.
489 * @param $name Mixed: Name and id for the drop-down
490 * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
491 * @param $other Mixed: Text for the "Other reasons" option
492 * @param $selected Mixed: Option which should be pre-selected
493 * @param $class Mixed: CSS classes for the drop-down
494 * @param $tabindex Mixed: Value of the tabindex attribute
495 * @return string
497 public static function listDropDown( $name = '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
498 $optgroup = false;
500 $options = self::option( $other, 'other', $selected === 'other' );
502 foreach ( explode( "\n", $list ) as $option ) {
503 $value = trim( $option );
504 if ( $value == '' ) {
505 continue;
506 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
507 // A new group is starting ...
508 $value = trim( substr( $value, 1 ) );
509 if ( $optgroup ) {
510 $options .= self::closeElement( 'optgroup' );
512 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
513 $optgroup = true;
514 } elseif ( substr( $value, 0, 2 ) == '**' ) {
515 // groupmember
516 $value = trim( substr( $value, 2 ) );
517 $options .= self::option( $value, $value, $selected === $value );
518 } else {
519 // groupless reason list
520 if ( $optgroup ) {
521 $options .= self::closeElement( 'optgroup' );
523 $options .= self::option( $value, $value, $selected === $value );
524 $optgroup = false;
528 if ( $optgroup ) {
529 $options .= self::closeElement( 'optgroup' );
532 $attribs = array();
534 if ( $name ) {
535 $attribs['id'] = $name;
536 $attribs['name'] = $name;
539 if ( $class ) {
540 $attribs['class'] = $class;
543 if ( $tabindex ) {
544 $attribs['tabindex'] = $tabindex;
547 return Xml::openElement( 'select', $attribs )
548 . "\n"
549 . $options
550 . "\n"
551 . Xml::closeElement( 'select' );
555 * Shortcut for creating fieldsets.
557 * @param string|bool $legend Legend of the fieldset. If evaluates to false, legend is not added.
558 * @param string $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
559 * @param array $attribs Any attributes to fieldset-element.
561 * @return string
563 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
564 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
566 if ( $legend ) {
567 $s .= Xml::element( 'legend', null, $legend ) . "\n";
570 if ( $content !== false ) {
571 $s .= $content . "\n";
572 $s .= Xml::closeElement( 'fieldset' ) . "\n";
575 return $s;
579 * Shortcut for creating textareas.
581 * @param string $name The 'name' for the textarea
582 * @param string $content Content for the textarea
583 * @param int $cols The number of columns for the textarea
584 * @param int $rows The number of rows for the textarea
585 * @param array $attribs Any other attributes for the textarea
587 * @return string
589 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
590 return self::element( 'textarea',
591 array(
592 'name' => $name,
593 'id' => $name,
594 'cols' => $cols,
595 'rows' => $rows
596 ) + $attribs,
597 $content, false );
601 * Returns an escaped string suitable for inclusion in a string literal
602 * for JavaScript source code.
603 * Illegal control characters are assumed not to be present.
605 * @deprecated since 1.21; use Xml::encodeJsVar() or Xml::encodeJsCall() instead
606 * @param string $string to escape
607 * @return String
609 public static function escapeJsString( $string ) {
610 // See ECMA 262 section 7.8.4 for string literal format
611 $pairs = array(
612 "\\" => "\\\\",
613 "\"" => "\\\"",
614 '\'' => '\\\'',
615 "\n" => "\\n",
616 "\r" => "\\r",
618 # To avoid closing the element or CDATA section
619 "<" => "\\x3c",
620 ">" => "\\x3e",
622 # To avoid any complaints about bad entity refs
623 "&" => "\\x26",
625 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
626 # Encode certain Unicode formatting chars so affected
627 # versions of Gecko don't misinterpret our strings;
628 # this is a common problem with Farsi text.
629 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
630 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
633 return strtr( $string, $pairs );
637 * Encode a variable of arbitrary type to JavaScript.
638 * If the value is an XmlJsCode object, pass through the object's value verbatim.
640 * @note Only use this function for generating JavaScript code. If generating output
641 * for a proper JSON parser, just call FormatJson::encode() directly.
643 * @param mixed $value The value being encoded. Can be any type except a resource.
644 * @param bool $pretty If true, add non-significant whitespace to improve readability.
645 * @return string|bool: String if successful; false upon failure
647 public static function encodeJsVar( $value, $pretty = false ) {
648 if ( $value instanceof XmlJsCode ) {
649 return $value->value;
651 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
655 * Create a call to a JavaScript function. The supplied arguments will be
656 * encoded using Xml::encodeJsVar().
658 * @since 1.17
659 * @param string $name The name of the function to call, or a JavaScript expression
660 * which evaluates to a function object which is called.
661 * @param array $args The arguments to pass to the function.
662 * @param bool $pretty If true, add non-significant whitespace to improve readability.
663 * @return string|bool: String if successful; false upon failure
665 public static function encodeJsCall( $name, $args, $pretty = false ) {
666 foreach ( $args as &$arg ) {
667 $arg = Xml::encodeJsVar( $arg, $pretty );
668 if ( $arg === false ) {
669 return false;
673 return "$name(" . ( $pretty
674 ? ( ' ' . implode( ', ', $args ) . ' ' )
675 : implode( ',', $args )
676 ) . ");";
680 * Check if a string is well-formed XML.
681 * Must include the surrounding tag.
683 * @param string $text string to test.
684 * @return bool
686 * @todo Error position reporting return
688 public static function isWellFormed( $text ) {
689 $parser = xml_parser_create( "UTF-8" );
691 # case folding violates XML standard, turn it off
692 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
694 if ( !xml_parse( $parser, $text, true ) ) {
695 //$err = xml_error_string( xml_get_error_code( $parser ) );
696 //$position = xml_get_current_byte_index( $parser );
697 //$fragment = $this->extractFragment( $html, $position );
698 //$this->mXmlError = "$err at byte $position:\n$fragment";
699 xml_parser_free( $parser );
700 return false;
703 xml_parser_free( $parser );
705 return true;
709 * Check if a string is a well-formed XML fragment.
710 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
711 * and can use HTML named entities.
713 * @param $text String:
714 * @return bool
716 public static function isWellFormedXmlFragment( $text ) {
717 $html =
718 Sanitizer::hackDocType() .
719 '<html>' .
720 $text .
721 '</html>';
723 return Xml::isWellFormed( $html );
727 * Replace " > and < with their respective HTML entities ( &quot;,
728 * &gt;, &lt;)
730 * @param string $in text that might contain HTML tags.
731 * @return string Escaped string
733 public static function escapeTagsOnly( $in ) {
734 return str_replace(
735 array( '"', '>', '<' ),
736 array( '&quot;', '&gt;', '&lt;' ),
737 $in );
741 * Generate a form (without the opening form element).
742 * Output optionally includes a submit button.
743 * @param array $fields Associative array, key is the name of a message that contains a description for the field, value is an HTML string containing the appropriate input.
744 * @param string $submitLabel The name of a message containing a label for the submit button.
745 * @param array $submitAttribs The attributes to add to the submit button
746 * @return string HTML form.
748 public static function buildForm( $fields, $submitLabel = null, $submitAttribs = array() ) {
749 $form = '';
750 $form .= "<table><tbody>";
752 foreach ( $fields as $labelmsg => $input ) {
753 $id = "mw-$labelmsg";
754 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
756 // TODO use a <label> here for accessibility purposes - will need
757 // to either not use a table to build the form, or find the ID of
758 // the input somehow.
760 $form .= Xml::tags( 'td', array( 'class' => 'mw-label' ), wfMessage( $labelmsg )->parse() );
761 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
762 $form .= Xml::closeElement( 'tr' );
765 if ( $submitLabel ) {
766 $form .= Xml::openElement( 'tr' );
767 $form .= Xml::tags( 'td', array(), '' );
768 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs ) . Xml::closeElement( 'td' );
769 $form .= Xml::closeElement( 'tr' );
772 $form .= "</tbody></table>";
774 return $form;
778 * Build a table of data
779 * @param array $rows An array of arrays of strings, each to be a row in a table
780 * @param array $attribs An array of attributes to apply to the table tag [optional]
781 * @param array $headers An array of strings to use as table headers [optional]
782 * @return string
784 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
785 $s = Xml::openElement( 'table', $attribs );
787 if ( is_array( $headers ) ) {
788 $s .= Xml::openElement( 'thead', $attribs );
790 foreach ( $headers as $id => $header ) {
791 $attribs = array();
793 if ( is_string( $id ) ) {
794 $attribs['id'] = $id;
797 $s .= Xml::element( 'th', $attribs, $header );
799 $s .= Xml::closeElement( 'thead' );
802 foreach ( $rows as $id => $row ) {
803 $attribs = array();
805 if ( is_string( $id ) ) {
806 $attribs['id'] = $id;
809 $s .= Xml::buildTableRow( $attribs, $row );
812 $s .= Xml::closeElement( 'table' );
814 return $s;
818 * Build a row for a table
819 * @param array $attribs An array of attributes to apply to the tr tag
820 * @param array $cells An array of strings to put in <td>
821 * @return string
823 public static function buildTableRow( $attribs, $cells ) {
824 $s = Xml::openElement( 'tr', $attribs );
826 foreach ( $cells as $id => $cell ) {
827 $attribs = array();
829 if ( is_string( $id ) ) {
830 $attribs['id'] = $id;
833 $s .= Xml::element( 'td', $attribs, $cell );
836 $s .= Xml::closeElement( 'tr' );
838 return $s;
842 class XmlSelect {
843 protected $options = array();
844 protected $default = false;
845 protected $attributes = array();
847 public function __construct( $name = false, $id = false, $default = false ) {
848 if ( $name ) {
849 $this->setAttribute( 'name', $name );
852 if ( $id ) {
853 $this->setAttribute( 'id', $id );
856 if ( $default !== false ) {
857 $this->default = $default;
862 * @param $default
864 public function setDefault( $default ) {
865 $this->default = $default;
869 * @param $name string
870 * @param $value
872 public function setAttribute( $name, $value ) {
873 $this->attributes[$name] = $value;
877 * @param $name
878 * @return array|null
880 public function getAttribute( $name ) {
881 if ( isset( $this->attributes[$name] ) ) {
882 return $this->attributes[$name];
883 } else {
884 return null;
889 * @param $name
890 * @param $value bool
892 public function addOption( $name, $value = false ) {
893 // Stab stab stab
894 $value = $value !== false ? $value : $name;
896 $this->options[] = array( $name => $value );
900 * This accepts an array of form
901 * label => value
902 * label => ( label => value, label => value )
904 * @param $options
906 public function addOptions( $options ) {
907 $this->options[] = $options;
911 * This accepts an array of form
912 * label => value
913 * label => ( label => value, label => value )
915 * @param $options
916 * @param bool $default
917 * @return string
919 static function formatOptions( $options, $default = false ) {
920 $data = '';
922 foreach ( $options as $label => $value ) {
923 if ( is_array( $value ) ) {
924 $contents = self::formatOptions( $value, $default );
925 $data .= Html::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
926 } else {
927 $data .= Xml::option( $label, $value, $value === $default ) . "\n";
931 return $data;
935 * @return string
937 public function getHTML() {
938 $contents = '';
940 foreach ( $this->options as $options ) {
941 $contents .= self::formatOptions( $options, $this->default );
944 return Html::rawElement( 'select', $this->attributes, rtrim( $contents ) );
949 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
950 * interpret a given string as being a JavaScript expression, instead of string
951 * data.
953 * Example:
955 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
957 * Returns "a + b".
959 * @note As of 1.21, XmlJsCode objects cannot be nested inside objects or arrays. The sole
960 * exception is the $args argument to Xml::encodeJsCall() because Xml::encodeJsVar() is
961 * called for each individual element in that array.
963 * @since 1.17
965 class XmlJsCode {
966 public $value;
968 function __construct( $value ) {
969 $this->value = $value;