Adding messages for new global group 'sysadmin'. Brion, Tim, Kate and JeLuF are all...
[lhc/web/wiklou.git] / includes / Xml.php
1 <?php
2
3 /**
4 * Module of static functions for generating XML
5 */
6
7 class Xml {
8 /**
9 * Format an XML element with given attributes and, optionally, text content.
10 * Element and attribute names are assumed to be ready for literal inclusion.
11 * Strings are assumed to not contain XML-illegal characters; special
12 * characters (<, >, &) are escaped but illegals are not touched.
13 *
14 * @param $element String: element name
15 * @param $attribs Array: Name=>value pairs. Values will be escaped.
16 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
17 * @param $allowShortTag Bool: whether '' in $contents will result in a contentless closed tag
18 * @return string
19 */
20 public static function element( $element, $attribs = null, $contents = '', $allowShortTag = true ) {
21 $out = '<' . $element;
22 if( !is_null( $attribs ) ) {
23 $out .= self::expandAttributes( $attribs );
24 }
25 if( is_null( $contents ) ) {
26 $out .= '>';
27 } else {
28 if( $allowShortTag && $contents === '' ) {
29 $out .= ' />';
30 } else {
31 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
32 }
33 }
34 return $out;
35 }
36
37 /**
38 * Given an array of ('attributename' => 'value'), it generates the code
39 * to set the XML attributes : attributename="value".
40 * The values are passed to Sanitizer::encodeAttribute.
41 * Return null if no attributes given.
42 * @param $attribs Array of attributes for an XML element
43 */
44 private static function expandAttributes( $attribs ) {
45 $out = '';
46 if( is_null( $attribs ) ) {
47 return null;
48 } elseif( is_array( $attribs ) ) {
49 foreach( $attribs as $name => $val )
50 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
51 return $out;
52 } else {
53 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
54 }
55 }
56
57 /**
58 * Format an XML element as with self::element(), but run text through the
59 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
60 * is passed.
61 *
62 * @param $element String:
63 * @param $attribs Array: Name=>value pairs. Values will be escaped.
64 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
65 * @return string
66 */
67 public static function elementClean( $element, $attribs = array(), $contents = '') {
68 if( $attribs ) {
69 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
70 }
71 if( $contents ) {
72 wfProfileIn( __METHOD__ . '-norm' );
73 $contents = UtfNormal::cleanUp( $contents );
74 wfProfileOut( __METHOD__ . '-norm' );
75 }
76 return self::element( $element, $attribs, $contents );
77 }
78
79 /**
80 * This opens an XML element
81 *
82 * @param $element name of the element
83 * @param $attribs array of attributes, see Xml::expandAttributes()
84 * @return string
85 */
86 public static function openElement( $element, $attribs = null ) {
87 return '<' . $element . self::expandAttributes( $attribs ) . '>';
88 }
89
90 /**
91 * Shortcut to close an XML element
92 * @param $element element name
93 * @return string
94 */
95 public static function closeElement( $element ) { return "</$element>"; }
96
97 /**
98 * Same as Xml::element(), but does not escape contents. Handy when the
99 * content you have is already valid xml.
100 *
101 * @param $element element name
102 * @param $attribs array of attributes
103 * @param $contents content of the element
104 * @return string
105 */
106 public static function tags( $element, $attribs = null, $contents ) {
107 return self::openElement( $element, $attribs ) . $contents . "</$element>";
108 }
109
110 /**
111 * Build a drop-down box for selecting a namespace
112 *
113 * @param $selected Mixed: Namespace which should be pre-selected
114 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
115 * @param $hidden Mixed: Include hidden namespaces? [WTF? --RC]
116 * @param $element_name String: value of the "name" attribute of the select tag
117 * @return string
118 */
119 public static function namespaceSelector( $selected = '', $all = null, $hidden = false, $element_name = 'namespace' ) {
120 global $wgContLang;
121 $namespaces = $wgContLang->getFormattedNamespaces();
122 $options = array();
123
124 // Godawful hack... we'll be frequently passed selected namespaces
125 // as strings since PHP is such a shithole.
126 // But we also don't want blanks and nulls and "all"s matching 0,
127 // so let's convert *just* string ints to clean ints.
128 if( preg_match( '/^\d+$/', $selected ) ) {
129 $selected = intval( $selected );
130 }
131
132 if( !is_null( $all ) )
133 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) + $namespaces;
134 foreach( $namespaces as $index => $name ) {
135 if( $index < NS_MAIN )
136 continue;
137 if( $index === 0 )
138 $name = wfMsg( 'blanknamespace' );
139 $options[] = self::option( $name, $index, $index === $selected );
140 }
141
142 return Xml::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
143 'class' => 'namespaceselector' ) )
144 . "\n"
145 . implode( "\n", $options )
146 . "\n"
147 . Xml::closeElement( 'select' );
148 }
149
150 /**
151 * Create a date selector
152 *
153 * @param $selected Mixed: the month which should be selected, default ''
154 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
155 * @param $id String: Element identifier
156 * @return String: Html string containing the month selector
157 */
158 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
159 global $wgLang;
160 $options = array();
161 if( is_null( $selected ) )
162 $selected = '';
163 if( !is_null( $allmonths ) )
164 $options[] = self::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
165 for( $i = 1; $i < 13; $i++ )
166 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
167 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
168 . implode( "\n", $options )
169 . self::closeElement( 'select' );
170 }
171
172 /**
173 *
174 * @param $selected The language code of the selected language
175 * @param $customisedOnly If true only languages which have some content are listed
176 * @return array of label and select
177 */
178 public static function languageSelector( $selected, $customisedOnly = true ) {
179 global $wgContLanguageCode;
180 /**
181 * Make sure the site language is in the list; a custom language code
182 * might not have a defined name...
183 */
184 $languages = Language::getLanguageNames( $customisedOnly );
185 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
186 $languages[$wgContLanguageCode] = $wgContLanguageCode;
187 }
188 ksort( $languages );
189
190 /**
191 * If a bogus value is set, default to the content language.
192 * Otherwise, no default is selected and the user ends up
193 * with an Afrikaans interface since it's first in the list.
194 */
195 $selected = isset( $languages[$selected] ) ? $selected : $wgContLanguageCode;
196 $options = "\n";
197 foreach( $languages as $code => $name ) {
198 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
199 }
200
201 return array(
202 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
203 Xml::tags( 'select',
204 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
205 $options
206 )
207 );
208
209 }
210
211 /**
212 * Shortcut to make a span element
213 * @param $text content of the element, will be escaped
214 * @param $class class name of the span element
215 * @param $attribs other attributes
216 * @return string
217 */
218 public static function span( $text, $class, $attribs=array() ) {
219 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
220 }
221
222 /**
223 * Shortcut to make a specific element with a class attribute
224 * @param $text content of the element, will be escaped
225 * @param $class class name of the span element
226 * @param $tag element name
227 * @param $attribs other attributes
228 * @return string
229 */
230 public static function wrapClass( $text, $class, $tag='span', $attribs=array() ) {
231 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
232 }
233
234 /**
235 * Convenience function to build an HTML text input field
236 * @param $name value of the name attribute
237 * @param $size value of the size attribute
238 * @param $value value of the value attribute
239 * @param $attribs other attributes
240 * @return string HTML
241 */
242 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
243 return self::element( 'input', array(
244 'name' => $name,
245 'size' => $size,
246 'value' => $value ) + $attribs );
247 }
248
249 /**
250 * Convenience function to build an HTML password input field
251 * @param $name value of the name attribute
252 * @param $size value of the size attribute
253 * @param $value value of the value attribute
254 * @param $attribs other attributes
255 * @return string HTML
256 */
257 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
258 return self::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
259 }
260
261 /**
262 * Internal function for use in checkboxes and radio buttons and such.
263 * @return array
264 */
265 public static function attrib( $name, $present = true ) {
266 return $present ? array( $name => $name ) : array();
267 }
268
269 /**
270 * Convenience function to build an HTML checkbox
271 * @param $name value of the name attribute
272 * @param $checked Whether the checkbox is checked or not
273 * @param $attribs other attributes
274 * @return string HTML
275 */
276 public static function check( $name, $checked=false, $attribs=array() ) {
277 return self::element( 'input', array_merge(
278 array(
279 'name' => $name,
280 'type' => 'checkbox',
281 'value' => 1 ),
282 self::attrib( 'checked', $checked ),
283 $attribs ) );
284 }
285
286 /**
287 * Convenience function to build an HTML radio button
288 * @param $name value of the name attribute
289 * @param $value value of the value attribute
290 * @param $checked Whether the checkbox is checked or not
291 * @param $attribs other attributes
292 * @return string HTML
293 */
294 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
295 return self::element( 'input', array(
296 'name' => $name,
297 'type' => 'radio',
298 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
299 }
300
301 /**
302 * Convenience function to build an HTML form label
303 * @param $label text of the label
304 * @param $id
305 * @return string HTML
306 */
307 public static function label( $label, $id ) {
308 return self::element( 'label', array( 'for' => $id ), $label );
309 }
310
311 /**
312 * Convenience function to build an HTML text input field with a label
313 * @param $label text of the label
314 * @param $name value of the name attribute
315 * @param $id id of the input
316 * @param $size value of the size attribute
317 * @param $value value of the value attribute
318 * @param $attribs other attributes
319 * @return string HTML
320 */
321 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
322 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
323 return $label . '&nbsp;' . $input;
324 }
325
326 /**
327 * Same as Xml::inputLabel() but return input and label in an array
328 */
329 public static function inputLabelSep( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
330 return array(
331 Xml::label( $label, $id ),
332 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
333 );
334 }
335
336 /**
337 * Convenience function to build an HTML checkbox with a label
338 * @return string HTML
339 */
340 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
341 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
342 '&nbsp;' .
343 self::label( $label, $id );
344 }
345
346 /**
347 * Convenience function to build an HTML radio button with a label
348 * @return string HTML
349 */
350 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
351 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
352 '&nbsp;' .
353 self::label( $label, $id );
354 }
355
356 /**
357 * Convenience function to build an HTML submit button
358 * @param $value String: label text for the button
359 * @param $attribs Array: optional custom attributes
360 * @return string HTML
361 */
362 public static function submitButton( $value, $attribs=array() ) {
363 return self::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
364 }
365
366 /**
367 * Convenience function to build an HTML hidden form field.
368 * @param $name String: name attribute for the field
369 * @param $value String: value for the hidden field
370 * @param $attribs Array: optional custom attributes
371 * @return string HTML
372 */
373 public static function hidden( $name, $value, $attribs=array() ) {
374 return self::element( 'input', array(
375 'name' => $name,
376 'type' => 'hidden',
377 'value' => $value ) + $attribs );
378 }
379
380 /**
381 * Convenience function to build an HTML drop-down list item.
382 * @param $text String: text for this item
383 * @param $value String: form submission value; if empty, use text
384 * @param $selected boolean: if true, will be the default selected item
385 * @param $attribs array: optional additional HTML attributes
386 * @return string HTML
387 */
388 public static function option( $text, $value=null, $selected=false,
389 $attribs=array() ) {
390 if( !is_null( $value ) ) {
391 $attribs['value'] = $value;
392 }
393 if( $selected ) {
394 $attribs['selected'] = 'selected';
395 }
396 return self::element( 'option', $attribs, $text );
397 }
398
399 /**
400 * Build a drop-down box from a textual list.
401 *
402 * @param $name Mixed: Name and id for the drop-down
403 * @param $class Mixed: CSS classes for the drop-down
404 * @param $other Mixed: Text for the "Other reasons" option
405 * @param $list Mixed: Correctly formatted text to be used to generate the options
406 * @param $selected Mixed: Option which should be pre-selected
407 * @param $tabindex Mixed: Value of the tabindex attribute
408 * @return string
409 */
410 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = Null ) {
411 $options = '';
412 $optgroup = false;
413
414 $options = self::option( $other, 'other', $selected === 'other' );
415
416 foreach ( explode( "\n", $list ) as $option) {
417 $value = trim( $option );
418 if ( $value == '' ) {
419 continue;
420 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
421 // A new group is starting ...
422 $value = trim( substr( $value, 1 ) );
423 if( $optgroup ) $options .= self::closeElement('optgroup');
424 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
425 $optgroup = true;
426 } elseif ( substr( $value, 0, 2) == '**' ) {
427 // groupmember
428 $value = trim( substr( $value, 2 ) );
429 $options .= self::option( $value, $value, $selected === $value );
430 } else {
431 // groupless reason list
432 if( $optgroup ) $options .= self::closeElement('optgroup');
433 $options .= self::option( $value, $value, $selected === $value );
434 $optgroup = false;
435 }
436 }
437 if( $optgroup ) $options .= self::closeElement('optgroup');
438
439 $attribs = array();
440 if( $name ) {
441 $attribs['id'] = $name;
442 $attribs['name'] = $name;
443 }
444 if( $class ) {
445 $attribs['class'] = $class;
446 }
447 if( $tabindex ) {
448 $attribs['tabindex'] = $tabindex;
449 }
450 return Xml::openElement( 'select', $attribs )
451 . "\n"
452 . $options
453 . "\n"
454 . Xml::closeElement( 'select' );
455 }
456
457 /**
458 * Shortcut for creating fieldsets.
459 *
460 * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
461 * @param $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
462 * @param $attribs Any attributes to fieldset-element.
463 */
464 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
465 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
466 if ( $legend ) {
467 $s .= Xml::element( 'legend', null, $legend ) . "\n";
468 }
469 if ( $content !== false ) {
470 $s .= $content . "\n";
471 $s .= Xml::closeElement( 'fieldset' ) . "\n";
472 }
473
474 return $s;
475 }
476
477 /**
478 * Shortcut for creating textareas.
479 *
480 * @param $name The 'name' for the textarea
481 * @param $content Content for the textarea
482 * @param $cols The number of columns for the textarea
483 * @param $rows The number of rows for the textarea
484 * @param $attribs Any other attributes for the textarea
485 */
486 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
487 return self::element( 'textarea',
488 array( 'name' => $name,
489 'id' => $name,
490 'cols' => $cols,
491 'rows' => $rows
492 ) + $attribs,
493 $content, false );
494 }
495
496 /**
497 * Returns an escaped string suitable for inclusion in a string literal
498 * for JavaScript source code.
499 * Illegal control characters are assumed not to be present.
500 *
501 * @param $string String to escape
502 * @return String
503 */
504 public static function escapeJsString( $string ) {
505 // See ECMA 262 section 7.8.4 for string literal format
506 $pairs = array(
507 "\\" => "\\\\",
508 "\"" => "\\\"",
509 '\'' => '\\\'',
510 "\n" => "\\n",
511 "\r" => "\\r",
512
513 # To avoid closing the element or CDATA section
514 "<" => "\\x3c",
515 ">" => "\\x3e",
516
517 # To avoid any complaints about bad entity refs
518 "&" => "\\x26",
519
520 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
521 # Encode certain Unicode formatting chars so affected
522 # versions of Gecko don't misinterpret our strings;
523 # this is a common problem with Farsi text.
524 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
525 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
526 );
527 return strtr( $string, $pairs );
528 }
529
530 /**
531 * Encode a variable of unknown type to JavaScript.
532 * Arrays are converted to JS arrays, objects are converted to JS associative
533 * arrays (objects). So cast your PHP associative arrays to objects before
534 * passing them to here.
535 */
536 public static function encodeJsVar( $value ) {
537 if ( is_bool( $value ) ) {
538 $s = $value ? 'true' : 'false';
539 } elseif ( is_null( $value ) ) {
540 $s = 'null';
541 } elseif ( is_int( $value ) ) {
542 $s = $value;
543 } elseif ( is_array( $value ) ) {
544 $s = '[';
545 foreach ( $value as $elt ) {
546 if ( $s != '[' ) {
547 $s .= ', ';
548 }
549 $s .= self::encodeJsVar( $elt );
550 }
551 $s .= ']';
552 } elseif ( is_object( $value ) ) {
553 $s = '{';
554 foreach ( (array)$value as $name => $elt ) {
555 if ( $s != '{' ) {
556 $s .= ', ';
557 }
558 $s .= '"' . self::escapeJsString( $name ) . '": ' .
559 self::encodeJsVar( $elt );
560 }
561 $s .= '}';
562 } else {
563 $s = '"' . self::escapeJsString( $value ) . '"';
564 }
565 return $s;
566 }
567
568
569 /**
570 * Check if a string is well-formed XML.
571 * Must include the surrounding tag.
572 *
573 * @param $text String: string to test.
574 * @return bool
575 *
576 * @todo Error position reporting return
577 */
578 public static function isWellFormed( $text ) {
579 $parser = xml_parser_create( "UTF-8" );
580
581 # case folding violates XML standard, turn it off
582 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
583
584 if( !xml_parse( $parser, $text, true ) ) {
585 //$err = xml_error_string( xml_get_error_code( $parser ) );
586 //$position = xml_get_current_byte_index( $parser );
587 //$fragment = $this->extractFragment( $html, $position );
588 //$this->mXmlError = "$err at byte $position:\n$fragment";
589 xml_parser_free( $parser );
590 return false;
591 }
592 xml_parser_free( $parser );
593 return true;
594 }
595
596 /**
597 * Check if a string is a well-formed XML fragment.
598 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
599 * and can use HTML named entities.
600 *
601 * @param $text String:
602 * @return bool
603 */
604 public static function isWellFormedXmlFragment( $text ) {
605 $html =
606 Sanitizer::hackDocType() .
607 '<html>' .
608 $text .
609 '</html>';
610 return Xml::isWellFormed( $html );
611 }
612
613 /**
614 * Replace " > and < with their respective HTML entities ( &quot;,
615 * &gt;, &lt;)
616 *
617 * @param $in String: text that might contain HTML tags.
618 * @return string Escaped string
619 */
620 public static function escapeTagsOnly( $in ) {
621 return str_replace(
622 array( '"', '>', '<' ),
623 array( '&quot;', '&gt;', '&lt;' ),
624 $in );
625 }
626
627 /**
628 * Generate a form (without the opening form element).
629 * Output optionally includes a submit button.
630 * @param $fields Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
631 * @param $submitLabel A message containing a label for the submit button.
632 * @return string HTML form.
633 */
634 public static function buildForm( $fields, $submitLabel = null ) {
635 $form = '';
636 $form .= "<table><tbody>";
637
638 foreach( $fields as $labelmsg => $input ) {
639 $id = "mw-$labelmsg";
640
641 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
642 $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
643 $form .= Xml::openElement( 'td' ) . $input . Xml::closeElement( 'td' );
644 $form .= Xml::closeElement( 'tr' );
645 }
646
647 $form .= "</tbody></table>";
648
649 if ($submitLabel) {
650 $form .= Xml::submitButton( wfMsg($submitLabel) );
651 }
652
653 return $form;
654 }
655 }
656
657 class XmlSelect {
658 protected $options = array();
659 protected $default = false;
660 protected $attributes = array();
661
662 public function __construct( $name = false, $id = false, $default = false ) {
663 if ( $name ) $this->setAttribute( 'name', $name );
664 if ( $id ) $this->setAttribute( 'id', $id );
665 if ( $default ) $this->default = $default;
666 }
667
668 public function setDefault( $default ) {
669 $this->default = $default;
670 }
671
672 public function setAttribute( $name, $value ) {
673 $this->attributes[$name] = $value;
674 }
675
676 public function addOption( $name, $value = false ) {
677 $value = $value ? $value : $name;
678 $this->options[] = Xml::option( $name, $value, $value === $this->default );
679 }
680
681 public function getHTML() {
682 return Xml::tags( 'select', $this->attributes, implode( "\n", $this->options ) );
683 }
684
685 }