Fixup some more wrong static usages
[lhc/web/wiklou.git] / includes / Xml.php
1 <?php
2
3 /**
4 * Module of static functions for generating XML
5 */
6
7 class Xml {
8 /**
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.
13 *
14 * @param $element String: element name
15 * @param $attribs Array: Name=>value pairs. Values will be escaped.
16 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
17 * @param $allowShortTag Bool: whether '' in $contents will result in a contentless closed tag
18 * @return string
19 */
20 public static function element( $element, $attribs = null, $contents = '', $allowShortTag = true ) {
21 $out = '<' . $element;
22 if( !is_null( $attribs ) ) {
23 $out .= self::expandAttributes( $attribs );
24 }
25 if( is_null( $contents ) ) {
26 $out .= '>';
27 } else {
28 if( $allowShortTag && $contents === '' ) {
29 $out .= ' />';
30 } else {
31 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
32 }
33 }
34 return $out;
35 }
36
37 /**
38 * Given an array of ('attributename' => 'value'), it generates the code
39 * to set the XML attributes : attributename="value".
40 * The values are passed to Sanitizer::encodeAttribute.
41 * Return null if no attributes given.
42 * @param $attribs Array of attributes for an XML element
43 */
44 public static function expandAttributes( $attribs ) {
45 $out = '';
46 if( is_null( $attribs ) ) {
47 return null;
48 } elseif( is_array( $attribs ) ) {
49 foreach( $attribs as $name => $val )
50 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
51 return $out;
52 } else {
53 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
54 }
55 }
56
57 /**
58 * Format an XML element as with self::element(), but run text through the
59 * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
60 * is passed.
61 *
62 * @param $element String:
63 * @param $attribs Array: Name=>value pairs. Values will be escaped.
64 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
65 * @return string
66 */
67 public static function elementClean( $element, $attribs = array(), $contents = '') {
68 global $wgContLang;
69 if( $attribs ) {
70 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
71 }
72 if( $contents ) {
73 wfProfileIn( __METHOD__ . '-norm' );
74 $contents = $wgContLang->normalize( $contents );
75 wfProfileOut( __METHOD__ . '-norm' );
76 }
77 return self::element( $element, $attribs, $contents );
78 }
79
80 /**
81 * This opens an XML element
82 *
83 * @param $element name of the element
84 * @param $attribs array of attributes, see Xml::expandAttributes()
85 * @return string
86 */
87 public static function openElement( $element, $attribs = null ) {
88 return '<' . $element . self::expandAttributes( $attribs ) . '>';
89 }
90
91 /**
92 * Shortcut to close an XML element
93 * @param $element element name
94 * @return string
95 */
96 public static function closeElement( $element ) { return "</$element>"; }
97
98 /**
99 * Same as Xml::element(), but does not escape contents. Handy when the
100 * content you have is already valid xml.
101 *
102 * @param $element element name
103 * @param $attribs array of attributes
104 * @param $contents content of the element
105 * @return string
106 */
107 public static function tags( $element, $attribs = null, $contents ) {
108 return self::openElement( $element, $attribs ) . $contents . "</$element>";
109 }
110
111 /**
112 * Build a drop-down box for selecting a namespace
113 *
114 * @param $selected Mixed: Namespace which should be pre-selected
115 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
116 * @param $element_name String: value of the "name" attribute of the select tag
117 * @param $label String: optional label to add to the field
118 * @return string
119 */
120 public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
121 global $wgContLang;
122 $namespaces = $wgContLang->getFormattedNamespaces();
123 $options = array();
124
125 // Godawful hack... we'll be frequently passed selected namespaces
126 // as strings since PHP is such a shithole.
127 // But we also don't want blanks and nulls and "all"s matching 0,
128 // so let's convert *just* string ints to clean ints.
129 if( preg_match( '/^\d+$/', $selected ) ) {
130 $selected = intval( $selected );
131 }
132
133 if( !is_null( $all ) )
134 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) + $namespaces;
135 foreach( $namespaces as $index => $name ) {
136 if( $index < NS_MAIN )
137 continue;
138 if( $index === 0 )
139 $name = wfMsg( 'blanknamespace' );
140 $options[] = self::option( $name, $index, $index === $selected );
141 }
142
143 $ret = Xml::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
144 'class' => 'namespaceselector' ) )
145 . "\n"
146 . implode( "\n", $options )
147 . "\n"
148 . Xml::closeElement( 'select' );
149 if ( !is_null( $label ) ) {
150 $ret = Xml::label( $label, $element_name ) . '&#160;' . $ret;
151 }
152 return $ret;
153 }
154
155 /**
156 * Create a date selector
157 *
158 * @param $selected Mixed: the month which should be selected, default ''
159 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
160 * @param $id String: Element identifier
161 * @return String: Html string containing the month selector
162 */
163 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
164 global $wgLang;
165 $options = array();
166 if( is_null( $selected ) )
167 $selected = '';
168 if( !is_null( $allmonths ) )
169 $options[] = self::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
170 for( $i = 1; $i < 13; $i++ )
171 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
172 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
173 . implode( "\n", $options )
174 . self::closeElement( 'select' );
175 }
176
177 /**
178 * @param $year Integer
179 * @param $month Integer
180 * @return string Formatted HTML
181 */
182 public static function dateMenu( $year, $month ) {
183 # Offset overrides year/month selection
184 if( $month && $month !== -1 ) {
185 $encMonth = intval( $month );
186 } else {
187 $encMonth = '';
188 }
189 if( $year ) {
190 $encYear = intval( $year );
191 } else if( $encMonth ) {
192 $thisMonth = intval( gmdate( 'n' ) );
193 $thisYear = intval( gmdate( 'Y' ) );
194 if( intval($encMonth) > $thisMonth ) {
195 $thisYear--;
196 }
197 $encYear = $thisYear;
198 } else {
199 $encYear = '';
200 }
201 return Xml::label( wfMsg( 'year' ), 'year' ) . ' '.
202 Xml::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) . ' '.
203 Xml::label( wfMsg( 'month' ), 'month' ) . ' '.
204 Xml::monthSelector( $encMonth, -1 );
205 }
206
207 /**
208 *
209 * @param $selected The language code of the selected language
210 * @param $customisedOnly If true only languages which have some content are listed
211 * @return array of label and select
212 */
213 public static function languageSelector( $selected, $customisedOnly = true ) {
214 global $wgContLanguageCode;
215 /**
216 * Make sure the site language is in the list; a custom language code
217 * might not have a defined name...
218 */
219 $languages = Language::getLanguageNames( $customisedOnly );
220 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
221 $languages[$wgContLanguageCode] = $wgContLanguageCode;
222 }
223 ksort( $languages );
224
225 /**
226 * If a bogus value is set, default to the content language.
227 * Otherwise, no default is selected and the user ends up
228 * with an Afrikaans interface since it's first in the list.
229 */
230 $selected = isset( $languages[$selected] ) ? $selected : $wgContLanguageCode;
231 $options = "\n";
232 foreach( $languages as $code => $name ) {
233 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
234 }
235
236 return array(
237 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
238 Xml::tags( 'select',
239 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
240 $options
241 )
242 );
243
244 }
245
246 /**
247 * Shortcut to make a span element
248 * @param $text content of the element, will be escaped
249 * @param $class class name of the span element
250 * @param $attribs other attributes
251 * @return string
252 */
253 public static function span( $text, $class, $attribs=array() ) {
254 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
255 }
256
257 /**
258 * Shortcut to make a specific element with a class attribute
259 * @param $text content of the element, will be escaped
260 * @param $class class name of the span element
261 * @param $tag element name
262 * @param $attribs other attributes
263 * @return string
264 */
265 public static function wrapClass( $text, $class, $tag='span', $attribs=array() ) {
266 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
267 }
268
269 /**
270 * Convenience function to build an HTML text input field
271 * @param $name value of the name attribute
272 * @param $size value of the size attribute
273 * @param $value value of the value attribute
274 * @param $attribs other attributes
275 * @return string HTML
276 */
277 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
278 $attributes = array( 'name' => $name );
279
280 if( $size ) {
281 $attributes['size'] = $size;
282 }
283
284 if( $value !== false ) { // maybe 0
285 $attributes['value'] = $value;
286 }
287
288 return self::element( 'input', $attributes + $attribs );
289 }
290
291 /**
292 * Convenience function to build an HTML password input field
293 * @param $name value of the name attribute
294 * @param $size value of the size attribute
295 * @param $value value of the value attribute
296 * @param $attribs other attributes
297 * @return string HTML
298 */
299 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
300 return self::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
301 }
302
303 /**
304 * Internal function for use in checkboxes and radio buttons and such.
305 * @return array
306 */
307 public static function attrib( $name, $present = true ) {
308 return $present ? array( $name => $name ) : array();
309 }
310
311 /**
312 * Convenience function to build an HTML checkbox
313 * @param $name value of the name attribute
314 * @param $checked Whether the checkbox is checked or not
315 * @param $attribs other attributes
316 * @return string HTML
317 */
318 public static function check( $name, $checked=false, $attribs=array() ) {
319 return self::element( 'input', array_merge(
320 array(
321 'name' => $name,
322 'type' => 'checkbox',
323 'value' => 1 ),
324 self::attrib( 'checked', $checked ),
325 $attribs ) );
326 }
327
328 /**
329 * Convenience function to build an HTML radio button
330 * @param $name value of the name attribute
331 * @param $value value of the value attribute
332 * @param $checked Whether the checkbox is checked or not
333 * @param $attribs other attributes
334 * @return string HTML
335 */
336 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
337 return self::element( 'input', array(
338 'name' => $name,
339 'type' => 'radio',
340 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
341 }
342
343 /**
344 * Convenience function to build an HTML form label
345 * @param $label text of the label
346 * @param $id
347 * @param $attribs Array, other attributes
348 * @return string HTML
349 */
350 public static function label( $label, $id, $attribs=array() ) {
351 $a = array( 'for' => $id );
352 if( isset( $attribs['class'] ) ){
353 $a['class'] = $attribs['class'];
354 }
355 return self::element( 'label', $a, $label );
356 }
357
358 /**
359 * Convenience function to build an HTML text input field with a label
360 * @param $label text of the label
361 * @param $name value of the name attribute
362 * @param $id id of the input
363 * @param $size value of the size attribute
364 * @param $value value of the value attribute
365 * @param $attribs other attributes
366 * @return string HTML
367 */
368 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
369 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
370 return $label . '&#160;' . $input;
371 }
372
373 /**
374 * Same as Xml::inputLabel() but return input and label in an array
375 */
376 public static function inputLabelSep( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
377 return array(
378 Xml::label( $label, $id, $attribs ),
379 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
380 );
381 }
382
383 /**
384 * Convenience function to build an HTML checkbox with a label
385 * @return string HTML
386 */
387 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
388 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
389 '&#160;' .
390 self::label( $label, $id, $attribs );
391 }
392
393 /**
394 * Convenience function to build an HTML radio button with a label
395 * @return string HTML
396 */
397 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
398 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
399 '&#160;' .
400 self::label( $label, $id, $attribs );
401 }
402
403 /**
404 * Convenience function to build an HTML submit button
405 * @param $value String: label text for the button
406 * @param $attribs Array: optional custom attributes
407 * @return string HTML
408 */
409 public static function submitButton( $value, $attribs=array() ) {
410 return Html::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
411 }
412
413 /**
414 * @deprecated Synonymous to Html::hidden()
415 */
416 public static function hidden( $name, $value, $attribs = array() ) {
417 return Html::hidden( $name, $value, $attribs );
418 }
419
420 /**
421 * Convenience function to build an HTML drop-down list item.
422 * @param $text String: text for this item
423 * @param $value String: form submission value; if empty, use text
424 * @param $selected boolean: if true, will be the default selected item
425 * @param $attribs array: optional additional HTML attributes
426 * @return string HTML
427 */
428 public static function option( $text, $value=null, $selected=false,
429 $attribs=array() ) {
430 if( !is_null( $value ) ) {
431 $attribs['value'] = $value;
432 }
433 if( $selected ) {
434 $attribs['selected'] = 'selected';
435 }
436 return self::element( 'option', $attribs, $text );
437 }
438
439 /**
440 * Build a drop-down box from a textual list.
441 *
442 * @param $name Mixed: Name and id for the drop-down
443 * @param $class Mixed: CSS classes for the drop-down
444 * @param $other Mixed: Text for the "Other reasons" option
445 * @param $list Mixed: Correctly formatted text to be used to generate the options
446 * @param $selected Mixed: Option which should be pre-selected
447 * @param $tabindex Mixed: Value of the tabindex attribute
448 * @return string
449 */
450 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = Null ) {
451 $options = '';
452 $optgroup = false;
453
454 $options = self::option( $other, 'other', $selected === 'other' );
455
456 foreach ( explode( "\n", $list ) as $option) {
457 $value = trim( $option );
458 if ( $value == '' ) {
459 continue;
460 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
461 // A new group is starting ...
462 $value = trim( substr( $value, 1 ) );
463 if( $optgroup ) $options .= self::closeElement('optgroup');
464 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
465 $optgroup = true;
466 } elseif ( substr( $value, 0, 2) == '**' ) {
467 // groupmember
468 $value = trim( substr( $value, 2 ) );
469 $options .= self::option( $value, $value, $selected === $value );
470 } else {
471 // groupless reason list
472 if( $optgroup ) $options .= self::closeElement('optgroup');
473 $options .= self::option( $value, $value, $selected === $value );
474 $optgroup = false;
475 }
476 }
477 if( $optgroup ) $options .= self::closeElement('optgroup');
478
479 $attribs = array();
480 if( $name ) {
481 $attribs['id'] = $name;
482 $attribs['name'] = $name;
483 }
484 if( $class ) {
485 $attribs['class'] = $class;
486 }
487 if( $tabindex ) {
488 $attribs['tabindex'] = $tabindex;
489 }
490 return Xml::openElement( 'select', $attribs )
491 . "\n"
492 . $options
493 . "\n"
494 . Xml::closeElement( 'select' );
495 }
496
497 /**
498 * Shortcut for creating fieldsets.
499 *
500 * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
501 * @param $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
502 * @param $attribs Any attributes to fieldset-element.
503 */
504 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
505 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
506 if ( $legend ) {
507 $s .= Xml::element( 'legend', null, $legend ) . "\n";
508 }
509 if ( $content !== false ) {
510 $s .= $content . "\n";
511 $s .= Xml::closeElement( 'fieldset' ) . "\n";
512 }
513
514 return $s;
515 }
516
517 /**
518 * Shortcut for creating textareas.
519 *
520 * @param $name The 'name' for the textarea
521 * @param $content Content for the textarea
522 * @param $cols The number of columns for the textarea
523 * @param $rows The number of rows for the textarea
524 * @param $attribs Any other attributes for the textarea
525 */
526 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
527 return self::element( 'textarea',
528 array( 'name' => $name,
529 'id' => $name,
530 'cols' => $cols,
531 'rows' => $rows
532 ) + $attribs,
533 $content, false );
534 }
535
536 /**
537 * Returns an escaped string suitable for inclusion in a string literal
538 * for JavaScript source code.
539 * Illegal control characters are assumed not to be present.
540 *
541 * @param $string String to escape
542 * @return String
543 */
544 public static function escapeJsString( $string ) {
545 // See ECMA 262 section 7.8.4 for string literal format
546 $pairs = array(
547 "\\" => "\\\\",
548 "\"" => "\\\"",
549 '\'' => '\\\'',
550 "\n" => "\\n",
551 "\r" => "\\r",
552
553 # To avoid closing the element or CDATA section
554 "<" => "\\x3c",
555 ">" => "\\x3e",
556
557 # To avoid any complaints about bad entity refs
558 "&" => "\\x26",
559
560 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
561 # Encode certain Unicode formatting chars so affected
562 # versions of Gecko don't misinterpret our strings;
563 # this is a common problem with Farsi text.
564 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
565 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
566 );
567 return strtr( $string, $pairs );
568 }
569
570 /**
571 * Encode a variable of unknown type to JavaScript.
572 * Arrays are converted to JS arrays, objects are converted to JS associative
573 * arrays (objects). So cast your PHP associative arrays to objects before
574 * passing them to here.
575 */
576 public static function encodeJsVar( $value ) {
577 if ( is_bool( $value ) ) {
578 $s = $value ? 'true' : 'false';
579 } elseif ( is_null( $value ) ) {
580 $s = 'null';
581 } elseif ( is_int( $value ) ) {
582 $s = $value;
583 } elseif ( is_array( $value ) && // Make sure it's not associative.
584 array_keys($value) === range( 0, count($value) - 1 ) ||
585 count($value) == 0
586 ) {
587 $s = '[';
588 foreach ( $value as $elt ) {
589 if ( $s != '[' ) {
590 $s .= ', ';
591 }
592 $s .= self::encodeJsVar( $elt );
593 }
594 $s .= ']';
595 } elseif ( is_object( $value ) || is_array( $value ) ) {
596 // Objects and associative arrays
597 $s = '{';
598 foreach ( (array)$value as $name => $elt ) {
599 if ( $s != '{' ) {
600 $s .= ', ';
601 }
602 $s .= '"' . self::escapeJsString( $name ) . '": ' .
603 self::encodeJsVar( $elt );
604 }
605 $s .= '}';
606 } else {
607 $s = '"' . self::escapeJsString( $value ) . '"';
608 }
609 return $s;
610 }
611
612
613 /**
614 * Check if a string is well-formed XML.
615 * Must include the surrounding tag.
616 *
617 * @param $text String: string to test.
618 * @return bool
619 *
620 * @todo Error position reporting return
621 */
622 public static function isWellFormed( $text ) {
623 $parser = xml_parser_create( "UTF-8" );
624
625 # case folding violates XML standard, turn it off
626 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
627
628 if( !xml_parse( $parser, $text, true ) ) {
629 //$err = xml_error_string( xml_get_error_code( $parser ) );
630 //$position = xml_get_current_byte_index( $parser );
631 //$fragment = $this->extractFragment( $html, $position );
632 //$this->mXmlError = "$err at byte $position:\n$fragment";
633 xml_parser_free( $parser );
634 return false;
635 }
636 xml_parser_free( $parser );
637 return true;
638 }
639
640 /**
641 * Check if a string is a well-formed XML fragment.
642 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
643 * and can use HTML named entities.
644 *
645 * @param $text String:
646 * @return bool
647 */
648 public static function isWellFormedXmlFragment( $text ) {
649 $html =
650 Sanitizer::hackDocType() .
651 '<html>' .
652 $text .
653 '</html>';
654 return Xml::isWellFormed( $html );
655 }
656
657 /**
658 * Replace " > and < with their respective HTML entities ( &quot;,
659 * &gt;, &lt;)
660 *
661 * @param $in String: text that might contain HTML tags.
662 * @return string Escaped string
663 */
664 public static function escapeTagsOnly( $in ) {
665 return str_replace(
666 array( '"', '>', '<' ),
667 array( '&quot;', '&gt;', '&lt;' ),
668 $in );
669 }
670
671 /**
672 * Generate a form (without the opening form element).
673 * Output optionally includes a submit button.
674 * @param $fields Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
675 * @param $submitLabel A message containing a label for the submit button.
676 * @return string HTML form.
677 */
678 public static function buildForm( $fields, $submitLabel = null ) {
679 $form = '';
680 $form .= "<table><tbody>";
681
682 foreach( $fields as $labelmsg => $input ) {
683 $id = "mw-$labelmsg";
684 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
685 $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
686 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
687 $form .= Xml::closeElement( 'tr' );
688 }
689
690 if( $submitLabel ) {
691 $form .= Xml::openElement( 'tr' );
692 $form .= Xml::tags( 'td', array(), '' );
693 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( wfMsg( $submitLabel ) ) . Xml::closeElement( 'td' );
694 $form .= Xml::closeElement( 'tr' );
695 }
696
697 $form .= "</tbody></table>";
698
699
700 return $form;
701 }
702
703 /**
704 * Build a table of data
705 * @param $rows An array of arrays of strings, each to be a row in a table
706 * @param $attribs An array of attributes to apply to the table tag [optional]
707 * @param $headers An array of strings to use as table headers [optional]
708 * @return string
709 */
710 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
711 $s = Xml::openElement( 'table', $attribs );
712 if ( is_array( $headers ) ) {
713 foreach( $headers as $id => $header ) {
714 $attribs = array();
715 if ( is_string( $id ) ) $attribs['id'] = $id;
716 $s .= Xml::element( 'th', $attribs, $header );
717 }
718 }
719 foreach( $rows as $id => $row ) {
720 $attribs = array();
721 if ( is_string( $id ) ) $attribs['id'] = $id;
722 $s .= Xml::buildTableRow( $attribs, $row );
723 }
724 $s .= Xml::closeElement( 'table' );
725 return $s;
726 }
727
728 /**
729 * Build a row for a table
730 * @param $attribs An array of attributes to apply to the tr tag
731 * @param $cells An array of strings to put in <td>
732 * @return string
733 */
734 public static function buildTableRow( $attribs, $cells ) {
735 $s = Xml::openElement( 'tr', $attribs );
736 foreach( $cells as $id => $cell ) {
737 $attribs = array();
738 if ( is_string( $id ) ) $attribs['id'] = $id;
739 $s .= Xml::element( 'td', $attribs, $cell );
740 }
741 $s .= Xml::closeElement( 'tr' );
742 return $s;
743 }
744 }
745
746 class XmlSelect {
747 protected $options = array();
748 protected $default = false;
749 protected $attributes = array();
750
751 public function __construct( $name = false, $id = false, $default = false ) {
752 if ( $name ) $this->setAttribute( 'name', $name );
753 if ( $id ) $this->setAttribute( 'id', $id );
754 if ( $default !== false ) $this->default = $default;
755 }
756
757 public function setDefault( $default ) {
758 $this->default = $default;
759 }
760
761 public function setAttribute( $name, $value ) {
762 $this->attributes[$name] = $value;
763 }
764
765 public function getAttribute( $name ) {
766 if ( isset($this->attributes[$name]) ) {
767 return $this->attributes[$name];
768 } else {
769 return null;
770 }
771 }
772
773 public function addOption( $name, $value = false ) {
774 // Stab stab stab
775 $value = ($value !== false) ? $value : $name;
776 $this->options[] = Xml::option( $name, $value, $value === $this->default );
777 }
778
779 // This accepts an array of form
780 // label => value
781 // label => ( label => value, label => value )
782 public function addOptions( $options ) {
783 $this->options[] = trim(self::formatOptions( $options, $this->default ));
784 }
785
786 // This accepts an array of form
787 // label => value
788 // label => ( label => value, label => value )
789 static function formatOptions( $options, $default = false ) {
790 $data = '';
791 foreach( $options as $label => $value ) {
792 if ( is_array( $value ) ) {
793 $contents = self::formatOptions( $value, $default );
794 $data .= Xml::tags( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
795 } else {
796 $data .= Xml::option( $label, $value, $value === $default ) . "\n";
797 }
798 }
799
800 return $data;
801 }
802
803 public function getHTML() {
804 return Xml::tags( 'select', $this->attributes, implode( "\n", $this->options ) );
805 }
806
807 }