Improve documentation
[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 * @return null|string
44 */
45 public static function expandAttributes( $attribs ) {
46 $out = '';
47 if( is_null( $attribs ) ) {
48 return null;
49 } elseif( is_array( $attribs ) ) {
50 foreach( $attribs as $name => $val ) {
51 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
52 }
53 return $out;
54 } else {
55 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
56 }
57 }
58
59 /**
60 * Format an XML element as with self::element(), but run text through the
61 * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
62 * is passed.
63 *
64 * @param $element String:
65 * @param $attribs Array: Name=>value pairs. Values will be escaped.
66 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
67 * @return string
68 */
69 public static function elementClean( $element, $attribs = array(), $contents = '') {
70 global $wgContLang;
71 if( $attribs ) {
72 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
73 }
74 if( $contents ) {
75 wfProfileIn( __METHOD__ . '-norm' );
76 $contents = $wgContLang->normalize( $contents );
77 wfProfileOut( __METHOD__ . '-norm' );
78 }
79 return self::element( $element, $attribs, $contents );
80 }
81
82 /**
83 * This opens an XML element
84 *
85 * @param $element String name of the element
86 * @param $attribs array of attributes, see Xml::expandAttributes()
87 * @return string
88 */
89 public static function openElement( $element, $attribs = null ) {
90 return '<' . $element . self::expandAttributes( $attribs ) . '>';
91 }
92
93 /**
94 * Shortcut to close an XML element
95 * @param $element String element name
96 * @return string
97 */
98 public static function closeElement( $element ) { return "</$element>"; }
99
100 /**
101 * Same as Xml::element(), but does not escape contents. Handy when the
102 * content you have is already valid xml.
103 *
104 * @param $element String element name
105 * @param $attribs array of attributes
106 * @param $contents String content of the element
107 * @return string
108 */
109 public static function tags( $element, $attribs = null, $contents ) {
110 return self::openElement( $element, $attribs ) . $contents . "</$element>";
111 }
112
113 /**
114 * Build a drop-down box for selecting a namespace
115 *
116 * @param $selected Mixed: Namespace which should be pre-selected
117 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
118 * @param $element_name String: value of the "name" attribute of the select tag
119 * @param $label String: optional label to add to the field
120 * @return string
121 * @deprecated since 1.19
122 */
123 public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
124 wfDeprecated( __METHOD__, '1.19' );
125 return Html::namespaceSelector( array(
126 'selected' => $selected,
127 'all' => $all,
128 'label' => $label,
129 ), array(
130 'name' => $element_name,
131 'id' => 'namespace',
132 'class' => 'namespaceselector',
133 ) );
134 }
135
136 /**
137 * Create a date selector
138 *
139 * @param $selected Mixed: the month which should be selected, default ''
140 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
141 * @param $id String: Element identifier
142 * @return String: Html string containing the month selector
143 */
144 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
145 global $wgLang;
146 $options = array();
147 if( is_null( $selected ) )
148 $selected = '';
149 if( !is_null( $allmonths ) )
150 $options[] = self::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
151 for( $i = 1; $i < 13; $i++ )
152 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
153 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
154 . implode( "\n", $options )
155 . self::closeElement( 'select' );
156 }
157
158 /**
159 * @param $year Integer
160 * @param $month Integer
161 * @return string Formatted HTML
162 */
163 public static function dateMenu( $year, $month ) {
164 # Offset overrides year/month selection
165 if( $month && $month !== -1 ) {
166 $encMonth = intval( $month );
167 } else {
168 $encMonth = '';
169 }
170 if( $year ) {
171 $encYear = intval( $year );
172 } elseif( $encMonth ) {
173 $thisMonth = intval( gmdate( 'n' ) );
174 $thisYear = intval( gmdate( 'Y' ) );
175 if( intval($encMonth) > $thisMonth ) {
176 $thisYear--;
177 }
178 $encYear = $thisYear;
179 } else {
180 $encYear = '';
181 }
182 return Xml::label( wfMsg( 'year' ), 'year' ) . ' '.
183 Xml::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) . ' '.
184 Xml::label( wfMsg( 'month' ), 'month' ) . ' '.
185 Xml::monthSelector( $encMonth, -1 );
186 }
187
188 /**
189 * Construct a language selector appropriate for use in a form or preferences
190 *
191 * @param string $selected The language code of the selected language
192 * @param boolean $customisedOnly If true only languages which have some content are listed
193 * @param string $language The ISO code of the language to display the select list in (optional)
194 * @return array containing 2 items: label HTML and select list HTML
195 */
196 public static function languageSelector( $selected, $customisedOnly = true, $language = null ) {
197 global $wgLanguageCode;
198
199 // TODO: This should be replaced with a hook or something, from r107002
200 // If a specific language was requested and CLDR is installed, use it
201 if ( $language && is_callable( array( 'LanguageNames', 'getNames' ) ) ) {
202 if ( $customisedOnly ) {
203 $listType = LanguageNames::LIST_MW_SUPPORTED; // Only pull names that have localisation in MediaWiki
204 } else {
205 $listType = LanguageNames::LIST_MW; // Pull all languages that are in Names.php
206 }
207 // Retrieve the list of languages in the requested language (via CLDR)
208 $languages = LanguageNames::getNames(
209 $language, // Code of the requested language
210 LanguageNames::FALLBACK_NORMAL, // Use fallback chain
211 $listType
212 );
213 } else {
214 $languages = Language::getLanguageNames( $customisedOnly );
215 }
216
217 // Make sure the site language is in the list; a custom language code might not have a
218 // defined name...
219 if( !array_key_exists( $wgLanguageCode, $languages ) ) {
220 $languages[$wgLanguageCode] = $wgLanguageCode;
221 }
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 : $wgLanguageCode;
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 String content of the element, will be escaped
249 * @param $class String class name of the span element
250 * @param $attribs array 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 string content of the element, will be escaped
260 * @param $class string class name of the span element
261 * @param $tag string element name
262 * @param $attribs array 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 String value of the name attribute
272 * @param $size int value of the size attribute
273 * @param $value mixed value of the value attribute
274 * @param $attribs array 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 string value of the name attribute
294 * @param $size int value of the size attribute
295 * @param $value mixed value of the value attribute
296 * @param $attribs array 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 *
306 * @param $name string
307 * @param $present bool
308 *
309 * @return array
310 */
311 public static function attrib( $name, $present = true ) {
312 return $present ? array( $name => $name ) : array();
313 }
314
315 /**
316 * Convenience function to build an HTML checkbox
317 * @param $name String value of the name attribute
318 * @param $checked Bool Whether the checkbox is checked or not
319 * @param $attribs Array other attributes
320 * @return string HTML
321 */
322 public static function check( $name, $checked = false, $attribs=array() ) {
323 return self::element( 'input', array_merge(
324 array(
325 'name' => $name,
326 'type' => 'checkbox',
327 'value' => 1 ),
328 self::attrib( 'checked', $checked ),
329 $attribs ) );
330 }
331
332 /**
333 * Convenience function to build an HTML radio button
334 * @param $name String value of the name attribute
335 * @param $value String value of the value attribute
336 * @param $checked Bool Whether the checkbox is checked or not
337 * @param $attribs Array other attributes
338 * @return string HTML
339 */
340 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
341 return self::element( 'input', array(
342 'name' => $name,
343 'type' => 'radio',
344 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
345 }
346
347 /**
348 * Convenience function to build an HTML form label
349 * @param $label String text of the label
350 * @param $id
351 * @param $attribs Array an attribute array. This will usuall be
352 * the same array as is passed to the corresponding input element,
353 * so this function will cherry-pick appropriate attributes to
354 * apply to the label as well; only class and title are applied.
355 * @return string HTML
356 */
357 public static function label( $label, $id, $attribs = array() ) {
358 $a = array( 'for' => $id );
359
360 # FIXME avoid copy pasting below:
361 if( isset( $attribs['class'] ) ){
362 $a['class'] = $attribs['class'];
363 }
364 if( isset( $attribs['title'] ) ){
365 $a['title'] = $attribs['title'];
366 }
367
368 return self::element( 'label', $a, $label );
369 }
370
371 /**
372 * Convenience function to build an HTML text input field with a label
373 * @param $label String text of the label
374 * @param $name String value of the name attribute
375 * @param $id String id of the input
376 * @param $size Int|Bool value of the size attribute
377 * @param $value String|Bool value of the value attribute
378 * @param $attribs array other attributes
379 * @return string HTML
380 */
381 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs = array() ) {
382 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
383 return $label . '&#160;' . $input;
384 }
385
386 /**
387 * Same as Xml::inputLabel() but return input and label in an array
388 *
389 * @param $label String
390 * @param $name String
391 * @param $id String
392 * @param $size Int|Bool
393 * @param $value String|Bool
394 * @param $attribs array
395 *
396 * @return array
397 */
398 public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
399 return array(
400 Xml::label( $label, $id, $attribs ),
401 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
402 );
403 }
404
405 /**
406 * Convenience function to build an HTML checkbox with a label
407 *
408 * @param $label
409 * @param $name
410 * @param $id
411 * @param $checked bool
412 * @param $attribs array
413 *
414 * @return string HTML
415 */
416 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
417 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
418 '&#160;' .
419 self::label( $label, $id, $attribs );
420 }
421
422 /**
423 * Convenience function to build an HTML radio button with a label
424 *
425 * @param $label
426 * @param $name
427 * @param $value
428 * @param $id
429 * @param $checked bool
430 * @param $attribs array
431 *
432 * @return string HTML
433 */
434 public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
435 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
436 '&#160;' .
437 self::label( $label, $id, $attribs );
438 }
439
440 /**
441 * Convenience function to build an HTML submit button
442 * @param $value String: label text for the button
443 * @param $attribs Array: optional custom attributes
444 * @return string HTML
445 */
446 public static function submitButton( $value, $attribs = array() ) {
447 return Html::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
448 }
449
450 /**
451 * Convenience function to build an HTML drop-down list item.
452 * @param $text String: text for this item
453 * @param $value String: form submission value; if empty, use text
454 * @param $selected boolean: if true, will be the default selected item
455 * @param $attribs array: optional additional HTML attributes
456 * @return string HTML
457 */
458 public static function option( $text, $value=null, $selected = false,
459 $attribs = array() ) {
460 if( !is_null( $value ) ) {
461 $attribs['value'] = $value;
462 }
463 if( $selected ) {
464 $attribs['selected'] = 'selected';
465 }
466 return Html::element( 'option', $attribs, $text );
467 }
468
469 /**
470 * Build a drop-down box from a textual list.
471 *
472 * @param $name Mixed: Name and id for the drop-down
473 * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
474 * @param $other Mixed: Text for the "Other reasons" option
475 * @param $selected Mixed: Option which should be pre-selected
476 * @param $class Mixed: CSS classes for the drop-down
477 * @param $tabindex Mixed: Value of the tabindex attribute
478 * @return string
479 */
480 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
481 $optgroup = false;
482
483 $options = self::option( $other, 'other', $selected === 'other' );
484
485 foreach ( explode( "\n", $list ) as $option) {
486 $value = trim( $option );
487 if ( $value == '' ) {
488 continue;
489 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
490 // A new group is starting ...
491 $value = trim( substr( $value, 1 ) );
492 if( $optgroup ) $options .= self::closeElement('optgroup');
493 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
494 $optgroup = true;
495 } elseif ( substr( $value, 0, 2) == '**' ) {
496 // groupmember
497 $value = trim( substr( $value, 2 ) );
498 $options .= self::option( $value, $value, $selected === $value );
499 } else {
500 // groupless reason list
501 if( $optgroup ) $options .= self::closeElement('optgroup');
502 $options .= self::option( $value, $value, $selected === $value );
503 $optgroup = false;
504 }
505 }
506
507 if( $optgroup ) $options .= self::closeElement('optgroup');
508
509 $attribs = array();
510
511 if( $name ) {
512 $attribs['id'] = $name;
513 $attribs['name'] = $name;
514 }
515
516 if( $class ) {
517 $attribs['class'] = $class;
518 }
519
520 if( $tabindex ) {
521 $attribs['tabindex'] = $tabindex;
522 }
523
524 return Xml::openElement( 'select', $attribs )
525 . "\n"
526 . $options
527 . "\n"
528 . Xml::closeElement( 'select' );
529 }
530
531 /**
532 * Shortcut for creating fieldsets.
533 *
534 * @param $legend string|bool Legend of the fieldset. If evaluates to false, legend is not added.
535 * @param $content string Pre-escaped content for the fieldset. If false, only open fieldset is returned.
536 * @param $attribs array Any attributes to fieldset-element.
537 *
538 * @return string
539 */
540 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
541 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
542
543 if ( $legend ) {
544 $s .= Xml::element( 'legend', null, $legend ) . "\n";
545 }
546
547 if ( $content !== false ) {
548 $s .= $content . "\n";
549 $s .= Xml::closeElement( 'fieldset' ) . "\n";
550 }
551
552 return $s;
553 }
554
555 /**
556 * Shortcut for creating textareas.
557 *
558 * @param $name string The 'name' for the textarea
559 * @param $content string Content for the textarea
560 * @param $cols int The number of columns for the textarea
561 * @param $rows int The number of rows for the textarea
562 * @param $attribs array Any other attributes for the textarea
563 *
564 * @return string
565 */
566 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
567 return self::element( 'textarea',
568 array( 'name' => $name,
569 'id' => $name,
570 'cols' => $cols,
571 'rows' => $rows
572 ) + $attribs,
573 $content, false );
574 }
575
576 /**
577 * Returns an escaped string suitable for inclusion in a string literal
578 * for JavaScript source code.
579 * Illegal control characters are assumed not to be present.
580 *
581 * @param $string String to escape
582 * @return String
583 */
584 public static function escapeJsString( $string ) {
585 // See ECMA 262 section 7.8.4 for string literal format
586 $pairs = array(
587 "\\" => "\\\\",
588 "\"" => "\\\"",
589 '\'' => '\\\'',
590 "\n" => "\\n",
591 "\r" => "\\r",
592
593 # To avoid closing the element or CDATA section
594 "<" => "\\x3c",
595 ">" => "\\x3e",
596
597 # To avoid any complaints about bad entity refs
598 "&" => "\\x26",
599
600 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
601 # Encode certain Unicode formatting chars so affected
602 # versions of Gecko don't misinterpret our strings;
603 # this is a common problem with Farsi text.
604 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
605 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
606 );
607
608 return strtr( $string, $pairs );
609 }
610
611 /**
612 * Encode a variable of unknown type to JavaScript.
613 * Arrays are converted to JS arrays, objects are converted to JS associative
614 * arrays (objects). So cast your PHP associative arrays to objects before
615 * passing them to here.
616 *
617 * @param $value
618 *
619 * @return string
620 */
621 public static function encodeJsVar( $value ) {
622 if ( is_bool( $value ) ) {
623 $s = $value ? 'true' : 'false';
624 } elseif ( is_null( $value ) ) {
625 $s = 'null';
626 } elseif ( is_int( $value ) || is_float( $value ) ) {
627 $s = strval($value);
628 } elseif ( is_array( $value ) && // Make sure it's not associative.
629 array_keys($value) === range( 0, count($value) - 1 ) ||
630 count($value) == 0
631 ) {
632 $s = '[';
633 foreach ( $value as $elt ) {
634 if ( $s != '[' ) {
635 $s .= ',';
636 }
637 $s .= self::encodeJsVar( $elt );
638 }
639 $s .= ']';
640 } elseif ( $value instanceof XmlJsCode ) {
641 $s = $value->value;
642 } elseif ( is_object( $value ) || is_array( $value ) ) {
643 // Objects and associative arrays
644 $s = '{';
645 foreach ( (array)$value as $name => $elt ) {
646 if ( $s != '{' ) {
647 $s .= ',';
648 }
649
650 $s .= '"' . self::escapeJsString( $name ) . '":' .
651 self::encodeJsVar( $elt );
652 }
653 $s .= '}';
654 } else {
655 $s = '"' . self::escapeJsString( $value ) . '"';
656 }
657 return $s;
658 }
659
660 /**
661 * Create a call to a JavaScript function. The supplied arguments will be
662 * encoded using Xml::encodeJsVar().
663 *
664 * @param $name String The name of the function to call, or a JavaScript expression
665 * which evaluates to a function object which is called.
666 * @param $args Array of arguments to pass to the function.
667 *
668 * @since 1.17
669 *
670 * @return string
671 */
672 public static function encodeJsCall( $name, $args ) {
673 $s = "$name(";
674 $first = true;
675
676 foreach ( $args as $arg ) {
677 if ( $first ) {
678 $first = false;
679 } else {
680 $s .= ', ';
681 }
682
683 $s .= Xml::encodeJsVar( $arg );
684 }
685
686 $s .= ");\n";
687
688 return $s;
689 }
690
691 /**
692 * Check if a string is well-formed XML.
693 * Must include the surrounding tag.
694 *
695 * @param $text String: string to test.
696 * @return bool
697 *
698 * @todo Error position reporting return
699 */
700 public static function isWellFormed( $text ) {
701 $parser = xml_parser_create( "UTF-8" );
702
703 # case folding violates XML standard, turn it off
704 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
705
706 if( !xml_parse( $parser, $text, true ) ) {
707 //$err = xml_error_string( xml_get_error_code( $parser ) );
708 //$position = xml_get_current_byte_index( $parser );
709 //$fragment = $this->extractFragment( $html, $position );
710 //$this->mXmlError = "$err at byte $position:\n$fragment";
711 xml_parser_free( $parser );
712 return false;
713 }
714
715 xml_parser_free( $parser );
716
717 return true;
718 }
719
720 /**
721 * Check if a string is a well-formed XML fragment.
722 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
723 * and can use HTML named entities.
724 *
725 * @param $text String:
726 * @return bool
727 */
728 public static function isWellFormedXmlFragment( $text ) {
729 $html =
730 Sanitizer::hackDocType() .
731 '<html>' .
732 $text .
733 '</html>';
734
735 return Xml::isWellFormed( $html );
736 }
737
738 /**
739 * Replace " > and < with their respective HTML entities ( &quot;,
740 * &gt;, &lt;)
741 *
742 * @param $in String: text that might contain HTML tags.
743 * @return string Escaped string
744 */
745 public static function escapeTagsOnly( $in ) {
746 return str_replace(
747 array( '"', '>', '<' ),
748 array( '&quot;', '&gt;', '&lt;' ),
749 $in );
750 }
751
752 /**
753 * Generate a form (without the opening form element).
754 * Output optionally includes a submit button.
755 * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
756 * @param $submitLabel String A message containing a label for the submit button.
757 * @return string HTML form.
758 */
759 public static function buildForm( $fields, $submitLabel = null ) {
760 $form = '';
761 $form .= "<table><tbody>";
762
763 foreach( $fields as $labelmsg => $input ) {
764 $id = "mw-$labelmsg";
765 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
766 $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
767 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
768 $form .= Xml::closeElement( 'tr' );
769 }
770
771 if( $submitLabel ) {
772 $form .= Xml::openElement( 'tr' );
773 $form .= Xml::tags( 'td', array(), '' );
774 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( wfMsg( $submitLabel ) ) . Xml::closeElement( 'td' );
775 $form .= Xml::closeElement( 'tr' );
776 }
777
778 $form .= "</tbody></table>";
779
780 return $form;
781 }
782
783 /**
784 * Build a table of data
785 * @param $rows array An array of arrays of strings, each to be a row in a table
786 * @param $attribs array An array of attributes to apply to the table tag [optional]
787 * @param $headers array An array of strings to use as table headers [optional]
788 * @return string
789 */
790 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
791 $s = Xml::openElement( 'table', $attribs );
792
793 if ( is_array( $headers ) ) {
794 $s .= Xml::openElement( 'thead', $attribs );
795
796 foreach( $headers as $id => $header ) {
797 $attribs = array();
798
799 if ( is_string( $id ) ) {
800 $attribs['id'] = $id;
801 }
802
803 $s .= Xml::element( 'th', $attribs, $header );
804 }
805 $s .= Xml::closeElement( 'thead' );
806 }
807
808 foreach( $rows as $id => $row ) {
809 $attribs = array();
810
811 if ( is_string( $id ) ) {
812 $attribs['id'] = $id;
813 }
814
815 $s .= Xml::buildTableRow( $attribs, $row );
816 }
817
818 $s .= Xml::closeElement( 'table' );
819
820 return $s;
821 }
822
823 /**
824 * Build a row for a table
825 * @param $attribs array An array of attributes to apply to the tr tag
826 * @param $cells array An array of strings to put in <td>
827 * @return string
828 */
829 public static function buildTableRow( $attribs, $cells ) {
830 $s = Xml::openElement( 'tr', $attribs );
831
832 foreach( $cells as $id => $cell ) {
833
834 $attribs = array();
835
836 if ( is_string( $id ) ) {
837 $attribs['id'] = $id;
838 }
839
840 $s .= Xml::element( 'td', $attribs, $cell );
841 }
842
843 $s .= Xml::closeElement( 'tr' );
844
845 return $s;
846 }
847 }
848
849 class XmlSelect {
850 protected $options = array();
851 protected $default = false;
852 protected $attributes = array();
853
854 public function __construct( $name = false, $id = false, $default = false ) {
855 if ( $name ) {
856 $this->setAttribute( 'name', $name );
857 }
858
859 if ( $id ) {
860 $this->setAttribute( 'id', $id );
861 }
862
863 if ( $default !== false ) {
864 $this->default = $default;
865 }
866 }
867
868 /**
869 * @param $default
870 */
871 public function setDefault( $default ) {
872 $this->default = $default;
873 }
874
875 /**
876 * @param $name string
877 * @param $value
878 */
879 public function setAttribute( $name, $value ) {
880 $this->attributes[$name] = $value;
881 }
882
883 /**
884 * @param $name
885 * @return array|null
886 */
887 public function getAttribute( $name ) {
888 if ( isset( $this->attributes[$name] ) ) {
889 return $this->attributes[$name];
890 } else {
891 return null;
892 }
893 }
894
895 /**
896 * @param $name
897 * @param $value bool
898 */
899 public function addOption( $name, $value = false ) {
900 // Stab stab stab
901 $value = ($value !== false) ? $value : $name;
902
903 $this->options[] = array( $name => $value );
904 }
905
906 /**
907 * This accepts an array of form
908 * label => value
909 * label => ( label => value, label => value )
910 *
911 * @param $options
912 */
913 public function addOptions( $options ) {
914 $this->options[] = $options;
915 }
916
917 /**
918 * This accepts an array of form
919 * label => value
920 * label => ( label => value, label => value )
921 *
922 * @param $options
923 * @param bool $default
924 * @return string
925 */
926 static function formatOptions( $options, $default = false ) {
927 $data = '';
928
929 foreach( $options as $label => $value ) {
930 if ( is_array( $value ) ) {
931 $contents = self::formatOptions( $value, $default );
932 $data .= Html::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
933 } else {
934 $data .= Xml::option( $label, $value, $value === $default ) . "\n";
935 }
936 }
937
938 return $data;
939 }
940
941 /**
942 * @return string
943 */
944 public function getHTML() {
945 $contents = '';
946
947 foreach ( $this->options as $options ) {
948 $contents .= self::formatOptions( $options, $this->default );
949 }
950
951 return Html::rawElement( 'select', $this->attributes, rtrim( $contents ) );
952 }
953 }
954
955 /**
956 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
957 * interpret a given string as being a JavaScript expression, instead of string
958 * data.
959 *
960 * Example:
961 *
962 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
963 *
964 * Returns "a + b".
965 * @since 1.17
966 */
967 class XmlJsCode {
968 public $value;
969
970 function __construct( $value ) {
971 $this->value = $value;
972 }
973 }