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