Merge "AutoloadGenerator.php: Update 'AutoloadClasses' in extension.json"
[lhc/web/wiklou.git] / includes / Xml.php
1 <?php
2 /**
3 * Methods to generate XML.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Module of static functions for generating XML
25 */
26 class Xml {
27 /**
28 * Format an XML element with given attributes and, optionally, text content.
29 * Element and attribute names are assumed to be ready for literal inclusion.
30 * Strings are assumed to not contain XML-illegal characters; special
31 * characters (<, >, &) are escaped but illegals are not touched.
32 *
33 * @param string $element Element name
34 * @param array $attribs Name=>value pairs. Values will be escaped.
35 * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
36 * @param bool $allowShortTag Whether '' in $contents will result in a contentless closed tag
37 * @return string
38 */
39 public static function element( $element, $attribs = null, $contents = '',
40 $allowShortTag = true
41 ) {
42 $out = '<' . $element;
43 if ( !is_null( $attribs ) ) {
44 $out .= self::expandAttributes( $attribs );
45 }
46 if ( is_null( $contents ) ) {
47 $out .= '>';
48 } else {
49 if ( $allowShortTag && $contents === '' ) {
50 $out .= ' />';
51 } else {
52 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
53 }
54 }
55 return $out;
56 }
57
58 /**
59 * Given an array of ('attributename' => 'value'), it generates the code
60 * to set the XML attributes : attributename="value".
61 * The values are passed to Sanitizer::encodeAttribute.
62 * Return null if no attributes given.
63 * @param array $attribs Array of attributes for an XML element
64 * @throws MWException
65 * @return null|string
66 */
67 public static function expandAttributes( $attribs ) {
68 $out = '';
69 if ( is_null( $attribs ) ) {
70 return null;
71 } elseif ( is_array( $attribs ) ) {
72 foreach ( $attribs as $name => $val ) {
73 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
74 }
75 return $out;
76 } else {
77 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
78 }
79 }
80
81 /**
82 * Format an XML element as with self::element(), but run text through the
83 * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
84 * is passed.
85 *
86 * @param string $element
87 * @param array $attribs Name=>value pairs. Values will be escaped.
88 * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
89 * @return string
90 */
91 public static function elementClean( $element, $attribs = array(), $contents = '' ) {
92 global $wgContLang;
93 if ( $attribs ) {
94 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
95 }
96 if ( $contents ) {
97 $contents = $wgContLang->normalize( $contents );
98 }
99 return self::element( $element, $attribs, $contents );
100 }
101
102 /**
103 * This opens an XML element
104 *
105 * @param string $element Name of the element
106 * @param array $attribs Array of attributes, see Xml::expandAttributes()
107 * @return string
108 */
109 public static function openElement( $element, $attribs = null ) {
110 return '<' . $element . self::expandAttributes( $attribs ) . '>';
111 }
112
113 /**
114 * Shortcut to close an XML element
115 * @param string $element Element name
116 * @return string
117 */
118 public static function closeElement( $element ) {
119 return "</$element>";
120 }
121
122 /**
123 * Same as Xml::element(), but does not escape contents. Handy when the
124 * content you have is already valid xml.
125 *
126 * @param string $element Element name
127 * @param array $attribs Array of attributes
128 * @param string $contents Content of the element
129 * @return string
130 */
131 public static function tags( $element, $attribs = null, $contents ) {
132 return self::openElement( $element, $attribs ) . $contents . "</$element>";
133 }
134
135 /**
136 * Create a date selector
137 *
138 * @param string $selected The month which should be selected, default ''.
139 * @param string $allmonths Value of a special item denoting all month.
140 * Null to not include (default).
141 * @param string $id 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 }
150 if ( !is_null( $allmonths ) ) {
151 $options[] = self::option(
152 wfMessage( 'monthsall' )->text(),
153 $allmonths,
154 $selected === $allmonths
155 );
156 }
157 for ( $i = 1; $i < 13; $i++ ) {
158 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
159 }
160 return self::openElement( 'select', array(
161 'id' => $id,
162 'name' => 'month',
163 'class' => 'mw-month-selector'
164 ) )
165 . implode( "\n", $options )
166 . self::closeElement( 'select' );
167 }
168
169 /**
170 * @param int $year
171 * @param int $month
172 * @return string Formatted HTML
173 */
174 public static function dateMenu( $year, $month ) {
175 # Offset overrides year/month selection
176 if ( $month && $month !== -1 ) {
177 $encMonth = intval( $month );
178 } else {
179 $encMonth = '';
180 }
181 if ( $year ) {
182 $encYear = intval( $year );
183 } elseif ( $encMonth ) {
184 $timestamp = MWTimestamp::getInstance();
185 $thisMonth = intval( $timestamp->format( 'n' ) );
186 $thisYear = intval( $timestamp->format( 'Y' ) );
187 if ( intval( $encMonth ) > $thisMonth ) {
188 $thisYear--;
189 }
190 $encYear = $thisYear;
191 } else {
192 $encYear = '';
193 }
194 $inputAttribs = array( 'id' => 'year', 'maxlength' => 4, 'size' => 7 );
195 return self::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
196 Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
197 self::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
198 self::monthSelector( $encMonth, -1 );
199 }
200
201 /**
202 * Construct a language selector appropriate for use in a form or preferences
203 *
204 * @param string $selected The language code of the selected language
205 * @param bool $customisedOnly If true only languages which have some content are listed
206 * @param string $inLanguage The ISO code of the language to display the select list in (optional)
207 * @param array $overrideAttrs Override the attributes of the select tag (since 1.20)
208 * @param Message|null $msg Label message key (since 1.20)
209 * @return array Array containing 2 items: label HTML and select list HTML
210 */
211 public static function languageSelector( $selected, $customisedOnly = true,
212 $inLanguage = null, $overrideAttrs = array(), Message $msg = null
213 ) {
214 global $wgLanguageCode;
215
216 $include = $customisedOnly ? 'mwfile' : 'mw';
217 $languages = Language::fetchLanguageNames( $inLanguage, $include );
218
219 // Make sure the site language is in the list;
220 // a custom language code might not have a defined name...
221 if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
222 $languages[$wgLanguageCode] = $wgLanguageCode;
223 }
224
225 ksort( $languages );
226
227 /**
228 * If a bogus value is set, default to the content language.
229 * Otherwise, no default is selected and the user ends up
230 * with Afrikaans since it's first in the list.
231 */
232 $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
233 $options = "\n";
234 foreach ( $languages as $code => $name ) {
235 $options .= Xml::option( "$code - $name", $code, $code == $selected ) . "\n";
236 }
237
238 $attrs = array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' );
239 $attrs = array_merge( $attrs, $overrideAttrs );
240
241 if ( $msg === null ) {
242 $msg = wfMessage( 'yourlanguage' );
243 }
244 return array(
245 Xml::label( $msg->text(), $attrs['id'] ),
246 Xml::tags( 'select', $attrs, $options )
247 );
248
249 }
250
251 /**
252 * Shortcut to make a span element
253 * @param string $text Content of the element, will be escaped
254 * @param string $class Class name of the span element
255 * @param array $attribs 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 string $text Content of the element, will be escaped
265 * @param string $class Class name of the span element
266 * @param string $tag Element name
267 * @param array $attribs 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 string $name Value of the name attribute
277 * @param int $size Value of the size attribute
278 * @param mixed $value Value of the value attribute
279 * @param array $attribs 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',
294 Html::getTextInputAttributes( $attributes + $attribs ) );
295 }
296
297 /**
298 * Convenience function to build an HTML password input field
299 * @param string $name Value of the name attribute
300 * @param int $size Value of the size attribute
301 * @param mixed $value Value of the value attribute
302 * @param array $attribs Other attributes
303 * @return string HTML
304 */
305 public static function password( $name, $size = false, $value = false,
306 $attribs = array()
307 ) {
308 return self::input( $name, $size, $value,
309 array_merge( $attribs, array( 'type' => 'password' ) ) );
310 }
311
312 /**
313 * Internal function for use in checkboxes and radio buttons and such.
314 *
315 * @param string $name
316 * @param bool $present
317 *
318 * @return array
319 */
320 public static function attrib( $name, $present = true ) {
321 return $present ? array( $name => $name ) : array();
322 }
323
324 /**
325 * Convenience function to build an HTML checkbox
326 * @param string $name Value of the name attribute
327 * @param bool $checked Whether the checkbox is checked or not
328 * @param array $attribs Array other attributes
329 * @return string HTML
330 */
331 public static function check( $name, $checked = false, $attribs = array() ) {
332 return self::element( 'input', array_merge(
333 array(
334 'name' => $name,
335 'type' => 'checkbox',
336 'value' => 1 ),
337 self::attrib( 'checked', $checked ),
338 $attribs ) );
339 }
340
341 /**
342 * Convenience function to build an HTML radio button
343 * @param string $name Value of the name attribute
344 * @param string $value Value of the value attribute
345 * @param bool $checked Whether the checkbox is checked or not
346 * @param array $attribs Other attributes
347 * @return string HTML
348 */
349 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
350 return self::element( 'input', array(
351 'name' => $name,
352 'type' => 'radio',
353 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
354 }
355
356 /**
357 * Convenience function to build an HTML form label
358 * @param string $label Text of the label
359 * @param string $id
360 * @param array $attribs An attribute array. This will usually be
361 * the same array as is passed to the corresponding input element,
362 * so this function will cherry-pick appropriate attributes to
363 * apply to the label as well; only class and title are applied.
364 * @return string HTML
365 */
366 public static function label( $label, $id, $attribs = array() ) {
367 $a = array( 'for' => $id );
368
369 foreach ( array( 'class', 'title' ) as $attr ) {
370 if ( isset( $attribs[$attr] ) ) {
371 $a[$attr] = $attribs[$attr];
372 }
373 }
374
375 return self::element( 'label', $a, $label );
376 }
377
378 /**
379 * Convenience function to build an HTML text input field with a label
380 * @param string $label Text of the label
381 * @param string $name Value of the name attribute
382 * @param string $id Id of the input
383 * @param int|bool $size Value of the size attribute
384 * @param string|bool $value Value of the value attribute
385 * @param array $attribs Other attributes
386 * @return string HTML
387 */
388 public static function inputLabel( $label, $name, $id, $size = false,
389 $value = false, $attribs = array()
390 ) {
391 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
392 return $label . '&#160;' . $input;
393 }
394
395 /**
396 * Same as Xml::inputLabel() but return input and label in an array
397 *
398 * @param string $label
399 * @param string $name
400 * @param string $id
401 * @param int|bool $size
402 * @param string|bool $value
403 * @param array $attribs
404 *
405 * @return array
406 */
407 public static function inputLabelSep( $label, $name, $id, $size = false,
408 $value = false, $attribs = array()
409 ) {
410 return array(
411 Xml::label( $label, $id, $attribs ),
412 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
413 );
414 }
415
416 /**
417 * Convenience function to build an HTML checkbox with a label
418 *
419 * @param string $label
420 * @param string $name
421 * @param string $id
422 * @param bool $checked
423 * @param array $attribs
424 *
425 * @return string HTML
426 */
427 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
428 global $wgUseMediaWikiUIEverywhere;
429 $chkLabel = self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
430 '&#160;' .
431 self::label( $label, $id, $attribs );
432
433 if ( $wgUseMediaWikiUIEverywhere ) {
434 $chkLabel = self::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
435 $chkLabel . self::closeElement( 'div' );
436 }
437 return $chkLabel;
438 }
439
440 /**
441 * Convenience function to build an HTML radio button with a label
442 *
443 * @param string $label
444 * @param string $name
445 * @param string $value
446 * @param string $id
447 * @param bool $checked
448 * @param array $attribs
449 *
450 * @return string HTML
451 */
452 public static function radioLabel( $label, $name, $value, $id,
453 $checked = false, $attribs = array()
454 ) {
455 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
456 '&#160;' .
457 self::label( $label, $id, $attribs );
458 }
459
460 /**
461 * Convenience function to build an HTML submit button
462 * When $wgUseMediaWikiUIEverywhere is true it will default to a constructive button
463 * @param string $value Label text for the button
464 * @param array $attribs Optional custom attributes
465 * @return string HTML
466 */
467 public static function submitButton( $value, $attribs = array() ) {
468 global $wgUseMediaWikiUIEverywhere;
469 $baseAttrs = array(
470 'type' => 'submit',
471 'value' => $value,
472 );
473 // Done conditionally for time being as it is possible
474 // some submit forms
475 // might need to be mw-ui-destructive (e.g. delete a page)
476 if ( $wgUseMediaWikiUIEverywhere ) {
477 $baseAttrs['class'] = 'mw-ui-button mw-ui-constructive';
478 }
479 // Any custom attributes will take precendence of anything in baseAttrs e.g. override the class
480 $attribs = $attribs + $baseAttrs;
481 return Html::element( 'input', $attribs );
482 }
483
484 /**
485 * Convenience function to build an HTML drop-down list item.
486 * @param string $text Text for this item. Will be HTML escaped
487 * @param string $value Form submission value; if empty, use text
488 * @param bool $selected If true, will be the default selected item
489 * @param array $attribs Optional additional HTML attributes
490 * @return string HTML
491 */
492 public static function option( $text, $value = null, $selected = false,
493 $attribs = array() ) {
494 if ( !is_null( $value ) ) {
495 $attribs['value'] = $value;
496 }
497 if ( $selected ) {
498 $attribs['selected'] = 'selected';
499 }
500 return Html::element( 'option', $attribs, $text );
501 }
502
503 /**
504 * Build a drop-down box from a textual list.
505 *
506 * @param string $name Name and id for the drop-down
507 * @param string $list Correctly formatted text (newline delimited) to be
508 * used to generate the options.
509 * @param string $other Text for the "Other reasons" option
510 * @param string $selected Option which should be pre-selected
511 * @param string $class CSS classes for the drop-down
512 * @param int $tabindex Value of the tabindex attribute
513 * @return string
514 */
515 public static function listDropDown( $name = '', $list = '', $other = '',
516 $selected = '', $class = '', $tabindex = null
517 ) {
518 $optgroup = false;
519
520 $options = self::option( $other, 'other', $selected === 'other' );
521
522 foreach ( explode( "\n", $list ) as $option ) {
523 $value = trim( $option );
524 if ( $value == '' ) {
525 continue;
526 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
527 // A new group is starting ...
528 $value = trim( substr( $value, 1 ) );
529 if ( $optgroup ) {
530 $options .= self::closeElement( 'optgroup' );
531 }
532 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
533 $optgroup = true;
534 } elseif ( substr( $value, 0, 2 ) == '**' ) {
535 // groupmember
536 $value = trim( substr( $value, 2 ) );
537 $options .= self::option( $value, $value, $selected === $value );
538 } else {
539 // groupless reason list
540 if ( $optgroup ) {
541 $options .= self::closeElement( 'optgroup' );
542 }
543 $options .= self::option( $value, $value, $selected === $value );
544 $optgroup = false;
545 }
546 }
547
548 if ( $optgroup ) {
549 $options .= self::closeElement( 'optgroup' );
550 }
551
552 $attribs = array();
553
554 if ( $name ) {
555 $attribs['id'] = $name;
556 $attribs['name'] = $name;
557 }
558
559 if ( $class ) {
560 $attribs['class'] = $class;
561 }
562
563 if ( $tabindex ) {
564 $attribs['tabindex'] = $tabindex;
565 }
566
567 return Xml::openElement( 'select', $attribs )
568 . "\n"
569 . $options
570 . "\n"
571 . Xml::closeElement( 'select' );
572 }
573
574 /**
575 * Shortcut for creating fieldsets.
576 *
577 * @param string|bool $legend Legend of the fieldset. If evaluates to false,
578 * legend is not added.
579 * @param string $content Pre-escaped content for the fieldset. If false,
580 * only open fieldset is returned.
581 * @param array $attribs Any attributes to fieldset-element.
582 *
583 * @return string
584 */
585 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
586 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
587
588 if ( $legend ) {
589 $s .= Xml::element( 'legend', null, $legend ) . "\n";
590 }
591
592 if ( $content !== false ) {
593 $s .= $content . "\n";
594 $s .= Xml::closeElement( 'fieldset' ) . "\n";
595 }
596
597 return $s;
598 }
599
600 /**
601 * Shortcut for creating textareas.
602 *
603 * @param string $name The 'name' for the textarea
604 * @param string $content Content for the textarea
605 * @param int $cols The number of columns for the textarea
606 * @param int $rows The number of rows for the textarea
607 * @param array $attribs Any other attributes for the textarea
608 *
609 * @return string
610 */
611 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
612 return self::element( 'textarea',
613 Html::getTextInputAttributes(
614 array(
615 'name' => $name,
616 'id' => $name,
617 'cols' => $cols,
618 'rows' => $rows
619 ) + $attribs
620 ),
621 $content, false );
622 }
623
624 /**
625 * Returns an escaped string suitable for inclusion in a string literal
626 * for JavaScript source code.
627 * Illegal control characters are assumed not to be present.
628 *
629 * @deprecated since 1.21; use Xml::encodeJsVar() or Xml::encodeJsCall() instead
630 * @param string $string String to escape
631 * @return string
632 */
633 public static function escapeJsString( $string ) {
634 // See ECMA 262 section 7.8.4 for string literal format
635 $pairs = array(
636 "\\" => "\\\\",
637 "\"" => "\\\"",
638 '\'' => '\\\'',
639 "\n" => "\\n",
640 "\r" => "\\r",
641
642 # To avoid closing the element or CDATA section
643 "<" => "\\x3c",
644 ">" => "\\x3e",
645
646 # To avoid any complaints about bad entity refs
647 "&" => "\\x26",
648
649 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
650 # Encode certain Unicode formatting chars so affected
651 # versions of Gecko don't misinterpret our strings;
652 # this is a common problem with Farsi text.
653 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
654 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
655 );
656
657 return strtr( $string, $pairs );
658 }
659
660 /**
661 * Encode a variable of arbitrary type to JavaScript.
662 * If the value is an XmlJsCode object, pass through the object's value verbatim.
663 *
664 * @note Only use this function for generating JavaScript code. If generating output
665 * for a proper JSON parser, just call FormatJson::encode() directly.
666 *
667 * @param mixed $value The value being encoded. Can be any type except a resource.
668 * @param bool $pretty If true, add non-significant whitespace to improve readability.
669 * @return string|bool String if successful; false upon failure
670 */
671 public static function encodeJsVar( $value, $pretty = false ) {
672 if ( $value instanceof XmlJsCode ) {
673 return $value->value;
674 }
675 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
676 }
677
678 /**
679 * Create a call to a JavaScript function. The supplied arguments will be
680 * encoded using Xml::encodeJsVar().
681 *
682 * @since 1.17
683 * @param string $name The name of the function to call, or a JavaScript expression
684 * which evaluates to a function object which is called.
685 * @param array $args The arguments to pass to the function.
686 * @param bool $pretty If true, add non-significant whitespace to improve readability.
687 * @return string|bool String if successful; false upon failure
688 */
689 public static function encodeJsCall( $name, $args, $pretty = false ) {
690 foreach ( $args as &$arg ) {
691 $arg = Xml::encodeJsVar( $arg, $pretty );
692 if ( $arg === false ) {
693 return false;
694 }
695 }
696
697 return "$name(" . ( $pretty
698 ? ( ' ' . implode( ', ', $args ) . ' ' )
699 : implode( ',', $args )
700 ) . ");";
701 }
702
703 /**
704 * Check if a string is well-formed XML.
705 * Must include the surrounding tag.
706 * This function is a DoS vector if an attacker can define
707 * entities in $text.
708 *
709 * @param string $text String to test.
710 * @return bool
711 *
712 * @todo Error position reporting return
713 */
714 private static function isWellFormed( $text ) {
715 $parser = xml_parser_create( "UTF-8" );
716
717 # case folding violates XML standard, turn it off
718 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
719
720 if ( !xml_parse( $parser, $text, true ) ) {
721 //$err = xml_error_string( xml_get_error_code( $parser ) );
722 //$position = xml_get_current_byte_index( $parser );
723 //$fragment = $this->extractFragment( $html, $position );
724 //$this->mXmlError = "$err at byte $position:\n$fragment";
725 xml_parser_free( $parser );
726 return false;
727 }
728
729 xml_parser_free( $parser );
730
731 return true;
732 }
733
734 /**
735 * Check if a string is a well-formed XML fragment.
736 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
737 * and can use HTML named entities.
738 *
739 * @param string $text
740 * @return bool
741 */
742 public static function isWellFormedXmlFragment( $text ) {
743 $html =
744 Sanitizer::hackDocType() .
745 '<html>' .
746 $text .
747 '</html>';
748
749 return Xml::isWellFormed( $html );
750 }
751
752 /**
753 * Replace " > and < with their respective HTML entities ( &quot;,
754 * &gt;, &lt;)
755 *
756 * @param string $in Text that might contain HTML tags.
757 * @return string Escaped string
758 */
759 public static function escapeTagsOnly( $in ) {
760 return str_replace(
761 array( '"', '>', '<' ),
762 array( '&quot;', '&gt;', '&lt;' ),
763 $in );
764 }
765
766 /**
767 * Generate a form (without the opening form element).
768 * Output optionally includes a submit button.
769 * @param array $fields Associative array, key is the name of a message that
770 * contains a description for the field, value is an HTML string
771 * containing the appropriate input.
772 * @param string $submitLabel The name of a message containing a label for
773 * the submit button.
774 * @param array $submitAttribs The attributes to add to the submit button
775 * @return string HTML form.
776 */
777 public static function buildForm( $fields, $submitLabel = null, $submitAttribs = array() ) {
778 $form = '';
779 $form .= "<table><tbody>";
780
781 foreach ( $fields as $labelmsg => $input ) {
782 $id = "mw-$labelmsg";
783 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
784
785 // TODO use a <label> here for accessibility purposes - will need
786 // to either not use a table to build the form, or find the ID of
787 // the input somehow.
788
789 $form .= Xml::tags( 'td', array( 'class' => 'mw-label' ), wfMessage( $labelmsg )->parse() );
790 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) )
791 . $input . Xml::closeElement( 'td' );
792 $form .= Xml::closeElement( 'tr' );
793 }
794
795 if ( $submitLabel ) {
796 $form .= Xml::openElement( 'tr' );
797 $form .= Xml::tags( 'td', array(), '' );
798 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) )
799 . Xml::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
800 . Xml::closeElement( 'td' );
801 $form .= Xml::closeElement( 'tr' );
802 }
803
804 $form .= "</tbody></table>";
805
806 return $form;
807 }
808
809 /**
810 * Build a table of data
811 * @param array $rows An array of arrays of strings, each to be a row in a table
812 * @param array $attribs An array of attributes to apply to the table tag [optional]
813 * @param array $headers An array of strings to use as table headers [optional]
814 * @return string
815 */
816 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
817 $s = Xml::openElement( 'table', $attribs );
818
819 if ( is_array( $headers ) ) {
820 $s .= Xml::openElement( 'thead', $attribs );
821
822 foreach ( $headers as $id => $header ) {
823 $attribs = array();
824
825 if ( is_string( $id ) ) {
826 $attribs['id'] = $id;
827 }
828
829 $s .= Xml::element( 'th', $attribs, $header );
830 }
831 $s .= Xml::closeElement( 'thead' );
832 }
833
834 foreach ( $rows as $id => $row ) {
835 $attribs = array();
836
837 if ( is_string( $id ) ) {
838 $attribs['id'] = $id;
839 }
840
841 $s .= Xml::buildTableRow( $attribs, $row );
842 }
843
844 $s .= Xml::closeElement( 'table' );
845
846 return $s;
847 }
848
849 /**
850 * Build a row for a table
851 * @param array $attribs An array of attributes to apply to the tr tag
852 * @param array $cells An array of strings to put in <td>
853 * @return string
854 */
855 public static function buildTableRow( $attribs, $cells ) {
856 $s = Xml::openElement( 'tr', $attribs );
857
858 foreach ( $cells as $id => $cell ) {
859 $attribs = array();
860
861 if ( is_string( $id ) ) {
862 $attribs['id'] = $id;
863 }
864
865 $s .= Xml::element( 'td', $attribs, $cell );
866 }
867
868 $s .= Xml::closeElement( 'tr' );
869
870 return $s;
871 }
872 }
873
874 /**
875 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
876 * interpret a given string as being a JavaScript expression, instead of string
877 * data.
878 *
879 * Example:
880 *
881 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
882 *
883 * Returns "a + b".
884 *
885 * @note As of 1.21, XmlJsCode objects cannot be nested inside objects or arrays. The sole
886 * exception is the $args argument to Xml::encodeJsCall() because Xml::encodeJsVar() is
887 * called for each individual element in that array.
888 *
889 * @since 1.17
890 */
891 class XmlJsCode {
892 public $value;
893
894 function __construct( $value ) {
895 $this->value = $value;
896 }
897 }