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