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