Remove silly 'm' prefix from StubObject/DeprecatedGlobal members
[mediawiki.git] / includes / Xml.php
blob6fb5380550a1d68692d26c941fd1ecda1f75bdf1
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 = '',
40 $allowShortTag = true
41 ) {
42 $out = '<' . $element;
43 if ( !is_null( $attribs ) ) {
44 $out .= self::expandAttributes( $attribs );
46 if ( is_null( $contents ) ) {
47 $out .= '>';
48 } else {
49 if ( $allowShortTag && $contents === '' ) {
50 $out .= ' />';
51 } else {
52 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
55 return $out;
58 /**
59 * Given an array of ('attributename' => 'value'), it generates the code
60 * to set the XML attributes : attributename="value".
61 * The values are passed to Sanitizer::encodeAttribute.
62 * Return null if no attributes given.
63 * @param array $attribs Array of attributes for an XML element
64 * @throws MWException
65 * @return null|string
67 public static function expandAttributes( $attribs ) {
68 $out = '';
69 if ( is_null( $attribs ) ) {
70 return null;
71 } elseif ( is_array( $attribs ) ) {
72 foreach ( $attribs as $name => $val ) {
73 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
75 return $out;
76 } else {
77 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
81 /**
82 * Format an XML element as with self::element(), but run text through the
83 * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
84 * is passed.
86 * @param string $element
87 * @param array $attribs Name=>value pairs. Values will be escaped.
88 * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
89 * @return string
91 public static function elementClean( $element, $attribs = array(), $contents = '' ) {
92 global $wgContLang;
93 if ( $attribs ) {
94 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
96 if ( $contents ) {
97 wfProfileIn( __METHOD__ . '-norm' );
98 $contents = $wgContLang->normalize( $contents );
99 wfProfileOut( __METHOD__ . '-norm' );
101 return self::element( $element, $attribs, $contents );
105 * This opens an XML element
107 * @param string $element Name of the element
108 * @param array $attribs Array of attributes, see Xml::expandAttributes()
109 * @return string
111 public static function openElement( $element, $attribs = null ) {
112 return '<' . $element . self::expandAttributes( $attribs ) . '>';
116 * Shortcut to close an XML element
117 * @param string $element Element name
118 * @return string
120 public static function closeElement( $element ) {
121 return "</$element>";
125 * Same as Xml::element(), but does not escape contents. Handy when the
126 * content you have is already valid xml.
128 * @param string $element Element name
129 * @param array $attribs Array of attributes
130 * @param string $contents Content of the element
131 * @return string
133 public static function tags( $element, $attribs = null, $contents ) {
134 return self::openElement( $element, $attribs ) . $contents . "</$element>";
138 * Build a drop-down box for selecting a namespace
140 * @param string $selected Namespace which should be pre-selected
141 * @param string|null $all Value of an item denoting all namespaces, or null to omit
142 * @param string $element_name Value of the "name" attribute of the select tag
143 * @param string $label Optional label to add to the field
144 * @return string
145 * @deprecated since 1.19
147 public static function namespaceSelector( $selected = '', $all = null,
148 $element_name = 'namespace', $label = null
150 wfDeprecated( __METHOD__, '1.19' );
151 return Html::namespaceSelector( array(
152 'selected' => $selected,
153 'all' => $all,
154 'label' => $label,
155 ), array(
156 'name' => $element_name,
157 'id' => 'namespace',
158 'class' => 'namespaceselector',
159 ) );
163 * Create a date selector
165 * @param string $selected The month which should be selected, default ''.
166 * @param string $allmonths Value of a special item denoting all month.
167 * Null to not include (default).
168 * @param string $id Element identifier
169 * @return string Html string containing the month selector
171 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
172 global $wgLang;
173 $options = array();
174 if ( is_null( $selected ) ) {
175 $selected = '';
177 if ( !is_null( $allmonths ) ) {
178 $options[] = self::option(
179 wfMessage( 'monthsall' )->text(),
180 $allmonths,
181 $selected === $allmonths
184 for ( $i = 1; $i < 13; $i++ ) {
185 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
187 return self::openElement( 'select', array(
188 'id' => $id,
189 'name' => 'month',
190 'class' => 'mw-month-selector'
192 . implode( "\n", $options )
193 . self::closeElement( 'select' );
197 * @param int $year
198 * @param int $month
199 * @return string Formatted HTML
201 public static function dateMenu( $year, $month ) {
202 # Offset overrides year/month selection
203 if ( $month && $month !== -1 ) {
204 $encMonth = intval( $month );
205 } else {
206 $encMonth = '';
208 if ( $year ) {
209 $encYear = intval( $year );
210 } elseif ( $encMonth ) {
211 $timestamp = MWTimestamp::getInstance();
212 $thisMonth = intval( $timestamp->format( 'n' ) );
213 $thisYear = intval( $timestamp->format( 'Y' ) );
214 if ( intval( $encMonth ) > $thisMonth ) {
215 $thisYear--;
217 $encYear = $thisYear;
218 } else {
219 $encYear = '';
221 $inputAttribs = array( 'id' => 'year', 'maxlength' => 4, 'size' => 7 );
222 return self::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
223 Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
224 self::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
225 self::monthSelector( $encMonth, -1 );
229 * Construct a language selector appropriate for use in a form or preferences
231 * @param string $selected The language code of the selected language
232 * @param bool $customisedOnly If true only languages which have some content are listed
233 * @param string $inLanguage The ISO code of the language to display the select list in (optional)
234 * @param array $overrideAttrs Override the attributes of the select tag (since 1.20)
235 * @param Message|null $msg Label message key (since 1.20)
236 * @return array containing 2 items: label HTML and select list HTML
238 public static function languageSelector( $selected, $customisedOnly = true,
239 $inLanguage = null, $overrideAttrs = array(), Message $msg = null
241 global $wgLanguageCode;
243 $include = $customisedOnly ? 'mwfile' : 'mw';
244 $languages = Language::fetchLanguageNames( $inLanguage, $include );
246 // Make sure the site language is in the list;
247 // a custom language code might not have a defined name...
248 if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
249 $languages[$wgLanguageCode] = $wgLanguageCode;
252 ksort( $languages );
255 * If a bogus value is set, default to the content language.
256 * Otherwise, no default is selected and the user ends up
257 * with Afrikaans since it's first in the list.
259 $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
260 $options = "\n";
261 foreach ( $languages as $code => $name ) {
262 $options .= Xml::option( "$code - $name", $code, $code == $selected ) . "\n";
265 $attrs = array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' );
266 $attrs = array_merge( $attrs, $overrideAttrs );
268 if ( $msg === null ) {
269 $msg = wfMessage( 'yourlanguage' );
271 return array(
272 Xml::label( $msg->text(), $attrs['id'] ),
273 Xml::tags( 'select', $attrs, $options )
279 * Shortcut to make a span element
280 * @param string $text Content of the element, will be escaped
281 * @param string $class Class name of the span element
282 * @param array $attribs Other attributes
283 * @return string
285 public static function span( $text, $class, $attribs = array() ) {
286 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
290 * Shortcut to make a specific element with a class attribute
291 * @param string $text Content of the element, will be escaped
292 * @param string $class Class name of the span element
293 * @param string $tag Element name
294 * @param array $attribs Other attributes
295 * @return string
297 public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
298 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
302 * Convenience function to build an HTML text input field
303 * @param string $name Value of the name attribute
304 * @param int $size Value of the size attribute
305 * @param mixed $value Value of the value attribute
306 * @param array $attribs Other attributes
307 * @return string HTML
309 public static function input( $name, $size = false, $value = false, $attribs = array() ) {
310 $attributes = array( 'name' => $name );
312 if ( $size ) {
313 $attributes['size'] = $size;
316 if ( $value !== false ) { // maybe 0
317 $attributes['value'] = $value;
320 return self::element( 'input', $attributes + $attribs );
324 * Convenience function to build an HTML password input field
325 * @param string $name Value of the name attribute
326 * @param int $size Value of the size attribute
327 * @param mixed $value Value of the value attribute
328 * @param array $attribs Other attributes
329 * @return string HTML
331 public static function password( $name, $size = false, $value = false,
332 $attribs = array()
334 return self::input( $name, $size, $value,
335 array_merge( $attribs, array( 'type' => 'password' ) ) );
339 * Internal function for use in checkboxes and radio buttons and such.
341 * @param string $name
342 * @param bool $present
344 * @return array
346 public static function attrib( $name, $present = true ) {
347 return $present ? array( $name => $name ) : array();
351 * Convenience function to build an HTML checkbox
352 * @param string $name Value of the name attribute
353 * @param bool $checked Whether the checkbox is checked or not
354 * @param array $attribs Array other attributes
355 * @return string HTML
357 public static function check( $name, $checked = false, $attribs = array() ) {
358 return self::element( 'input', array_merge(
359 array(
360 'name' => $name,
361 'type' => 'checkbox',
362 'value' => 1 ),
363 self::attrib( 'checked', $checked ),
364 $attribs ) );
368 * Convenience function to build an HTML radio button
369 * @param string $name Value of the name attribute
370 * @param string $value Value of the value attribute
371 * @param bool $checked Whether the checkbox is checked or not
372 * @param array $attribs Other attributes
373 * @return string HTML
375 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
376 return self::element( 'input', array(
377 'name' => $name,
378 'type' => 'radio',
379 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
383 * Convenience function to build an HTML form label
384 * @param string $label Text of the label
385 * @param string $id
386 * @param array $attribs An attribute array. This will usually be
387 * the same array as is passed to the corresponding input element,
388 * so this function will cherry-pick appropriate attributes to
389 * apply to the label as well; only class and title are applied.
390 * @return string HTML
392 public static function label( $label, $id, $attribs = array() ) {
393 $a = array( 'for' => $id );
395 # FIXME avoid copy pasting below:
396 if ( isset( $attribs['class'] ) ) {
397 $a['class'] = $attribs['class'];
399 if ( isset( $attribs['title'] ) ) {
400 $a['title'] = $attribs['title'];
403 return self::element( 'label', $a, $label );
407 * Convenience function to build an HTML text input field with a label
408 * @param string $label Text of the label
409 * @param string $name Value of the name attribute
410 * @param string $id Id of the input
411 * @param int|bool $size Value of the size attribute
412 * @param string|bool $value Value of the value attribute
413 * @param array $attribs Other attributes
414 * @return string HTML
416 public static function inputLabel( $label, $name, $id, $size = false,
417 $value = false, $attribs = array()
419 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
420 return $label . '&#160;' . $input;
424 * Same as Xml::inputLabel() but return input and label in an array
426 * @param string $label
427 * @param string $name
428 * @param string $id
429 * @param int|bool $size
430 * @param string|bool $value
431 * @param array $attribs
433 * @return array
435 public static function inputLabelSep( $label, $name, $id, $size = false,
436 $value = false, $attribs = array()
438 return array(
439 Xml::label( $label, $id, $attribs ),
440 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
445 * Convenience function to build an HTML checkbox with a label
447 * @param string $label
448 * @param string $name
449 * @param string $id
450 * @param bool $checked
451 * @param array $attribs
453 * @return string HTML
455 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
456 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
457 '&#160;' .
458 self::label( $label, $id, $attribs );
462 * Convenience function to build an HTML radio button with a label
464 * @param string $label
465 * @param string $name
466 * @param string $value
467 * @param string $id
468 * @param bool $checked
469 * @param array $attribs
471 * @return string HTML
473 public static function radioLabel( $label, $name, $value, $id,
474 $checked = false, $attribs = array()
476 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
477 '&#160;' .
478 self::label( $label, $id, $attribs );
482 * Convenience function to build an HTML submit button
483 * @param string $value Label text for the button
484 * @param array $attribs Optional custom attributes
485 * @return string HTML
487 public static function submitButton( $value, $attribs = array() ) {
488 return Html::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
492 * Convenience function to build an HTML drop-down list item.
493 * @param string $text Text for this item. Will be HTML escaped
494 * @param string $value Form submission value; if empty, use text
495 * @param bool $selected If true, will be the default selected item
496 * @param array $attribs Optional additional HTML attributes
497 * @return string HTML
499 public static function option( $text, $value = null, $selected = false,
500 $attribs = array() ) {
501 if ( !is_null( $value ) ) {
502 $attribs['value'] = $value;
504 if ( $selected ) {
505 $attribs['selected'] = 'selected';
507 return Html::element( 'option', $attribs, $text );
511 * Build a drop-down box from a textual list.
513 * @param string $name Name and id for the drop-down
514 * @param string $list Correctly formatted text (newline delimited) to be
515 * used to generate the options.
516 * @param string $other Text for the "Other reasons" option
517 * @param string $selected Option which should be pre-selected
518 * @param string $class CSS classes for the drop-down
519 * @param int $tabindex Value of the tabindex attribute
520 * @return string
522 public static function listDropDown( $name = '', $list = '', $other = '',
523 $selected = '', $class = '', $tabindex = null
525 $optgroup = false;
527 $options = self::option( $other, 'other', $selected === 'other' );
529 foreach ( explode( "\n", $list ) as $option ) {
530 $value = trim( $option );
531 if ( $value == '' ) {
532 continue;
533 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
534 // A new group is starting ...
535 $value = trim( substr( $value, 1 ) );
536 if ( $optgroup ) {
537 $options .= self::closeElement( 'optgroup' );
539 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
540 $optgroup = true;
541 } elseif ( substr( $value, 0, 2 ) == '**' ) {
542 // groupmember
543 $value = trim( substr( $value, 2 ) );
544 $options .= self::option( $value, $value, $selected === $value );
545 } else {
546 // groupless reason list
547 if ( $optgroup ) {
548 $options .= self::closeElement( 'optgroup' );
550 $options .= self::option( $value, $value, $selected === $value );
551 $optgroup = false;
555 if ( $optgroup ) {
556 $options .= self::closeElement( 'optgroup' );
559 $attribs = array();
561 if ( $name ) {
562 $attribs['id'] = $name;
563 $attribs['name'] = $name;
566 if ( $class ) {
567 $attribs['class'] = $class;
570 if ( $tabindex ) {
571 $attribs['tabindex'] = $tabindex;
574 return Xml::openElement( 'select', $attribs )
575 . "\n"
576 . $options
577 . "\n"
578 . Xml::closeElement( 'select' );
582 * Shortcut for creating fieldsets.
584 * @param string|bool $legend Legend of the fieldset. If evaluates to false,
585 * legend is not added.
586 * @param string $content Pre-escaped content for the fieldset. If false,
587 * only open fieldset is returned.
588 * @param array $attribs Any attributes to fieldset-element.
590 * @return string
592 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
593 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
595 if ( $legend ) {
596 $s .= Xml::element( 'legend', null, $legend ) . "\n";
599 if ( $content !== false ) {
600 $s .= $content . "\n";
601 $s .= Xml::closeElement( 'fieldset' ) . "\n";
604 return $s;
608 * Shortcut for creating textareas.
610 * @param string $name The 'name' for the textarea
611 * @param string $content Content for the textarea
612 * @param int $cols The number of columns for the textarea
613 * @param int $rows The number of rows for the textarea
614 * @param array $attribs Any other attributes for the textarea
616 * @return string
618 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
619 return self::element( 'textarea',
620 array(
621 'name' => $name,
622 'id' => $name,
623 'cols' => $cols,
624 'rows' => $rows
625 ) + $attribs,
626 $content, false );
630 * Returns an escaped string suitable for inclusion in a string literal
631 * for JavaScript source code.
632 * Illegal control characters are assumed not to be present.
634 * @deprecated since 1.21; use Xml::encodeJsVar() or Xml::encodeJsCall() instead
635 * @param string $string String to escape
636 * @return string
638 public static function escapeJsString( $string ) {
639 // See ECMA 262 section 7.8.4 for string literal format
640 $pairs = array(
641 "\\" => "\\\\",
642 "\"" => "\\\"",
643 '\'' => '\\\'',
644 "\n" => "\\n",
645 "\r" => "\\r",
647 # To avoid closing the element or CDATA section
648 "<" => "\\x3c",
649 ">" => "\\x3e",
651 # To avoid any complaints about bad entity refs
652 "&" => "\\x26",
654 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
655 # Encode certain Unicode formatting chars so affected
656 # versions of Gecko don't misinterpret our strings;
657 # this is a common problem with Farsi text.
658 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
659 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
662 return strtr( $string, $pairs );
666 * Encode a variable of arbitrary type to JavaScript.
667 * If the value is an XmlJsCode object, pass through the object's value verbatim.
669 * @note Only use this function for generating JavaScript code. If generating output
670 * for a proper JSON parser, just call FormatJson::encode() directly.
672 * @param mixed $value The value being encoded. Can be any type except a resource.
673 * @param bool $pretty If true, add non-significant whitespace to improve readability.
674 * @return string|bool String if successful; false upon failure
676 public static function encodeJsVar( $value, $pretty = false ) {
677 if ( $value instanceof XmlJsCode ) {
678 return $value->value;
680 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
684 * Create a call to a JavaScript function. The supplied arguments will be
685 * encoded using Xml::encodeJsVar().
687 * @since 1.17
688 * @param string $name The name of the function to call, or a JavaScript expression
689 * which evaluates to a function object which is called.
690 * @param array $args The arguments to pass to the function.
691 * @param bool $pretty If true, add non-significant whitespace to improve readability.
692 * @return string|bool String if successful; false upon failure
694 public static function encodeJsCall( $name, $args, $pretty = false ) {
695 foreach ( $args as &$arg ) {
696 $arg = Xml::encodeJsVar( $arg, $pretty );
697 if ( $arg === false ) {
698 return false;
702 return "$name(" . ( $pretty
703 ? ( ' ' . implode( ', ', $args ) . ' ' )
704 : implode( ',', $args )
705 ) . ");";
709 * Check if a string is well-formed XML.
710 * Must include the surrounding tag.
712 * @param string $text String to test.
713 * @return bool
715 * @todo Error position reporting return
717 public static function isWellFormed( $text ) {
718 $parser = xml_parser_create( "UTF-8" );
720 # case folding violates XML standard, turn it off
721 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
723 if ( !xml_parse( $parser, $text, true ) ) {
724 //$err = xml_error_string( xml_get_error_code( $parser ) );
725 //$position = xml_get_current_byte_index( $parser );
726 //$fragment = $this->extractFragment( $html, $position );
727 //$this->mXmlError = "$err at byte $position:\n$fragment";
728 xml_parser_free( $parser );
729 return false;
732 xml_parser_free( $parser );
734 return true;
738 * Check if a string is a well-formed XML fragment.
739 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
740 * and can use HTML named entities.
742 * @param string $text
743 * @return bool
745 public static function isWellFormedXmlFragment( $text ) {
746 $html =
747 Sanitizer::hackDocType() .
748 '<html>' .
749 $text .
750 '</html>';
752 return Xml::isWellFormed( $html );
756 * Replace " > and < with their respective HTML entities ( &quot;,
757 * &gt;, &lt;)
759 * @param string $in Text that might contain HTML tags.
760 * @return string Escaped string
762 public static function escapeTagsOnly( $in ) {
763 return str_replace(
764 array( '"', '>', '<' ),
765 array( '&quot;', '&gt;', '&lt;' ),
766 $in );
770 * Generate a form (without the opening form element).
771 * Output optionally includes a submit button.
772 * @param array $fields Associative array, key is the name of a message that
773 * contains a description for the field, value is an HTML string
774 * containing the appropriate input.
775 * @param string $submitLabel The name of a message containing a label for
776 * the submit button.
777 * @param array $submitAttribs The attributes to add to the submit button
778 * @return string HTML form.
780 public static function buildForm( $fields, $submitLabel = null, $submitAttribs = array() ) {
781 $form = '';
782 $form .= "<table><tbody>";
784 foreach ( $fields as $labelmsg => $input ) {
785 $id = "mw-$labelmsg";
786 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
788 // TODO use a <label> here for accessibility purposes - will need
789 // to either not use a table to build the form, or find the ID of
790 // the input somehow.
792 $form .= Xml::tags( 'td', array( 'class' => 'mw-label' ), wfMessage( $labelmsg )->parse() );
793 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) )
794 . $input . Xml::closeElement( 'td' );
795 $form .= Xml::closeElement( 'tr' );
798 if ( $submitLabel ) {
799 $form .= Xml::openElement( 'tr' );
800 $form .= Xml::tags( 'td', array(), '' );
801 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) )
802 . Xml::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
803 . Xml::closeElement( 'td' );
804 $form .= Xml::closeElement( 'tr' );
807 $form .= "</tbody></table>";
809 return $form;
813 * Build a table of data
814 * @param array $rows An array of arrays of strings, each to be a row in a table
815 * @param array $attribs An array of attributes to apply to the table tag [optional]
816 * @param array $headers An array of strings to use as table headers [optional]
817 * @return string
819 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
820 $s = Xml::openElement( 'table', $attribs );
822 if ( is_array( $headers ) ) {
823 $s .= Xml::openElement( 'thead', $attribs );
825 foreach ( $headers as $id => $header ) {
826 $attribs = array();
828 if ( is_string( $id ) ) {
829 $attribs['id'] = $id;
832 $s .= Xml::element( 'th', $attribs, $header );
834 $s .= Xml::closeElement( 'thead' );
837 foreach ( $rows as $id => $row ) {
838 $attribs = array();
840 if ( is_string( $id ) ) {
841 $attribs['id'] = $id;
844 $s .= Xml::buildTableRow( $attribs, $row );
847 $s .= Xml::closeElement( 'table' );
849 return $s;
853 * Build a row for a table
854 * @param array $attribs An array of attributes to apply to the tr tag
855 * @param array $cells An array of strings to put in <td>
856 * @return string
858 public static function buildTableRow( $attribs, $cells ) {
859 $s = Xml::openElement( 'tr', $attribs );
861 foreach ( $cells as $id => $cell ) {
862 $attribs = array();
864 if ( is_string( $id ) ) {
865 $attribs['id'] = $id;
868 $s .= Xml::element( 'td', $attribs, $cell );
871 $s .= Xml::closeElement( 'tr' );
873 return $s;
877 class XmlSelect {
878 protected $options = array();
879 protected $default = false;
880 protected $attributes = array();
882 public function __construct( $name = false, $id = false, $default = false ) {
883 if ( $name ) {
884 $this->setAttribute( 'name', $name );
887 if ( $id ) {
888 $this->setAttribute( 'id', $id );
891 if ( $default !== false ) {
892 $this->default = $default;
897 * @param string $default
899 public function setDefault( $default ) {
900 $this->default = $default;
904 * @param string $name
905 * @param array $value
907 public function setAttribute( $name, $value ) {
908 $this->attributes[$name] = $value;
912 * @param string $name
913 * @return array|null
915 public function getAttribute( $name ) {
916 if ( isset( $this->attributes[$name] ) ) {
917 return $this->attributes[$name];
918 } else {
919 return null;
924 * @param string $name
925 * @param bool $value
927 public function addOption( $name, $value = false ) {
928 // Stab stab stab
929 $value = $value !== false ? $value : $name;
931 $this->options[] = array( $name => $value );
935 * This accepts an array of form
936 * label => value
937 * label => ( label => value, label => value )
939 * @param array $options
941 public function addOptions( $options ) {
942 $this->options[] = $options;
946 * This accepts an array of form
947 * label => value
948 * label => ( label => value, label => value )
950 * @param array $options
951 * @param bool $default
952 * @return string
954 static function formatOptions( $options, $default = false ) {
955 $data = '';
957 foreach ( $options as $label => $value ) {
958 if ( is_array( $value ) ) {
959 $contents = self::formatOptions( $value, $default );
960 $data .= Html::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
961 } else {
962 $data .= Xml::option( $label, $value, $value === $default ) . "\n";
966 return $data;
970 * @return string
972 public function getHTML() {
973 $contents = '';
975 foreach ( $this->options as $options ) {
976 $contents .= self::formatOptions( $options, $this->default );
979 return Html::rawElement( 'select', $this->attributes, rtrim( $contents ) );
984 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
985 * interpret a given string as being a JavaScript expression, instead of string
986 * data.
988 * Example:
990 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
992 * Returns "a + b".
994 * @note As of 1.21, XmlJsCode objects cannot be nested inside objects or arrays. The sole
995 * exception is the $args argument to Xml::encodeJsCall() because Xml::encodeJsVar() is
996 * called for each individual element in that array.
998 * @since 1.17
1000 class XmlJsCode {
1001 public $value;
1003 function __construct( $value ) {
1004 $this->value = $value;