1e8696be1e4d6ce725d871890c5e7ab2cacf2a16
[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 */
121 public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
122 global $wgContLang;
123 $namespaces = $wgContLang->getFormattedNamespaces();
124 $options = array();
125
126 // Godawful hack... we'll be frequently passed selected namespaces
127 // as strings since PHP is such a shithole.
128 // But we also don't want blanks and nulls and "all"s matching 0,
129 // so let's convert *just* string ints to clean ints.
130 if( preg_match( '/^\d+$/', $selected ) ) {
131 $selected = intval( $selected );
132 }
133
134 if( !is_null( $all ) )
135 # Please make sure the 'namespacesall' is the first or you will break
136 # such an assumption (ex js: mw.special.recentchanges.updateCheckboxes)
137 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) + $namespaces;
138 foreach( $namespaces as $index => $name ) {
139 if( $index < NS_MAIN ) {
140 continue;
141 }
142 if( $index === 0 ) {
143 $name = wfMsg( 'blanknamespace' );
144 }
145 $options[] = self::option( $name, $index, $index === $selected );
146 }
147
148 $ret = Xml::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
149 'class' => 'namespaceselector' ) )
150 . "\n"
151 . implode( "\n", $options )
152 . "\n"
153 . Xml::closeElement( 'select' );
154 if ( !is_null( $label ) ) {
155 $ret = Xml::label( $label, $element_name ) . '&#160;' . $ret;
156 }
157 return $ret;
158 }
159
160 /**
161 * Create a date selector
162 *
163 * @param $selected Mixed: the month which should be selected, default ''
164 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
165 * @param $id String: Element identifier
166 * @return String: Html string containing the month selector
167 */
168 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
169 global $wgLang;
170 $options = array();
171 if( is_null( $selected ) )
172 $selected = '';
173 if( !is_null( $allmonths ) )
174 $options[] = self::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
175 for( $i = 1; $i < 13; $i++ )
176 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
177 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
178 . implode( "\n", $options )
179 . self::closeElement( 'select' );
180 }
181
182 /**
183 * @param $year Integer
184 * @param $month Integer
185 * @return string Formatted HTML
186 */
187 public static function dateMenu( $year, $month ) {
188 # Offset overrides year/month selection
189 if( $month && $month !== -1 ) {
190 $encMonth = intval( $month );
191 } else {
192 $encMonth = '';
193 }
194 if( $year ) {
195 $encYear = intval( $year );
196 } elseif( $encMonth ) {
197 $thisMonth = intval( gmdate( 'n' ) );
198 $thisYear = intval( gmdate( 'Y' ) );
199 if( intval($encMonth) > $thisMonth ) {
200 $thisYear--;
201 }
202 $encYear = $thisYear;
203 } else {
204 $encYear = '';
205 }
206 return Xml::label( wfMsg( 'year' ), 'year' ) . ' '.
207 Xml::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) . ' '.
208 Xml::label( wfMsg( 'month' ), 'month' ) . ' '.
209 Xml::monthSelector( $encMonth, -1 );
210 }
211
212 /**
213 *
214 * @param $selected string The language code of the selected language
215 * @param $customisedOnly bool If true only languages which have some content are listed
216 * @return array of label and select
217 */
218 public static function languageSelector( $selected, $customisedOnly = true ) {
219 global $wgLanguageCode;
220 /**
221 * Make sure the site language is in the list; a custom language code
222 * might not have a defined name...
223 */
224 $languages = Language::getLanguageNames( $customisedOnly );
225 if( !array_key_exists( $wgLanguageCode, $languages ) ) {
226 $languages[$wgLanguageCode] = $wgLanguageCode;
227 }
228 ksort( $languages );
229
230 /**
231 * If a bogus value is set, default to the content language.
232 * Otherwise, no default is selected and the user ends up
233 * with an Afrikaans interface since it's first in the list.
234 */
235 $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
236 $options = "\n";
237 foreach( $languages as $code => $name ) {
238 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
239 }
240
241 return array(
242 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
243 Xml::tags( 'select',
244 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
245 $options
246 )
247 );
248
249 }
250
251 /**
252 * Shortcut to make a span element
253 * @param $text String content of the element, will be escaped
254 * @param $class String class name of the span element
255 * @param $attribs array other attributes
256 * @return string
257 */
258 public static function span( $text, $class, $attribs = array() ) {
259 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
260 }
261
262 /**
263 * Shortcut to make a specific element with a class attribute
264 * @param $text content of the element, will be escaped
265 * @param $class class name of the span element
266 * @param $tag string element name
267 * @param $attribs array other attributes
268 * @return string
269 */
270 public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
271 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
272 }
273
274 /**
275 * Convenience function to build an HTML text input field
276 * @param $name String value of the name attribute
277 * @param $size int value of the size attribute
278 * @param $value mixed value of the value attribute
279 * @param $attribs array other attributes
280 * @return string HTML
281 */
282 public static function input( $name, $size = false, $value = false, $attribs = array() ) {
283 $attributes = array( 'name' => $name );
284
285 if( $size ) {
286 $attributes['size'] = $size;
287 }
288
289 if( $value !== false ) { // maybe 0
290 $attributes['value'] = $value;
291 }
292
293 return self::element( 'input', $attributes + $attribs );
294 }
295
296 /**
297 * Convenience function to build an HTML password input field
298 * @param $name string value of the name attribute
299 * @param $size int value of the size attribute
300 * @param $value mixed value of the value attribute
301 * @param $attribs array other attributes
302 * @return string HTML
303 */
304 public static function password( $name, $size = false, $value = false, $attribs = array() ) {
305 return self::input( $name, $size, $value, array_merge( $attribs, array( 'type' => 'password' ) ) );
306 }
307
308 /**
309 * Internal function for use in checkboxes and radio buttons and such.
310 *
311 * @param $name string
312 * @param $present bool
313 *
314 * @return array
315 */
316 public static function attrib( $name, $present = true ) {
317 return $present ? array( $name => $name ) : array();
318 }
319
320 /**
321 * Convenience function to build an HTML checkbox
322 * @param $name String value of the name attribute
323 * @param $checked Bool Whether the checkbox is checked or not
324 * @param $attribs Array other attributes
325 * @return string HTML
326 */
327 public static function check( $name, $checked = false, $attribs=array() ) {
328 return self::element( 'input', array_merge(
329 array(
330 'name' => $name,
331 'type' => 'checkbox',
332 'value' => 1 ),
333 self::attrib( 'checked', $checked ),
334 $attribs ) );
335 }
336
337 /**
338 * Convenience function to build an HTML radio button
339 * @param $name value of the name attribute
340 * @param $value value of the value attribute
341 * @param $checked Whether the checkbox is checked or not
342 * @param $attribs other attributes
343 * @return string HTML
344 */
345 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
346 return self::element( 'input', array(
347 'name' => $name,
348 'type' => 'radio',
349 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
350 }
351
352 /**
353 * Convenience function to build an HTML form label
354 * @param $label String text of the label
355 * @param $id
356 * @param $attribs Array an attribute array. This will usuall be
357 * the same array as is passed to the corresponding input element,
358 * so this function will cherry-pick appropriate attributes to
359 * apply to the label as well; only class and title are applied.
360 * @return string HTML
361 */
362 public static function label( $label, $id, $attribs = array() ) {
363 $a = array( 'for' => $id );
364
365 # FIXME avoid copy pasting below:
366 if( isset( $attribs['class'] ) ){
367 $a['class'] = $attribs['class'];
368 }
369 if( isset( $attribs['title'] ) ){
370 $a['title'] = $attribs['title'];
371 }
372
373 return self::element( 'label', $a, $label );
374 }
375
376 /**
377 * Convenience function to build an HTML text input field with a label
378 * @param $label String text of the label
379 * @param $name String value of the name attribute
380 * @param $id String id of the input
381 * @param $size int value of the size attribute
382 * @param $value value of the value attribute
383 * @param $attribs array other attributes
384 * @return string HTML
385 */
386 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs = array() ) {
387 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
388 return $label . '&#160;' . $input;
389 }
390
391 /**
392 * Same as Xml::inputLabel() but return input and label in an array
393 *
394 * @param $label
395 * @param $name
396 * @param $id
397 * @param $size
398 * @param $value
399 * @param $attribs array
400 *
401 * @return array
402 */
403 public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
404 return array(
405 Xml::label( $label, $id, $attribs ),
406 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
407 );
408 }
409
410 /**
411 * Convenience function to build an HTML checkbox with a label
412 *
413 * @param $label
414 * @param $name
415 * @param $id
416 * @param $checked bool
417 * @param $attribs array
418 *
419 * @return string HTML
420 */
421 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
422 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
423 '&#160;' .
424 self::label( $label, $id, $attribs );
425 }
426
427 /**
428 * Convenience function to build an HTML radio button with a label
429 *
430 * @param $label
431 * @param $name
432 * @param $value
433 * @param $id
434 * @param $checked bool
435 * @param $attribs array
436 *
437 * @return string HTML
438 */
439 public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
440 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
441 '&#160;' .
442 self::label( $label, $id, $attribs );
443 }
444
445 /**
446 * Convenience function to build an HTML submit button
447 * @param $value String: label text for the button
448 * @param $attribs Array: optional custom attributes
449 * @return string HTML
450 */
451 public static function submitButton( $value, $attribs = array() ) {
452 return Html::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
453 }
454
455 /**
456 * Convenience function to build an HTML drop-down list item.
457 * @param $text String: text for this item
458 * @param $value String: form submission value; if empty, use text
459 * @param $selected boolean: if true, will be the default selected item
460 * @param $attribs array: optional additional HTML attributes
461 * @return string HTML
462 */
463 public static function option( $text, $value=null, $selected = false,
464 $attribs = array() ) {
465 if( !is_null( $value ) ) {
466 $attribs['value'] = $value;
467 }
468 if( $selected ) {
469 $attribs['selected'] = 'selected';
470 }
471 return self::element( 'option', $attribs, $text );
472 }
473
474 /**
475 * Build a drop-down box from a textual list.
476 *
477 * @param $name Mixed: Name and id for the drop-down
478 * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
479 * @param $other Mixed: Text for the "Other reasons" option
480 * @param $selected Mixed: Option which should be pre-selected
481 * @param $class Mixed: CSS classes for the drop-down
482 * @param $tabindex Mixed: Value of the tabindex attribute
483 * @return string
484 */
485 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
486 $optgroup = false;
487
488 $options = self::option( $other, 'other', $selected === 'other' );
489
490 foreach ( explode( "\n", $list ) as $option) {
491 $value = trim( $option );
492 if ( $value == '' ) {
493 continue;
494 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
495 // A new group is starting ...
496 $value = trim( substr( $value, 1 ) );
497 if( $optgroup ) $options .= self::closeElement('optgroup');
498 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
499 $optgroup = true;
500 } elseif ( substr( $value, 0, 2) == '**' ) {
501 // groupmember
502 $value = trim( substr( $value, 2 ) );
503 $options .= self::option( $value, $value, $selected === $value );
504 } else {
505 // groupless reason list
506 if( $optgroup ) $options .= self::closeElement('optgroup');
507 $options .= self::option( $value, $value, $selected === $value );
508 $optgroup = false;
509 }
510 }
511 if( $optgroup ) $options .= self::closeElement('optgroup');
512
513 $attribs = array();
514 if( $name ) {
515 $attribs['id'] = $name;
516 $attribs['name'] = $name;
517 }
518 if( $class ) {
519 $attribs['class'] = $class;
520 }
521 if( $tabindex ) {
522 $attribs['tabindex'] = $tabindex;
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 Legend of the fieldset. If evaluates to false, legend is not added.
535 * @param $content 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 if ( $legend ) {
543 $s .= Xml::element( 'legend', null, $legend ) . "\n";
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 return strtr( $string, $pairs );
606 }
607
608 /**
609 * Encode a variable of unknown type to JavaScript.
610 * Arrays are converted to JS arrays, objects are converted to JS associative
611 * arrays (objects). So cast your PHP associative arrays to objects before
612 * passing them to here.
613 *
614 * @param $value
615 *
616 * @return string
617 */
618 public static function encodeJsVar( $value ) {
619 if ( is_bool( $value ) ) {
620 $s = $value ? 'true' : 'false';
621 } elseif ( is_null( $value ) ) {
622 $s = 'null';
623 } elseif ( is_int( $value ) || is_float( $value ) ) {
624 $s = strval($value);
625 } elseif ( is_array( $value ) && // Make sure it's not associative.
626 array_keys($value) === range( 0, count($value) - 1 ) ||
627 count($value) == 0
628 ) {
629 $s = '[';
630 foreach ( $value as $elt ) {
631 if ( $s != '[' ) {
632 $s .= ', ';
633 }
634 $s .= self::encodeJsVar( $elt );
635 }
636 $s .= ']';
637 } elseif ( $value instanceof XmlJsCode ) {
638 $s = $value->value;
639 } elseif ( is_object( $value ) || is_array( $value ) ) {
640 // Objects and associative arrays
641 $s = '{';
642 foreach ( (array)$value as $name => $elt ) {
643 if ( $s != '{' ) {
644 $s .= ', ';
645 }
646 $s .= '"' . self::escapeJsString( $name ) . '": ' .
647 self::encodeJsVar( $elt );
648 }
649 $s .= '}';
650 } else {
651 $s = '"' . self::escapeJsString( $value ) . '"';
652 }
653 return $s;
654 }
655
656 /**
657 * Create a call to a JavaScript function. The supplied arguments will be
658 * encoded using Xml::encodeJsVar().
659 *
660 * @param $name String The name of the function to call, or a JavaScript expression
661 * which evaluates to a function object which is called.
662 * @param $args Array of arguments to pass to the function.
663 *
664 * @since 1.17
665 *
666 * @return string
667 */
668 public static function encodeJsCall( $name, $args ) {
669 $s = "$name(";
670 $first = true;
671 foreach ( $args as $arg ) {
672 if ( $first ) {
673 $first = false;
674 } else {
675 $s .= ', ';
676 }
677 $s .= Xml::encodeJsVar( $arg );
678 }
679 $s .= ");\n";
680 return $s;
681 }
682
683
684 /**
685 * Check if a string is well-formed XML.
686 * Must include the surrounding tag.
687 *
688 * @param $text String: string to test.
689 * @return bool
690 *
691 * @todo Error position reporting return
692 */
693 public static function isWellFormed( $text ) {
694 $parser = xml_parser_create( "UTF-8" );
695
696 # case folding violates XML standard, turn it off
697 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
698
699 if( !xml_parse( $parser, $text, true ) ) {
700 //$err = xml_error_string( xml_get_error_code( $parser ) );
701 //$position = xml_get_current_byte_index( $parser );
702 //$fragment = $this->extractFragment( $html, $position );
703 //$this->mXmlError = "$err at byte $position:\n$fragment";
704 xml_parser_free( $parser );
705 return false;
706 }
707 xml_parser_free( $parser );
708 return true;
709 }
710
711 /**
712 * Check if a string is a well-formed XML fragment.
713 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
714 * and can use HTML named entities.
715 *
716 * @param $text String:
717 * @return bool
718 */
719 public static function isWellFormedXmlFragment( $text ) {
720 $html =
721 Sanitizer::hackDocType() .
722 '<html>' .
723 $text .
724 '</html>';
725 return Xml::isWellFormed( $html );
726 }
727
728 /**
729 * Replace " > and < with their respective HTML entities ( &quot;,
730 * &gt;, &lt;)
731 *
732 * @param $in String: text that might contain HTML tags.
733 * @return string Escaped string
734 */
735 public static function escapeTagsOnly( $in ) {
736 return str_replace(
737 array( '"', '>', '<' ),
738 array( '&quot;', '&gt;', '&lt;' ),
739 $in );
740 }
741
742 /**
743 * Generate a form (without the opening form element).
744 * Output optionally includes a submit button.
745 * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
746 * @param $submitLabel String A message containing a label for the submit button.
747 * @return string HTML form.
748 */
749 public static function buildForm( $fields, $submitLabel = null ) {
750 $form = '';
751 $form .= "<table><tbody>";
752
753 foreach( $fields as $labelmsg => $input ) {
754 $id = "mw-$labelmsg";
755 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
756 $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
757 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
758 $form .= Xml::closeElement( 'tr' );
759 }
760
761 if( $submitLabel ) {
762 $form .= Xml::openElement( 'tr' );
763 $form .= Xml::tags( 'td', array(), '' );
764 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( wfMsg( $submitLabel ) ) . Xml::closeElement( 'td' );
765 $form .= Xml::closeElement( 'tr' );
766 }
767
768 $form .= "</tbody></table>";
769
770
771 return $form;
772 }
773
774 /**
775 * Build a table of data
776 * @param $rows array An array of arrays of strings, each to be a row in a table
777 * @param $attribs array An array of attributes to apply to the table tag [optional]
778 * @param $headers array An array of strings to use as table headers [optional]
779 * @return string
780 */
781 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
782 $s = Xml::openElement( 'table', $attribs );
783 if ( is_array( $headers ) ) {
784 foreach( $headers as $id => $header ) {
785 $attribs = array();
786 if ( is_string( $id ) ) $attribs['id'] = $id;
787 $s .= Xml::element( 'th', $attribs, $header );
788 }
789 }
790 foreach( $rows as $id => $row ) {
791 $attribs = array();
792 if ( is_string( $id ) ) $attribs['id'] = $id;
793 $s .= Xml::buildTableRow( $attribs, $row );
794 }
795 $s .= Xml::closeElement( 'table' );
796 return $s;
797 }
798
799 /**
800 * Build a row for a table
801 * @param $attribs An array of attributes to apply to the tr tag
802 * @param $cells An array of strings to put in <td>
803 * @return string
804 */
805 public static function buildTableRow( $attribs, $cells ) {
806 $s = Xml::openElement( 'tr', $attribs );
807 foreach( $cells as $id => $cell ) {
808 $attribs = array();
809 if ( is_string( $id ) ) $attribs['id'] = $id;
810 $s .= Xml::element( 'td', $attribs, $cell );
811 }
812 $s .= Xml::closeElement( 'tr' );
813 return $s;
814 }
815 }
816
817 class XmlSelect {
818 protected $options = array();
819 protected $default = false;
820 protected $attributes = array();
821
822 public function __construct( $name = false, $id = false, $default = false ) {
823 if ( $name ) {
824 $this->setAttribute( 'name', $name );
825 }
826 if ( $id ) {
827 $this->setAttribute( 'id', $id );
828 }
829 if ( $default !== false ) {
830 $this->default = $default;
831 }
832 }
833
834 /**
835 * @param $default
836 */
837 public function setDefault( $default ) {
838 $this->default = $default;
839 }
840
841 /**
842 * @param $name string
843 * @param $value
844 */
845 public function setAttribute( $name, $value ) {
846 $this->attributes[$name] = $value;
847 }
848
849 /**
850 * @param $name
851 * @return array|null
852 */
853 public function getAttribute( $name ) {
854 if ( isset($this->attributes[$name]) ) {
855 return $this->attributes[$name];
856 } else {
857 return null;
858 }
859 }
860
861 /**
862 * @param $name
863 * @param $value bool
864 */
865 public function addOption( $name, $value = false ) {
866 // Stab stab stab
867 $value = ($value !== false) ? $value : $name;
868 $this->options[] = Xml::option( $name, $value, $value === $this->default );
869 }
870
871 /**
872 * This accepts an array of form
873 * label => value
874 * label => ( label => value, label => value )
875 *
876 * @param $options
877 */
878 public function addOptions( $options ) {
879 $this->options[] = trim( self::formatOptions( $options, $this->default ) );
880 }
881
882 /**
883 * This accepts an array of form
884 * label => value
885 * label => ( label => value, label => value )
886 *
887 * @param $options
888 * @param bool $default
889 * @return string
890 */
891 static function formatOptions( $options, $default = false ) {
892 $data = '';
893 foreach( $options as $label => $value ) {
894 if ( is_array( $value ) ) {
895 $contents = self::formatOptions( $value, $default );
896 $data .= Xml::tags( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
897 } else {
898 $data .= Xml::option( $label, $value, $value === $default ) . "\n";
899 }
900 }
901
902 return $data;
903 }
904
905 /**
906 * @return string
907 */
908 public function getHTML() {
909 return Xml::tags( 'select', $this->attributes, implode( "\n", $this->options ) );
910 }
911
912 }
913
914 /**
915 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
916 * interpret a given string as being a JavaScript expression, instead of string
917 * data.
918 *
919 * Example:
920 *
921 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
922 *
923 * Returns "a + b".
924 * @since 1.17
925 */
926 class XmlJsCode {
927 public $value;
928
929 function __construct( $value ) {
930 $this->value = $value;
931 }
932 }