More return 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 // If a specific language was requested and CLDR is installed, use it
200 if ( $language && is_callable( array( 'LanguageNames', 'getNames' ) ) ) {
201 if ( $customisedOnly ) {
202 $listType = LanguageNames::LIST_MW_SUPPORTED; // Only pull names that have localisation in MediaWiki
203 } else {
204 $listType = LanguageNames::LIST_MW; // Pull all languages that are in Names.php
205 }
206 // Retrieve the list of languages in the requested language (via CLDR)
207 $languages = LanguageNames::getNames(
208 $language, // Code of the requested language
209 LanguageNames::FALLBACK_NORMAL, // Use fallback chain
210 $listType
211 );
212 } else {
213 $languages = Language::getLanguageNames( $customisedOnly );
214 }
215
216 // Make sure the site language is in the list; a custom language code might not have a
217 // defined name...
218 if( !array_key_exists( $wgLanguageCode, $languages ) ) {
219 $languages[$wgLanguageCode] = $wgLanguageCode;
220 }
221
222 ksort( $languages );
223
224 /**
225 * If a bogus value is set, default to the content language.
226 * Otherwise, no default is selected and the user ends up
227 * with an Afrikaans interface since it's first in the list.
228 */
229 $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
230 $options = "\n";
231 foreach( $languages as $code => $name ) {
232 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
233 }
234
235 return array(
236 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
237 Xml::tags( 'select',
238 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
239 $options
240 )
241 );
242
243 }
244
245 /**
246 * Shortcut to make a span element
247 * @param $text String content of the element, will be escaped
248 * @param $class String class name of the span element
249 * @param $attribs array other attributes
250 * @return string
251 */
252 public static function span( $text, $class, $attribs = array() ) {
253 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
254 }
255
256 /**
257 * Shortcut to make a specific element with a class attribute
258 * @param $text string content of the element, will be escaped
259 * @param $class string class name of the span element
260 * @param $tag string element name
261 * @param $attribs array other attributes
262 * @return string
263 */
264 public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
265 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
266 }
267
268 /**
269 * Convenience function to build an HTML text input field
270 * @param $name String value of the name attribute
271 * @param $size int value of the size attribute
272 * @param $value mixed value of the value attribute
273 * @param $attribs array other attributes
274 * @return string HTML
275 */
276 public static function input( $name, $size = false, $value = false, $attribs = array() ) {
277 $attributes = array( 'name' => $name );
278
279 if( $size ) {
280 $attributes['size'] = $size;
281 }
282
283 if( $value !== false ) { // maybe 0
284 $attributes['value'] = $value;
285 }
286
287 return self::element( 'input', $attributes + $attribs );
288 }
289
290 /**
291 * Convenience function to build an HTML password input field
292 * @param $name string value of the name attribute
293 * @param $size int value of the size attribute
294 * @param $value mixed value of the value attribute
295 * @param $attribs array other attributes
296 * @return string HTML
297 */
298 public static function password( $name, $size = false, $value = false, $attribs = array() ) {
299 return self::input( $name, $size, $value, array_merge( $attribs, array( 'type' => 'password' ) ) );
300 }
301
302 /**
303 * Internal function for use in checkboxes and radio buttons and such.
304 *
305 * @param $name string
306 * @param $present bool
307 *
308 * @return array
309 */
310 public static function attrib( $name, $present = true ) {
311 return $present ? array( $name => $name ) : array();
312 }
313
314 /**
315 * Convenience function to build an HTML checkbox
316 * @param $name String value of the name attribute
317 * @param $checked Bool Whether the checkbox is checked or not
318 * @param $attribs Array other attributes
319 * @return string HTML
320 */
321 public static function check( $name, $checked = false, $attribs=array() ) {
322 return self::element( 'input', array_merge(
323 array(
324 'name' => $name,
325 'type' => 'checkbox',
326 'value' => 1 ),
327 self::attrib( 'checked', $checked ),
328 $attribs ) );
329 }
330
331 /**
332 * Convenience function to build an HTML radio button
333 * @param $name String value of the name attribute
334 * @param $value String value of the value attribute
335 * @param $checked Bool Whether the checkbox is checked or not
336 * @param $attribs Array other attributes
337 * @return string HTML
338 */
339 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
340 return self::element( 'input', array(
341 'name' => $name,
342 'type' => 'radio',
343 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
344 }
345
346 /**
347 * Convenience function to build an HTML form label
348 * @param $label String text of the label
349 * @param $id
350 * @param $attribs Array an attribute array. This will usuall be
351 * the same array as is passed to the corresponding input element,
352 * so this function will cherry-pick appropriate attributes to
353 * apply to the label as well; only class and title are applied.
354 * @return string HTML
355 */
356 public static function label( $label, $id, $attribs = array() ) {
357 $a = array( 'for' => $id );
358
359 # FIXME avoid copy pasting below:
360 if( isset( $attribs['class'] ) ){
361 $a['class'] = $attribs['class'];
362 }
363 if( isset( $attribs['title'] ) ){
364 $a['title'] = $attribs['title'];
365 }
366
367 return self::element( 'label', $a, $label );
368 }
369
370 /**
371 * Convenience function to build an HTML text input field with a label
372 * @param $label String text of the label
373 * @param $name String value of the name attribute
374 * @param $id String id of the input
375 * @param $size Int|Bool value of the size attribute
376 * @param $value String|Bool value of the value attribute
377 * @param $attribs array other attributes
378 * @return string HTML
379 */
380 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs = array() ) {
381 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
382 return $label . '&#160;' . $input;
383 }
384
385 /**
386 * Same as Xml::inputLabel() but return input and label in an array
387 *
388 * @param $label String
389 * @param $name String
390 * @param $id String
391 * @param $size Int|Bool
392 * @param $value String|Bool
393 * @param $attribs array
394 *
395 * @return array
396 */
397 public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
398 return array(
399 Xml::label( $label, $id, $attribs ),
400 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
401 );
402 }
403
404 /**
405 * Convenience function to build an HTML checkbox with a label
406 *
407 * @param $label
408 * @param $name
409 * @param $id
410 * @param $checked bool
411 * @param $attribs array
412 *
413 * @return string HTML
414 */
415 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
416 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
417 '&#160;' .
418 self::label( $label, $id, $attribs );
419 }
420
421 /**
422 * Convenience function to build an HTML radio button with a label
423 *
424 * @param $label
425 * @param $name
426 * @param $value
427 * @param $id
428 * @param $checked bool
429 * @param $attribs array
430 *
431 * @return string HTML
432 */
433 public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
434 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
435 '&#160;' .
436 self::label( $label, $id, $attribs );
437 }
438
439 /**
440 * Convenience function to build an HTML submit button
441 * @param $value String: label text for the button
442 * @param $attribs Array: optional custom attributes
443 * @return string HTML
444 */
445 public static function submitButton( $value, $attribs = array() ) {
446 return Html::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
447 }
448
449 /**
450 * Convenience function to build an HTML drop-down list item.
451 * @param $text String: text for this item
452 * @param $value String: form submission value; if empty, use text
453 * @param $selected boolean: if true, will be the default selected item
454 * @param $attribs array: optional additional HTML attributes
455 * @return string HTML
456 */
457 public static function option( $text, $value=null, $selected = false,
458 $attribs = array() ) {
459 if( !is_null( $value ) ) {
460 $attribs['value'] = $value;
461 }
462 if( $selected ) {
463 $attribs['selected'] = 'selected';
464 }
465 return Html::element( 'option', $attribs, $text );
466 }
467
468 /**
469 * Build a drop-down box from a textual list.
470 *
471 * @param $name Mixed: Name and id for the drop-down
472 * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
473 * @param $other Mixed: Text for the "Other reasons" option
474 * @param $selected Mixed: Option which should be pre-selected
475 * @param $class Mixed: CSS classes for the drop-down
476 * @param $tabindex Mixed: Value of the tabindex attribute
477 * @return string
478 */
479 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
480 $optgroup = false;
481
482 $options = self::option( $other, 'other', $selected === 'other' );
483
484 foreach ( explode( "\n", $list ) as $option) {
485 $value = trim( $option );
486 if ( $value == '' ) {
487 continue;
488 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
489 // A new group is starting ...
490 $value = trim( substr( $value, 1 ) );
491 if( $optgroup ) $options .= self::closeElement('optgroup');
492 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
493 $optgroup = true;
494 } elseif ( substr( $value, 0, 2) == '**' ) {
495 // groupmember
496 $value = trim( substr( $value, 2 ) );
497 $options .= self::option( $value, $value, $selected === $value );
498 } else {
499 // groupless reason list
500 if( $optgroup ) $options .= self::closeElement('optgroup');
501 $options .= self::option( $value, $value, $selected === $value );
502 $optgroup = false;
503 }
504 }
505
506 if( $optgroup ) $options .= self::closeElement('optgroup');
507
508 $attribs = array();
509
510 if( $name ) {
511 $attribs['id'] = $name;
512 $attribs['name'] = $name;
513 }
514
515 if( $class ) {
516 $attribs['class'] = $class;
517 }
518
519 if( $tabindex ) {
520 $attribs['tabindex'] = $tabindex;
521 }
522
523 return Xml::openElement( 'select', $attribs )
524 . "\n"
525 . $options
526 . "\n"
527 . Xml::closeElement( 'select' );
528 }
529
530 /**
531 * Shortcut for creating fieldsets.
532 *
533 * @param $legend string|bool Legend of the fieldset. If evaluates to false, legend is not added.
534 * @param $content string Pre-escaped content for the fieldset. If false, only open fieldset is returned.
535 * @param $attribs array Any attributes to fieldset-element.
536 *
537 * @return string
538 */
539 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
540 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
541
542 if ( $legend ) {
543 $s .= Xml::element( 'legend', null, $legend ) . "\n";
544 }
545
546 if ( $content !== false ) {
547 $s .= $content . "\n";
548 $s .= Xml::closeElement( 'fieldset' ) . "\n";
549 }
550
551 return $s;
552 }
553
554 /**
555 * Shortcut for creating textareas.
556 *
557 * @param $name string The 'name' for the textarea
558 * @param $content string Content for the textarea
559 * @param $cols int The number of columns for the textarea
560 * @param $rows int The number of rows for the textarea
561 * @param $attribs array Any other attributes for the textarea
562 *
563 * @return string
564 */
565 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
566 return self::element( 'textarea',
567 array( 'name' => $name,
568 'id' => $name,
569 'cols' => $cols,
570 'rows' => $rows
571 ) + $attribs,
572 $content, false );
573 }
574
575 /**
576 * Returns an escaped string suitable for inclusion in a string literal
577 * for JavaScript source code.
578 * Illegal control characters are assumed not to be present.
579 *
580 * @param $string String to escape
581 * @return String
582 */
583 public static function escapeJsString( $string ) {
584 // See ECMA 262 section 7.8.4 for string literal format
585 $pairs = array(
586 "\\" => "\\\\",
587 "\"" => "\\\"",
588 '\'' => '\\\'',
589 "\n" => "\\n",
590 "\r" => "\\r",
591
592 # To avoid closing the element or CDATA section
593 "<" => "\\x3c",
594 ">" => "\\x3e",
595
596 # To avoid any complaints about bad entity refs
597 "&" => "\\x26",
598
599 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
600 # Encode certain Unicode formatting chars so affected
601 # versions of Gecko don't misinterpret our strings;
602 # this is a common problem with Farsi text.
603 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
604 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
605 );
606
607 return strtr( $string, $pairs );
608 }
609
610 /**
611 * Encode a variable of unknown type to JavaScript.
612 * Arrays are converted to JS arrays, objects are converted to JS associative
613 * arrays (objects). So cast your PHP associative arrays to objects before
614 * passing them to here.
615 *
616 * @param $value
617 *
618 * @return string
619 */
620 public static function encodeJsVar( $value ) {
621 if ( is_bool( $value ) ) {
622 $s = $value ? 'true' : 'false';
623 } elseif ( is_null( $value ) ) {
624 $s = 'null';
625 } elseif ( is_int( $value ) || is_float( $value ) ) {
626 $s = strval($value);
627 } elseif ( is_array( $value ) && // Make sure it's not associative.
628 array_keys($value) === range( 0, count($value) - 1 ) ||
629 count($value) == 0
630 ) {
631 $s = '[';
632 foreach ( $value as $elt ) {
633 if ( $s != '[' ) {
634 $s .= ',';
635 }
636 $s .= self::encodeJsVar( $elt );
637 }
638 $s .= ']';
639 } elseif ( $value instanceof XmlJsCode ) {
640 $s = $value->value;
641 } elseif ( is_object( $value ) || is_array( $value ) ) {
642 // Objects and associative arrays
643 $s = '{';
644 foreach ( (array)$value as $name => $elt ) {
645 if ( $s != '{' ) {
646 $s .= ',';
647 }
648
649 $s .= '"' . self::escapeJsString( $name ) . '":' .
650 self::encodeJsVar( $elt );
651 }
652 $s .= '}';
653 } else {
654 $s = '"' . self::escapeJsString( $value ) . '"';
655 }
656 return $s;
657 }
658
659 /**
660 * Create a call to a JavaScript function. The supplied arguments will be
661 * encoded using Xml::encodeJsVar().
662 *
663 * @param $name String The name of the function to call, or a JavaScript expression
664 * which evaluates to a function object which is called.
665 * @param $args Array of arguments to pass to the function.
666 *
667 * @since 1.17
668 *
669 * @return string
670 */
671 public static function encodeJsCall( $name, $args ) {
672 $s = "$name(";
673 $first = true;
674
675 foreach ( $args as $arg ) {
676 if ( $first ) {
677 $first = false;
678 } else {
679 $s .= ', ';
680 }
681
682 $s .= Xml::encodeJsVar( $arg );
683 }
684
685 $s .= ");\n";
686
687 return $s;
688 }
689
690 /**
691 * Check if a string is well-formed XML.
692 * Must include the surrounding tag.
693 *
694 * @param $text String: string to test.
695 * @return bool
696 *
697 * @todo Error position reporting return
698 */
699 public static function isWellFormed( $text ) {
700 $parser = xml_parser_create( "UTF-8" );
701
702 # case folding violates XML standard, turn it off
703 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
704
705 if( !xml_parse( $parser, $text, true ) ) {
706 //$err = xml_error_string( xml_get_error_code( $parser ) );
707 //$position = xml_get_current_byte_index( $parser );
708 //$fragment = $this->extractFragment( $html, $position );
709 //$this->mXmlError = "$err at byte $position:\n$fragment";
710 xml_parser_free( $parser );
711 return false;
712 }
713
714 xml_parser_free( $parser );
715
716 return true;
717 }
718
719 /**
720 * Check if a string is a well-formed XML fragment.
721 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
722 * and can use HTML named entities.
723 *
724 * @param $text String:
725 * @return bool
726 */
727 public static function isWellFormedXmlFragment( $text ) {
728 $html =
729 Sanitizer::hackDocType() .
730 '<html>' .
731 $text .
732 '</html>';
733
734 return Xml::isWellFormed( $html );
735 }
736
737 /**
738 * Replace " > and < with their respective HTML entities ( &quot;,
739 * &gt;, &lt;)
740 *
741 * @param $in String: text that might contain HTML tags.
742 * @return string Escaped string
743 */
744 public static function escapeTagsOnly( $in ) {
745 return str_replace(
746 array( '"', '>', '<' ),
747 array( '&quot;', '&gt;', '&lt;' ),
748 $in );
749 }
750
751 /**
752 * Generate a form (without the opening form element).
753 * Output optionally includes a submit button.
754 * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
755 * @param $submitLabel String A message containing a label for the submit button.
756 * @return string HTML form.
757 */
758 public static function buildForm( $fields, $submitLabel = null ) {
759 $form = '';
760 $form .= "<table><tbody>";
761
762 foreach( $fields as $labelmsg => $input ) {
763 $id = "mw-$labelmsg";
764 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
765 $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
766 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
767 $form .= Xml::closeElement( 'tr' );
768 }
769
770 if( $submitLabel ) {
771 $form .= Xml::openElement( 'tr' );
772 $form .= Xml::tags( 'td', array(), '' );
773 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( wfMsg( $submitLabel ) ) . Xml::closeElement( 'td' );
774 $form .= Xml::closeElement( 'tr' );
775 }
776
777 $form .= "</tbody></table>";
778
779 return $form;
780 }
781
782 /**
783 * Build a table of data
784 * @param $rows array An array of arrays of strings, each to be a row in a table
785 * @param $attribs array An array of attributes to apply to the table tag [optional]
786 * @param $headers array An array of strings to use as table headers [optional]
787 * @return string
788 */
789 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
790 $s = Xml::openElement( 'table', $attribs );
791
792 if ( is_array( $headers ) ) {
793 $s .= Xml::openElement( 'thead', $attribs );
794
795 foreach( $headers as $id => $header ) {
796 $attribs = array();
797
798 if ( is_string( $id ) ) {
799 $attribs['id'] = $id;
800 }
801
802 $s .= Xml::element( 'th', $attribs, $header );
803 }
804 $s .= Xml::closeElement( 'thead' );
805 }
806
807 foreach( $rows as $id => $row ) {
808 $attribs = array();
809
810 if ( is_string( $id ) ) {
811 $attribs['id'] = $id;
812 }
813
814 $s .= Xml::buildTableRow( $attribs, $row );
815 }
816
817 $s .= Xml::closeElement( 'table' );
818
819 return $s;
820 }
821
822 /**
823 * Build a row for a table
824 * @param $attribs array An array of attributes to apply to the tr tag
825 * @param $cells array An array of strings to put in <td>
826 * @return string
827 */
828 public static function buildTableRow( $attribs, $cells ) {
829 $s = Xml::openElement( 'tr', $attribs );
830
831 foreach( $cells as $id => $cell ) {
832
833 $attribs = array();
834
835 if ( is_string( $id ) ) {
836 $attribs['id'] = $id;
837 }
838
839 $s .= Xml::element( 'td', $attribs, $cell );
840 }
841
842 $s .= Xml::closeElement( 'tr' );
843
844 return $s;
845 }
846 }
847
848 class XmlSelect {
849 protected $options = array();
850 protected $default = false;
851 protected $attributes = array();
852
853 public function __construct( $name = false, $id = false, $default = false ) {
854 if ( $name ) {
855 $this->setAttribute( 'name', $name );
856 }
857
858 if ( $id ) {
859 $this->setAttribute( 'id', $id );
860 }
861
862 if ( $default !== false ) {
863 $this->default = $default;
864 }
865 }
866
867 /**
868 * @param $default
869 */
870 public function setDefault( $default ) {
871 $this->default = $default;
872 }
873
874 /**
875 * @param $name string
876 * @param $value
877 */
878 public function setAttribute( $name, $value ) {
879 $this->attributes[$name] = $value;
880 }
881
882 /**
883 * @param $name
884 * @return array|null
885 */
886 public function getAttribute( $name ) {
887 if ( isset( $this->attributes[$name] ) ) {
888 return $this->attributes[$name];
889 } else {
890 return null;
891 }
892 }
893
894 /**
895 * @param $name
896 * @param $value bool
897 */
898 public function addOption( $name, $value = false ) {
899 // Stab stab stab
900 $value = ($value !== false) ? $value : $name;
901
902 $this->options[] = array( $name => $value );
903 }
904
905 /**
906 * This accepts an array of form
907 * label => value
908 * label => ( label => value, label => value )
909 *
910 * @param $options
911 */
912 public function addOptions( $options ) {
913 $this->options[] = $options;
914 }
915
916 /**
917 * This accepts an array of form
918 * label => value
919 * label => ( label => value, label => value )
920 *
921 * @param $options
922 * @param bool $default
923 * @return string
924 */
925 static function formatOptions( $options, $default = false ) {
926 $data = '';
927
928 foreach( $options as $label => $value ) {
929 if ( is_array( $value ) ) {
930 $contents = self::formatOptions( $value, $default );
931 $data .= Html::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
932 } else {
933 $data .= Xml::option( $label, $value, $value === $default ) . "\n";
934 }
935 }
936
937 return $data;
938 }
939
940 /**
941 * @return string
942 */
943 public function getHTML() {
944 $contents = '';
945
946 foreach ( $this->options as $options ) {
947 $contents .= self::formatOptions( $options, $this->default );
948 }
949
950 return Html::rawElement( 'select', $this->attributes, rtrim( $contents ) );
951 }
952 }
953
954 /**
955 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
956 * interpret a given string as being a JavaScript expression, instead of string
957 * data.
958 *
959 * Example:
960 *
961 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
962 *
963 * Returns "a + b".
964 * @since 1.17
965 */
966 class XmlJsCode {
967 public $value;
968
969 function __construct( $value ) {
970 $this->value = $value;
971 }
972 }