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