Some fixes to avoid Xml::element call with null content when we actually want
[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:
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 if( is_null( $attribs ) ) {
45 return null;
46 } else {
47 $out = '';
48 foreach( $attribs as $name => $val ) {
49 $out .= ' ' . $name . '="' . Sanitizer::encodeAttribute( $val ) . '"';
50 }
51 return $out;
52 }
53 }
54
55 /**
56 * Format an XML element as with self::element(), but run text through the
57 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
58 * is passed.
59 *
60 * @param $element String:
61 * @param $attribs Array: Name=>value pairs. Values will be escaped.
62 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
63 * @return string
64 */
65 public static function elementClean( $element, $attribs = array(), $contents = '') {
66 if( $attribs ) {
67 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
68 }
69 if( $contents ) {
70 wfProfileIn( __METHOD__ . '-norm' );
71 $contents = UtfNormal::cleanUp( $contents );
72 wfProfileOut( __METHOD__ . '-norm' );
73 }
74 return self::element( $element, $attribs, $contents );
75 }
76
77 /** This open an XML element */
78 public static function openElement( $element, $attribs = null ) {
79 return '<' . $element . self::expandAttributes( $attribs ) . '>';
80 }
81
82 // Shortcut
83 public static function closeElement( $element ) { return "</$element>"; }
84
85 /**
86 * Same as <link>element</link>, but does not escape contents. Handy when the
87 * content you have is already valid xml.
88 */
89 public static function tags( $element, $attribs = null, $contents ) {
90 return self::openElement( $element, $attribs ) . $contents . "</$element>";
91 }
92
93 /**
94 * Create a namespace selector
95 *
96 * @param $selected Mixed: the namespace which should be selected, default ''
97 * @param $allnamespaces String: value of a special item denoting all namespaces. Null to not include (default)
98 * @param $includehidden Bool: include hidden namespaces?
99 * @return String: Html string containing the namespace selector
100 */
101 public static function namespaceSelector($selected = '', $allnamespaces = null, $includehidden=false) {
102 global $wgContLang;
103 if( $selected !== '' ) {
104 if( is_null( $selected ) ) {
105 // No namespace selected; let exact match work without hitting Main
106 $selected = '';
107 } else {
108 // Let input be numeric strings without breaking the empty match.
109 $selected = intval( $selected );
110 }
111 }
112 $s = "\n<select id='namespace' name='namespace' class='namespaceselector'>\n";
113 $arr = $wgContLang->getFormattedNamespaces();
114 if( !is_null($allnamespaces) ) {
115 $arr = array($allnamespaces => wfMsg('namespacesall')) + $arr;
116 }
117 foreach ($arr as $index => $name) {
118 if ($index < NS_MAIN) continue;
119
120 $name = $index !== 0 ? $name : wfMsg('blanknamespace');
121
122 if ($index === $selected) {
123 $s .= "\t" . self::element("option",
124 array("value" => $index, "selected" => "selected"),
125 $name) . "\n";
126 } else {
127 $s .= "\t" . self::element("option", array("value" => $index), $name) . "\n";
128 }
129 }
130 $s .= "</select>\n";
131 return $s;
132 }
133
134 /**
135 *
136 * @param $language The language code of the selected language
137 * @param $customisedOnly If true only languages which have some content are listed
138 * @return array of label and select
139 */
140 public static function languageSelector( $selected, $customisedOnly = true ) {
141 global $wgContLanguageCode;
142 /**
143 * Make sure the site language is in the list; a custom language code
144 * might not have a defined name...
145 */
146 $languages = Language::getLanguageNames( $customisedOnly );
147 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
148 $languages[$wgContLanguageCode] = $wgContLanguageCode;
149 }
150 ksort( $languages );
151
152 /**
153 * If a bogus value is set, default to the content language.
154 * Otherwise, no default is selected and the user ends up
155 * with an Afrikaans interface since it's first in the list.
156 */
157 $selected = isset( $languages[$selected] ) ? $selected : $wgContLanguageCode;
158 $options = "\n";
159 foreach( $languages as $code => $name ) {
160 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
161 }
162
163 return array(
164 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
165 Xml::tags( 'select',
166 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
167 $options
168 )
169 );
170
171 }
172
173 public static function span( $text, $class, $attribs=array() ) {
174 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
175 }
176
177 /**
178 * Convenience function to build an HTML text input field
179 * @return string HTML
180 */
181 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
182 return self::element( 'input', array(
183 'name' => $name,
184 'size' => $size,
185 'value' => $value ) + $attribs );
186 }
187
188 /**
189 * Convenience function to build an HTML password input field
190 * @return string HTML
191 */
192 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
193 return self::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
194 }
195
196 /**
197 * Internal function for use in checkboxes and radio buttons and such.
198 * @return array
199 */
200 public static function attrib( $name, $present = true ) {
201 return $present ? array( $name => $name ) : array();
202 }
203
204 /**
205 * Convenience function to build an HTML checkbox
206 * @return string HTML
207 */
208 public static function check( $name, $checked=false, $attribs=array() ) {
209 return self::element( 'input', array_merge(
210 array(
211 'name' => $name,
212 'type' => 'checkbox',
213 'value' => 1 ),
214 self::attrib( 'checked', $checked ),
215 $attribs ) );
216 }
217
218 /**
219 * Convenience function to build an HTML radio button
220 * @return string HTML
221 */
222 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
223 return self::element( 'input', array(
224 'name' => $name,
225 'type' => 'radio',
226 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
227 }
228
229 /**
230 * Convenience function to build an HTML form label
231 * @return string HTML
232 */
233 public static function label( $label, $id ) {
234 return self::element( 'label', array( 'for' => $id ), $label );
235 }
236
237 /**
238 * Convenience function to build an HTML text input field with a label
239 * @return string HTML
240 */
241 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
242 return Xml::label( $label, $id ) .
243 '&nbsp;' .
244 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs );
245 }
246
247 /**
248 * Convenience function to build an HTML checkbox with a label
249 * @return string HTML
250 */
251 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
252 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
253 '&nbsp;' .
254 self::label( $label, $id );
255 }
256
257 /**
258 * Convenience function to build an HTML radio button with a label
259 * @return string HTML
260 */
261 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
262 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
263 '&nbsp;' .
264 self::label( $label, $id );
265 }
266
267 /**
268 * Convenience function to build an HTML submit button
269 * @param $value String: label text for the button
270 * @param $attribs Array: optional custom attributes
271 * @return string HTML
272 */
273 public static function submitButton( $value, $attribs=array() ) {
274 return self::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
275 }
276
277 /**
278 * Convenience function to build an HTML hidden form field.
279 * @todo Document $name parameter.
280 * @param $name FIXME
281 * @param $value String: label text for the button
282 * @param $attribs Array: optional custom attributes
283 * @return string HTML
284 */
285 public static function hidden( $name, $value, $attribs=array() ) {
286 return self::element( 'input', array(
287 'name' => $name,
288 'type' => 'hidden',
289 'value' => $value ) + $attribs );
290 }
291
292 /**
293 * Convenience function to build an HTML drop-down list item.
294 * @param $text String: text for this item
295 * @param $value String: form submission value; if empty, use text
296 * @param $selected boolean: if true, will be the default selected item
297 * @param $attribs array: optional additional HTML attributes
298 * @return string HTML
299 */
300 public static function option( $text, $value=null, $selected=false,
301 $attribs=array() ) {
302 if( !is_null( $value ) ) {
303 $attribs['value'] = $value;
304 }
305 if( $selected ) {
306 $attribs['selected'] = 'selected';
307 }
308 return self::element( 'option', $attribs, $text );
309 }
310
311 /**
312 * Returns an escaped string suitable for inclusion in a string literal
313 * for JavaScript source code.
314 * Illegal control characters are assumed not to be present.
315 *
316 * @param string $string
317 * @return string
318 */
319 public static function escapeJsString( $string ) {
320 // See ECMA 262 section 7.8.4 for string literal format
321 $pairs = array(
322 "\\" => "\\\\",
323 "\"" => "\\\"",
324 '\'' => '\\\'',
325 "\n" => "\\n",
326 "\r" => "\\r",
327
328 # To avoid closing the element or CDATA section
329 "<" => "\\x3c",
330 ">" => "\\x3e",
331
332 # To avoid any complaints about bad entity refs
333 "&" => "\\x26",
334 );
335 return strtr( $string, $pairs );
336 }
337
338 /**
339 * Encode a variable of unknown type to JavaScript.
340 * Doesn't support hashtables just yet.
341 */
342 public static function encodeJsVar( $value ) {
343 if ( is_bool( $value ) ) {
344 $s = $value ? 'true' : 'false';
345 } elseif ( is_null( $value ) ) {
346 $s = 'null';
347 } elseif ( is_int( $value ) ) {
348 $s = $value;
349 } elseif ( is_array( $value ) ) {
350 $s = '[';
351 foreach ( $value as $name => $elt ) {
352 if ( $s != '[' ) {
353 $s .= ', ';
354 }
355 $s .= self::encodeJsVar( $elt );
356 }
357 $s .= ']';
358 } else {
359 $s = '"' . self::escapeJsString( $value ) . '"';
360 }
361 return $s;
362 }
363
364
365 /**
366 * Check if a string is well-formed XML.
367 * Must include the surrounding tag.
368 *
369 * @param $text String: string to test.
370 * @return bool
371 *
372 * @todo Error position reporting return
373 */
374 public static function isWellFormed( $text ) {
375 $parser = xml_parser_create( "UTF-8" );
376
377 # case folding violates XML standard, turn it off
378 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
379
380 if( !xml_parse( $parser, $text, true ) ) {
381 //$err = xml_error_string( xml_get_error_code( $parser ) );
382 //$position = xml_get_current_byte_index( $parser );
383 //$fragment = $this->extractFragment( $html, $position );
384 //$this->mXmlError = "$err at byte $position:\n$fragment";
385 xml_parser_free( $parser );
386 return false;
387 }
388 xml_parser_free( $parser );
389 return true;
390 }
391
392 /**
393 * Check if a string is a well-formed XML fragment.
394 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
395 * and can use HTML named entities.
396 *
397 * @param $text String:
398 * @return bool
399 */
400 public static function isWellFormedXmlFragment( $text ) {
401 $html =
402 Sanitizer::hackDocType() .
403 '<html>' .
404 $text .
405 '</html>';
406 return Xml::isWellFormed( $html );
407 }
408
409 /**
410 * Replace " > and < with their respective HTML entities ( &quot;,
411 * &gt;, &lt;)
412 *
413 * @param $in String: text that might contain HTML tags.
414 * @return string Escaped string
415 */
416 public static function escapeTagsOnly( $in ) {
417 return str_replace(
418 array( '"', '>', '<' ),
419 array( '&quot;', '&gt;', '&lt;' ),
420 $in );
421 }
422 }
423 ?>