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